Created
October 21, 2022 16:11
-
-
Save Reyuu/9e3aa08825e58794b77ecd47f902ad7a to your computer and use it in GitHub Desktop.
Convert image to text characters
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 PIL import Image | |
import math | |
# open and load image | |
img = Image.open("image.jpg") | |
img.load() | |
# convert to grayscale | |
img = img.convert("L") | |
# define density string, try out different ones! | |
#density_string = "◙◘■▩●▦▣◚◛◕▨▧◉▤◐◒▮◍◑▼▪◤▬◗◭◖◈◎◮◊◫▰◄◯□▯▷▫▽◹△◁▸▭◅▵◌▱▹▿◠◃◦◟◞◜" | |
#density_string = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. " | |
#density_string = "@QB#NgWM8RDHdOKq9$6khEPXwmeZaoS2yjufF]}{tx1zv7lciL/\\|?*>r^;:_\"~,'.-`" | |
density_string = "@$BGOUou{[(|!=*+-\"'. " | |
cutout_white = 3 | |
cutout_black = 0 | |
# incorporate cutouts to tweak the brightness ramp | |
density_string = " " * cutout_black + density_string + " " * cutout_white | |
# map values | |
# i'm too stupid for this, check out the SO below | |
# https://stackoverflow.com/a/45389903 | |
def mapFromTo(x,a,b,c,d): | |
y=(x-a)/(b-a)*(d-c)+c | |
return y | |
buffer = "" | |
for y in range(img.height): | |
row = "" | |
for x in range(img.width): | |
# since image is grayscale, it only has 1 value - how bright (or dark) a pixel is | |
brightness = img.getpixel((x, y)) | |
# map the value to a range and floor it -> this will become a character from density string | |
mapped_value = math.floor(mapFromTo(brightness, 0, 255, 0, len(density_string))) | |
# get character from density string | |
char = density_string[mapped_value] | |
# add space and character to a row, the space helps with formatting | |
row += " "+char | |
# add the row to a buffer with a newline | |
buffer += f"{row}\n" | |
# save output as a HTML, for easier viewing | |
with open("main.html", "w", encoding="utf-8") as f: | |
buffer = """ | |
<html> | |
<head> | |
<style> | |
html{ | |
background-color: black; | |
color: white; | |
} | |
</style> | |
</head> | |
<body> | |
<pre>""" + buffer + """ | |
</pre> | |
</body> | |
""" | |
f.write(buffer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment