Skip to content

Instantly share code, notes, and snippets.

@StrikingLoo
Last active July 24, 2022 19:21
Show Gist options
  • Save StrikingLoo/481717106a5c9790d8a8fe2687fb7087 to your computer and use it in GitHub Desktop.
Save StrikingLoo/481717106a5c9790d8a8fe2687fb7087 to your computer and use it in GitHub Desktop.
from PIL import Image
import numpy as np
import sys
image = Image.open(sys.argv[1])
image_data = np.asarray(image)
for i in range(image_data.shape[0]):
for j in range(image_data.shape[1]):
oldpixel = image_data[i][j]
newpixel = find_closest_palette_color(oldpixel[:3])
image_data[i][j][:3] = newpixel
if oldpixel.shape[0] < 4 or oldpixel[3] > 0:
quant_error = oldpixel[:3] - newpixel
quant_error = quant_error/16
j_not_out_of_bounds = (j < image_data.shape[1] -1)
if i < image_data.shape[0] -1:
image_data[i + 1][j ][:3] = image_data[i + 1][j ][:3] + quant_error * 5
if j > 0:
image_data[i + 1][j - 1][:3] = image_data[i + 1][j - 1][:3] + quant_error * 3
if j_not_out_of_bounds:
image_data[i + 1][j + 1][:3] = image_data[i + 1][j + 1][:3] + quant_error
if j_not_out_of_bounds:
image_data[i ][j + 1][:3] = image_data[i ][j + 1][:3] + quant_error * 7
#taking only 3 values and leaving fourth the same so this works for RGBA images like .png
old_image = np.asarray(image)
output_image = Image.fromarray(image_data)
output_image.save(sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment