Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Get images from CLI (or randomly from Instagram pics shared under creative commons liscensing) & glitch 'em
from PIL import Image, ImageStat, ImageEnhance
from random import *
import numpy as np
from itertools import *
import requests
import simplejson
from cStringIO import StringIO
from images2gif import writeGif
import os, sys
class glitcher:
@staticmethod
def ditherBayer3(pixels,size):
threshold_maps = [
[[3, 7, 4], [6, 1, 9], [2, 8, 5]],
[[1, 9, 3, 11], [13, 5, 15, 7], [4, 12, 2, 10], [16, 8, 14, 6]],
[[1, 49, 13, 61, 4, 52, 16, 64], [33, 17, 45, 29, 36, 20, 48, 32], [9, 57, 5, 53, 12, 60, 8, 56], [41, 25, 37, 21, 44, 28, 40, 24], [3, 51, 15, 63, 2, 50, 14, 62], [35, 19, 47, 31, 34, 18, 46, 30], [11, 59, 7, 55, 10, 58, 6, 54], [43, 27, 39, 23, 42, 26, 38, 22]]
]
threshold_map = threshold_maps[randint(0,len(threshold_maps)-1)]
map_size = len(threshold_map)
map_sum = sum(max(threshold_map,key=sum)) + 1
for i in range(size[0]): # for every pixel:
for j in range(size[1]):
px = pixels[i,j]
map_loc = threshold_map[i%map_size][j%map_size]
r = ((px[0]) * map_sum) / 255
g = ((px[1]) * map_sum) / 255
b = ((px[2]) * map_sum) / 255
r = 0 if r < map_loc else 255
g = 0 if g < map_loc else 255
b = 0 if b < map_loc else 255
pixels[i,j] = (r,g,b)
#
# @staticmethod
# def ditherBayer(pixels,size):
# threshold_maps = [
# [[3, 7, 4], [6, 1, 9], [2, 8, 5]],
# [[1, 9, 3, 11], [13, 5, 15, 7], [4, 12, 2, 10], [16, 8, 14, 6]],
# [[1, 49, 13, 61, 4, 52, 16, 64], [33, 17, 45, 29, 36, 20, 48, 32], [9, 57, 5, 53, 12, 60, 8, 56], [41, 25, 37, 21, 44, 28, 40, 24], [3, 51, 15, 63, 2, 50, 14, 62], [35, 19, 47, 31, 34, 18, 46, 30], [11, 59, 7, 55, 10, 58, 6, 54], [43, 27, 39, 23, 42, 26, 38, 22]]
# ]
# threshold_map = threshold_maps[int(random() * len(threshold_maps))]
# map_size = len(threshold_map)
# for i in range(size[0]): # for every pixel:
# for j in range(size[1]):
# px = pixels[i,j]
# gray = 0.3 * px[0] + 0.59 * px[1] + 0.11 * px[2]
# scaled = (gray * 17) / 255
# val = 0 if scaled < threshold_map[i%map_size][j%map_size] else 255
# pixels[i,j] = (val, val, val)
#
# @staticmethod
# def ditherRandom(pixels,size):
# for i in range(size[0]): # for every pixel:
# for j in range(size[1]):
# px = pixels[i,j]
# gray = 0.3 * px[0] + 0.59 * px[1] + 0.11 * px[2]
# val = 0 if gray < randint(0,128) else 255
# pixels[i,j] = (val, val, val)
#
@staticmethod
def ditherRandom2(pixels,size):
for i in range(size[0]): # for every pixel:
for j in range(size[1]):
pixels[i,j] = tuple(map(lambda x: 0 if x < randint(0,128) else 255, pixels[i,j]))
@staticmethod
def colorReverseSort(pixels,size):
for i in range(size[0]): # for every pixel:
for j in range(size[1]):
pixels[i,j] = tuple(sorted(pixels[i,j],None,None,True))
@staticmethod
def colorSort(pixels,size):
for i in range(size[0]): # for every pixel:
for j in range(size[1]):
pixels[i,j] = tuple(sorted(pixels[i,j]))
@staticmethod
def colorShuffle(pixels,size):
for i in range(size[0]): # for every pixel:
for j in range(size[1]):
px = list(pixels[i,j])
shuffle(px)
pixels[i,j] = tuple(px)
@staticmethod
def colorPush(pixels,size):
shifter = [2,2,1]
shuffle(shifter)
for i in range(size[0]): # for every pixel:
for j in range(size[1]):
pixels[i,j] = tuple(map(lambda x,y: int(x/y),pixels[i,j],shifter))
@staticmethod
def ditherBits(pixels, size):
masks = [0xA0,0xB0,0xC0,0xD0, 0xE0, 0xF0]
mask = masks[randint(0,len(masks)-1)]
for i in range(size[0]): # for every pixel:
for j in range(size[1]):
pixels[i,j] = tuple(map(lambda x: x & mask, pixels[i,j]))
@staticmethod
def ditherRandomBits(pixels, size):
mask = randint(10,245)
for i in range(size[0]): # for every pixel:
for j in range(size[1]):
pixels[i,j] = tuple(map(lambda x: x & mask, pixels[i,j]))
@staticmethod
def colorShift(pixels, size):
mask = randint(10,245)
for i in range(size[0]): # for every pixel:
for j in range(size[1]):
pix = list(pixels[i,j])
pix.insert(0,pix.pop())
pixels[i,j] = tuple(pix)
@staticmethod
def pixelate(pixels,size):
pix = 5
for i in range(0,size[0],pix): # for every pixel:
for j in range(0,size[1],pix):
for x in range(pix):
for y in range(pix):
pixels[(i+x)%size[0],(j+y)%size[1]] = pixels[i,j]
@staticmethod
def badsignal(pixels,size):
pix = randint(4,16)
for i in range(0,size[0],pix): # for every pixel:
for j in range(0,size[1],pix):
if randrange(100) > 33:
i += pix
j += pix
continue
px = pixels[i%size[0],j%size[1]]
colorchoice = randrange(100)
signal = [choice([0,1]),choice([0,1]),choice([0,1])]
for x in range(pix):
for y in range(pix):
if colorchoice > 25:
pixels[(i+x)%size[0],(j+y)%size[1]] = px
else:
pixels[(i+x)%size[0],(j+y)%size[1]] = tuple(map((lambda a,b: a & 0x40 if b else a & 0xC0),pixels[i%size[0],j%size[1]],signal))
@staticmethod
def slicer(pixels,size):
pix = []
for i in range(size[0]): # for every pixel:
for j in range(size[1]):
pix += pixels[i,j]
limit = size[0] * size[1]
for i in range(randint(1,3)):
cutend = randint(len(pix)/2,len(pix))
cutstart = int(cutend/2)
cutlen = cutend - cutstart
A = [x for x in islice(pix,0,cutstart)]
B = [x for x in islice(pix,cutstart,cutend)]
C = [x for x in islice(pix,cutend,limit)]
order = randint(0,3)
bac = [B,A,C]
shuffle(bac)
pix = bac[0] + bac[1] + bac[2]
index = 0
for x in range(size[0]): # for every pixel:
for y in range(size[1]):
index = index % (limit-2)
pixels[x,y] = (pix[index],pix[index+1],pix[index+2])
index += 3
# @staticmethod
# def hexSort(pixels,size):
# pix = []
# for i in range(size[0]): # for every pixel:
# for j in range(size[1]):
# pix += pixels[i,j]
#
# pix.sort()
# index = 0
# for x in range(size[0]): # for every pixel:
# for y in range(size[1]):
# pixels[x,y] = (pix[index],pix[index+1],pix[index+2])
# index += 3
@staticmethod
def jinker(pixels,size):
pix = []
for i in range(size[0]): # for every pixel:
for j in range(size[1]):
pix += pixels[i,j]
limit = size[0] * size[1]
for i in range(randint(1,17)):
pix.insert(randint(0,len(pix)),randint(0,255))
index = 0
for x in range(size[0]): # for every pixel:
for y in range(size[1]):
pixels[x,y] = (pix[index],pix[index+1],pix[index+2])
index += 3
def colors( im ):
stat = ImageStat.Stat(im)
return np.average(stat.median)
def brightness( im ):
stat = ImageStat.Stat(im)
return np.average(stat.mean)
def fromInstagram():
r = requests.get('http://i-am-cc.org/api/instagram_photo/?format=json')
c = r.content
j = simplejson.loads(c)
imgs = []
for i in j['objects']:
item = tuple((i['image_standard_resolution'],i['link'],i['license_info']['full_name']))
if None not in item:
imgs.append(item)
im = choice(imgs)
ir = requests.get(im[0])
ic = StringIO(ir.content)
subject = "!m Original by [%s](%s)" % (im[2], im[1])
print subject
glitch(ic)
#test(ic)
def glitch(image,name="output"):
methods = dir(glitcher)
img = Image.open(image)
pixels = img.load() # create the pixel map
gif = [img.copy()]
i = 0
functs = ""
while i < randrange(10)+5:
funct = choice(methods[2:len(methods)])
if funct[0:2] != "__":
functs += funct + " "
getattr(glitcher,funct)(pixels,img.size)
gif.append(img.copy())
i += 1
print functs
b = brightness(img)
if b < 20 or b > 240:
print "## RETRY"
glitch(image)
else:
img.show()
img.save(name+".jpg","JPEG")
writeGif(name+".gif",gif,duration=0.2)
def test(image):
img = Image.open(image)
pixels = img.load() # create the pixel map
img.show()
glitcher.hexSort(pixels,img.size)
img.show()
def fromCLI(filename):
img = Image.open(str(filename))
pixels = img.load() # create the pixel map
glitch(img)
if __name__ == "__main__":
args = sys.argv
print args
if len(args) >= 2:
fromCLI(str(args[1]))
else:
fromInstagram()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment