Last active
July 10, 2024 04:48
-
-
Save AlexanderHott/c3292cb80d865699625fb0020746e20a to your computer and use it in GitHub Desktop.
Count the number of pixels in an image.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Count the number of pixels in an image. | |
Usage | |
----- | |
python ./main.py path/to/image | |
""" | |
import sys | |
from PIL import Image # pip install Pillow | |
CLEAR = "\033[0m" | |
WIDTH = 105 | |
HEIGHT = 213 | |
def rgb_to_ansi(r, g, b): | |
s = f"\033[48;2;{r};{g};{b}m" | |
brightness = 0.299 * r + 0.587 * g + 0.114 * b | |
if brightness > 127: | |
s = "\033[38;2;0;0;0m" + s | |
return s | |
if __name__ == "__main__": | |
if len(sys.argv) < 2: | |
print(f"Usage: {sys.argv[0]} <image>") | |
exit(1) | |
img = Image.open(sys.argv[1]) | |
img = img.resize((WIDTH, HEIGHT), Image.Resampling.NEAREST) # NEAREST for pixel art | |
num_colors = 20 | |
img = img.quantize(colors=num_colors, method=2, kmeans=0) | |
scaled = img.resize((WIDTH*16, HEIGHT*16), Image.Resampling.NEAREST) | |
scaled.save(f"new-{sys.argv[1].split('.')[0]}.png", format="PNG") | |
palette = img.getpalette() | |
if palette is None: | |
print("Error, no palette") | |
exit(1) | |
# img.show() | |
color_counts = img.getcolors(maxcolors=img.size[0]*img.size[1]) | |
if color_counts is None: | |
print("Too many colors in the image to count. Increase the maxcolors value.") | |
exit(1) | |
color_count_dict = {color: count for count, color in color_counts} | |
for color_index, count in sorted(color_count_dict.items(), key=lambda i: i[1]): | |
r, g, b = palette[color_index * 3 : color_index * 3 + 3] | |
print(f"{rgb_to_ansi(r,g,b)}({r} {g} {b}): {count} pixels {CLEAR}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment