Created
October 30, 2014 02:00
-
-
Save erinaceous/6816f7d35f7e072b045e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2 | |
# vim: set tabstop=4 shiftwidth=4 textwidth=79 cc=72,79: | |
""" | |
jpeglitcher: Read a JPEG one byte at a time, | |
occasionally making a mistake. | |
Original Author: Owain Jones [github.com/erinaceous] [contact@odj.me] | |
""" | |
from __future__ import print_function | |
import subprocess | |
import argparse | |
import random | |
import struct | |
import time | |
import cv2 | |
def parse_args(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-c', '--cmd', default=False) | |
parser.add_argument('-l', '--loop', action='store_true', default=False) | |
parser.add_argument('-o', '--output', default='/tmp/glitch.jpg') | |
parser.add_argument('-p', '--prob', type=float, default=0.001) | |
parser.add_argument('-r', '--range', type=int, default=1) | |
parser.add_argument('-s', '--sleep', type=float, default=0.01) | |
parser.add_argument('-v', '--viewer', action='store_true', default=False) | |
parser.add_argument('input') | |
return parser.parse_args() | |
def glitchy_read(inputpath, outputpath, probability=0.001, maxrange=100): | |
inputfile = open(inputpath, 'rb') | |
outputfile = open(outputpath, 'w+b') | |
data = inputfile.read(1) | |
currange = maxrange | |
junk = 0 | |
while data != b'': | |
if random.random() < probability: | |
if maxrange > 1: | |
currange = int(random.random() * maxrange) | |
junk = 1 - int(random.random() * 2) | |
outputfile.write(struct.pack('%dB' % currange, | |
*[int(random.random() * 255) for x in range(0, | |
currange)])) | |
else: | |
outputfile.write(data) | |
data = inputfile.read(currange + junk) | |
def preview(img, sleeptime=1): | |
try: | |
previmg = cv2.imread(img) | |
cv2.imshow('jpeglitcher', previmg) | |
cv2.waitKey(int(sleeptime)) | |
except cv2.error: | |
pass | |
if __name__ == '__main__': | |
args = parse_args() | |
if args.viewer: | |
import cv2 | |
if args.loop: | |
while True: | |
glitchy_read(args.input, args.output, args.prob, args.range) | |
if args.viewer: | |
preview(args.output) | |
if args.cmd is not False: | |
subprocess.call( | |
args.cmd.format(infile=args.input, outfile=args.output), | |
shell=True | |
) | |
time.sleep(args.sleep) | |
else: | |
glitchy_read(args.input, args.output, args.prob, args.range) | |
if args.viewer: | |
preview(args.output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment