Skip to content

Instantly share code, notes, and snippets.

@Random832
Created April 23, 2021 20:38
Show Gist options
  • Save Random832/599e27f1aa336edbc9998b60f2a4399e to your computer and use it in GitHub Desktop.
Save Random832/599e27f1aa336edbc9998b60f2a4399e to your computer and use it in GitHub Desktop.
bayer dithering experiment
import numpy as np
from PIL import Image
import sys
im = Image.open('chart.png')
im2 = np.array(im)
factor = 127 # 84
threshmap = ((np.array([
0, 8, 2,10,
12, 4,14, 6,
3,11, 1, 9,
15, 7,13, 5]) / 15.0 - 0.5) * factor).reshape(4, 4, 1)
#print(threshmap)
h, w, c = im2.shape
#print(h, w, c)
threshbig = np.tile(threshmap, ((h+3)//4, (w+3)//4, 3))[:h, :w, :c]
#print(threshbig.shape == im2.shape)
#threshbig = ((np.random.random_sample(im2.shape) - 0.5) * 127)
im3 = im2 + threshbig
tmp = im3.astype('uint8')
tmp[im3 < 0] = 0
tmp[im3 > 255] = 255
tmp = Image.fromarray(tmp, 'RGB')
tmp.save('intermediate.png')
im3 = np.reshape(im3, (h, w, 1, 3))
palette = np.array([[0,0,0],[0,0,128],[0,128,0],[0,128,128],[128,0,0],[128,0,128],[128,128,0],[192,192,192],[128,128,128],[0,0,255],[0,255,0],[0,255,255],[255,0,0],[255,0,255],[255,255,0], [255,255,255]], dtype='uint8')
#palette = np.array([
# [0,0,0],[0,0,170],[0,170,0],[0,170,170],[170,0,0],[170,0,170],[0,0,0],[170,170,170],
# [0,0,0],[85,85,255],[85,255,85],[85,255,255],[255,85,85],[255,85,255],[255,255,85],[255,255,255],
# ], dtype='uint8')
#palette = []
#for r in range(0,256,85):
# for g in range(0,256,85):
# for b in range(0,256,85):
# palette.append((r, g, b))
palette = np.array(palette, dtype='uint8')
palette = palette.reshape(1, 1, len(palette), 3)
#print(im3.shape)
#print(palette.shape)
im4 = im3 - palette
im4 *= im4
im4 = im4.sum(3) # eliminate fourth axis which is rgb channel
im5 = im4.argmin(2).astype('uint8')
#print(im5.shape)
#spec7 = (im2 - 192).astype('float32')
#spec7 *= spec7
#spec7 = spec7.sum(2)
#im5[spec7 < 64] = 7
#print(im5[im5 == 7])
#palette = palette.reshape(16, 3)
#palette[7] = 192,192,192
im6 = Image.fromarray(im5, 'P')
im6.putpalette(palette.flatten())
#print(im6)
print(im6.getpalette())
im6.save('chart16.png')
sys.exit(0)
#def dither(channel, maxval):
# output = np.zeros(channel.shape, bool)
# #threshmap = np.array([[0, 2], [3, 1]])
# mh, mw = threshmap.shape
# threshmax = np.amax(threshmap)
# for (y, x), v in np.ndenumerate(channel):
# thresh = threshmap[y % mh, x % mw]
# rthresh = ((thresh + 0.5) / (threshmax + 1))*maxval
# output[y, x] = v > rthresh # is this correct?
# return output
#
## non-dithered output for sanity check
#
#cv2.imwrite('chart_gamut.png', cv2.merge((b+i, g+i, r+i)))
#
#outimage = cv2.merge((b2, g2, r2))
#cv2.imwrite('chart_dithered.png', outimage)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment