First of all to clear the idea, the image is composed of pixels, different pixels have different colors (RGB), so since we want to convert to character painting, the most straightforward way is to use a string instead of pixels, that is, different strings to represent different pixels. In addition to the picture is generally color, and acsii (generally printed on the terminal bar) are black and white, at this time to introduce another concept:
Gray value: Refers to the color depth of black and white image midpoint, the range is generally from 0 to 255, White 255, black 0, so black and white pictures are also called grayscale images.
The idea here is clear, and what we have to do is two things:
1. Map each pixel (color image with RGB) to each grayscale value ...
2. Map grayscale values to each string ...
So we also need to convert the RGB to grayscale value of the pixel from the formula: Grayscale value = 0.2126 * r + 0.7152 * g + 0.0722 * B.
The code is as follows:
1 fromPILImportImage2 3Ascii_chars = List ("[Email protected]%8&wm#*oahkbdpqwmzo0qlcjuyxzcvunxrjft/\| () 1{}[]?-_+~<>i!li;:,\ "^".")#the character set used to replace pixels ...4 5 defGet_chars (R, G, B, alpha = 256):6 GlobalAscii_chars7 ifAlpha = =0:8 return ' '9Length =Len (ascii_chars)TenGray = Int (0.2126 * r + 0.7152 * g + 0.0722 *b) OneUnit = Alpha/length#distribute 256 pixels to characters ... A returnAscii_chars[int (gray/unit)] - - the -ImagePath ="/users/zhangzhimin/ascii_dora.png" -Outputheight = 70 -Outputwidth = 100 + - +IMG =Image.open (ImagePath) AIMG =img.resize ((Outputwidth, outputheight)) at - -TXT ="" - forYinchRange (outputheight): - forXinchRange (outputwidth): -TXT + = get_chars (*Img.getpixel ((x, y))) inTXT + ='\ n' - to Print(TXT)
The effect is probably this:
It is worth mentioning that only a few layers of simple graphics will have a good effect, if you want to parse complex images suggest increasing the number of strings and the size of the display ...
Thank the lab building for providing such an interesting programming exercise ...
Image processing Extension: picture-to-character painting (ASCII)