Created
December 16, 2021 20:40
-
-
Save dmitmel/ef3930f0f662ba20633b8f1eb0126522 to your computer and use it in GitHub Desktop.
This file contains 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
from typing import cast | |
from PIL import Image, ImageColor, ImageEnhance | |
import itertools | |
import math | |
import sys | |
def range_map( | |
x: float, from_start: float, from_end: float, to_start: float, to_end: float | |
) -> float: | |
return (x - from_start) * (to_end - to_start) / (from_end - from_start) + to_start | |
def clamp(x: float, start: float, end: float) -> float: | |
return min(end, max(start, x)) | |
dog_image = Image.open(sys.argv[1]) | |
SIZE = 20 | |
dog_image = dog_image.resize((SIZE, SIZE), Image.LANCZOS) | |
background = Image.new('RGBA', dog_image.size, (0, 0, 0)) | |
composite_img = Image.alpha_composite(background, dog_image).convert("RGB") | |
composite_img = ImageEnhance.Contrast(composite_img).enhance(1.5) | |
composite_img = ImageEnhance.Sharpness(composite_img).enhance(1.8) | |
composite_img = ImageEnhance.Color(composite_img).enhance(0.8) | |
# composite_img = ImageEnhance.Brightness(composite_img).enhance(1.1) | |
# box_chars = ["░", "▒", "▓", "█"] | |
box_chars = ["▒", "▓", "█"] | |
# box_chars = ["a", "b", "c", "d"] | |
# minecraft_palette = [ | |
# '#000000', '#0000AA', '#00AA00', '#00AAAA', '#AA0000', '#AA00AA', '#FFAA00', '#AAAAAA', | |
# '#555555', '#5555FF', '#55FF55', '#55FFFF', '#FF5555', '#FF55FF', '#FFFF55', '#FFFFFF', '#DDD605' | |
# ] | |
# minecraft_palette = cast( | |
# list[tuple[int, int, int]], list(map(ImageColor.getrgb, minecraft_palette)) | |
# ) | |
# palette_image = Image.new("P", (1, 1)) | |
# palette_image.putpalette( | |
# list( | |
# itertools.chain. | |
# from_iterable(minecraft_palette + [(0, 0, 0)] * (0x100 - len(minecraft_palette))) | |
# ) | |
# ) | |
# quantized_image = composite_img.quantize(palette=palette_image, dither=Image.NONE) | |
grayscale_image = composite_img.convert("L") | |
img_w, img_h = dog_image.size | |
for y in range(img_h): | |
s = '' | |
for x in range(img_w): | |
# r, g, b = minecraft_palette[quantized_image.getpixel((x, y))] | |
r, g, b = composite_img.getpixel((x, y)) | |
l = grayscale_image.getpixel((x, y)) | |
# r, g, b = l, l, l | |
# char = box_chars[int(clamp(range_map(l, 80, 150, 0, 1), 0, 1) * (len(box_chars) - 1))] | |
char = box_chars[-1] | |
# s += f"\x1b[38;2;{r};{g};{b}m" + char + char | |
s += f"§#{r:02x}{g:02x}{b:02x}" + char | |
# s += char | |
print(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment