Skip to content

Instantly share code, notes, and snippets.

@wyojustin
Created October 11, 2020 16:37
Embed
What would you like to do?
Convert an image to a mono-bit dithered image.
from PIL import ImageOps
from PIL import Image
import numpy as np
import pylab as pl
import sys
usage = '''USAGE:
python dither.py <input_image_fn> [dim]
'''
if len(sys.argv) < 2:
print(usage)
sys.exit()
img_fn = sys.argv[1]
DIM = 5
if len(sys.argv) > 2:
DIM = float(sys.argv[2])
img = Image.open(img_fn)
size = img.size
##max(size) / reduce = 1000
reduce = min(size) / 1000
print(size[0]//reduce, size[1] // reduce)
img.thumbnail((size[0]//reduce, size[1]//reduce))
img.convert('1').save('out_1.bmp')
rgb = img.split()
if len(rgb) == 3:
r,g,b = img.split()
else:
r,g,b,a = img.split()
zero = r.point(lambda i: 0)
if True:
r = r.point(lambda i:i/DIM)
g = g.point(lambda i:i/DIM)
b = b.point(lambda i:i/DIM)
white = Image.merge('RGB', (r, g, b))
neg = ImageOps.invert(white)
one_neg = neg.convert('1')
out_fn = '%s_1_neg.bmp' % img_fn[:-4]
one_neg.save(out_fn)
print('wrote', out_fn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment