Made a small function to convert the Image to ASCII characters
#2
by
Xialah
- opened
Hi,
Thank you very much for the model! In return, I've made a small function to convert the Image to ASCII characters.
Best,
from PIL import Image
ASCII_RAMP = "@%#*+=-:. "
def image_to_ascii(img: Image.Image, width=100, invert=False, ramp=ASCII_RAMP):
# 1) Normalize
if img.mode in ("RGBA", "P"):
img = img.convert("RGB")
# 2) Resize with char aspect compensation (~2:1 height)
w, h = img.size
new_h = max(1, int(h / w * width * 0.5))
img = img.resize((width, new_h), Image.BICUBIC).convert("L")
# 3) Pixels as list -> slicing OK
pixels = list(img.getdata())
# 4) Map to ASCII
chars = ramp[::-1] if invert else ramp
n = len(chars) - 1
lines = []
for y in range(img.height):
row_pixels = pixels[y*img.width:(y+1)*img.width] # now this slices fine
row = "".join(chars[int(p / 255 * n)] for p in row_pixels)
lines.append(row)
return "\n".join(lines)