The other day, I found an interesting site called ASCII Camera. In this way, it gets the camera image from the browser and converts it to an ASCII character string.
I thought that I could make it myself, so I decided to make a program to convert images to ASCII art.
The mechanism is as follows.
Python and OpenCV make these things pretty easy.
The path of the image to be read should be obtained by input. This will convert it to grayscale and the gray will contain the density (0-255) for each pixel.
import cv2
imgpath = input("Path: ")
img = cv2.imread(imgpath)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
You need to determine the ASCII characters for each pixel density (0-255), but there are not 256 ASCII characters that you can actually use. I couldn't help it, so I carefully selected 64 characters to use, and decided to select the characters by dividing the density into 4 parts. For example, if the density is 0 to 3, it is "M", if it is 252 to 255, it is "(blank)", and so on.
Below are 64 letters arranged in "high density" order.
MWN$@%#&B89EGA6mK5HRkbYT43V0JL7gpaseyxznocv?jIftr1li*=-~^`':;,.
It was quite difficult to decide this order. The order is just decided by appearance, so it's super suitable.
The conversion process looks like this.
colorset = "MWN$@%#&B89EGA6mK5HRkbYT43V0JL7gpaseyxznocv?jIftr1li*=-~^`':;,. "
for gray2 in gray:
output += "\n"
for dark in gray2:
output += colorset[dark // 4] * 2
You can get the colorset index just right by dividing the density by 4 and truncating it. Since the aspect ratio of ASCII characters is 2: 1, the characters to be written are doubled.
The completed program looks like this. The result is output to a file.
import cv2
colorset = "MWN$@%#&B89EGA6mK5HRkbYT43V0JL7gpaseyxznocv?jIftr1li*=-~^`':;,. "
imgpath = input("Path:")
img = cv2.imread(imgpath)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
output = ""
for gray2 in gray:
output += "\n"
for dark in gray2:
output += colorset[dark // 4] * 2
with open("output.txt", mode="w") as f:
f.write(output)
I will try to convert my icon (this ↓). Result is...
Like this. I was surprised that I was able to convert it properly.
Next, I will try a free image of the natural scenery of northern England received from Mr. Pakutaso converted to 300 x 200px. Result is...
Yeah ... I think it's a good line.
Finally, I got it from This person does not exist, a site where AI automatically generates a face photo. Let's convert this image to 250x250px and run it.
Result is...
It feels pretty good! This is good ... it was worth the effort ...
That's why it was possible with just 12 lines of code. I first touched OpenCV this time, but I didn't find it so convenient. It might be interesting to try the same thing in Unicode with 256 characters.
Recommended Posts