Skip to content

Instantly share code, notes, and snippets.

@ncarboni
Last active January 23, 2025 13:24
Show Gist options
  • Select an option

  • Save ncarboni/e9e878bc4a58f3df3ece12b3c301f2a1 to your computer and use it in GitHub Desktop.

Select an option

Save ncarboni/e9e878bc4a58f3df3ece12b3c301f2a1 to your computer and use it in GitHub Desktop.
Pixelate effect on a image
from PIL import Image, ImageFilter
import numpy as np
from scipy.cluster.vq import kmeans2
import os
import sys
def create_pixel_art(image_path, colors=16, pixel_size=8, width=64):
img = Image.open(image_path)
aspect = img.width / img.height
new_height = int(width / aspect)
img = img.resize((width, new_height), Image.LANCZOS)
pixels = np.array(img)
flat_pixels = pixels.reshape((-1, 3))
palette, labels = kmeans2(flat_pixels.astype(float), colors, minit='points')
quantized = palette[labels].reshape(pixels.shape)
result = Image.fromarray(quantized.astype('uint8'))
result = result.resize((width * pixel_size, new_height * pixel_size), Image.NEAREST)
output_path = image_path.rsplit('.', 1)[0] + '_pixel_art.png'
result.save(output_path, 'PNG')
print(f"Saved pixel art to: {output_path}")
return output_path
def create_lego_art(image_path, stud_size=16, colors=16, width=48):
img = Image.open(image_path)
aspect = img.width / img.height
new_height = int(width / aspect)
img = img.resize((width, new_height), Image.LANCZOS)
pixels = np.array(img)
flat_pixels = pixels.reshape((-1, 3))
palette, labels = kmeans2(flat_pixels.astype(float), colors, minit='points')
quantized = palette[labels].reshape(pixels.shape)
result = Image.fromarray(quantized.astype('uint8'))
large = result.resize((width * stud_size, new_height * stud_size), Image.NEAREST)
large = large.filter(ImageFilter.SMOOTH)
output_path = image_path.rsplit('.', 1)[0] + '_lego.png'
large.save(output_path, 'PNG')
print(f"Saved LEGO art to: {output_path}")
return output_path
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python script.py [pixel|lego] <image_path>")
sys.exit(1)
style = sys.argv[1].lower()
image_path = sys.argv[2]
if style == 'pixel':
create_pixel_art(image_path)
elif style == 'lego':
create_lego_art(image_path)
else:
print("Invalid style. Use 'pixel' or 'lego'")
# Use in the terminal as
# python pixel.py {pixel,lego} image_path
#
# parameters to change:
# colors=8, pixel_size=8, width=60
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment