Home  >  Article  >  Backend Development  >  How to use Python to convert pictures into character paintings

How to use Python to convert pictures into character paintings

王林
王林forward
2023-05-17 14:34:061528browse

First of all, there is a problem, which is to simulate grayscale. Here is a formula:

1
Gray = 0.2126 × R + 0.7152 × G + 0.0722 × B

This will be easier to handle. Of course, in RGB mode, although the color range of 256x256x256 is converted into a grayscale range of 256, the characters are still not in one-to-one correspondence. We can solve this problem by using one character to correspond to multiple grayscales.

Remember to install the PIL library first, including:

If it is Python 2, run pip install PIL.

If it is Python 3, run pip install pillow.

Let’s go directly to the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from PIL import Image
#设置显示的字符集
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")    
WIDTH = 130
HEIGHT = 50
def get_char(r,g,b,alpha = 256):
    if alpha == 0:
        return ' '
    length = len(ascii_char)
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
    unit = (255.0 + 1)/length
    return ascii_char[int(gray/unit)]
if __name__ == '__main__':
    img = "E:/WindowsDocuments/G7/Desktop/1.png"
    im = Image.open(img)
    im = im.resize((WIDTH,HEIGHT), Image.NEAREST)
    txt = ""
    for i in range(HEIGHT):
        for j in range(WIDTH):
            txt += get_char(*im.getpixel((j,i)))
        txt += '\n'
    print(txt)

If you want to output to a file, you can add the file name you want to save in the definition part OUTPUT = 'output.txt', and then write it at the end:

1
2
with open(OUTPUT, 'w') as f:
    f.write(txt)

Finally, we got this:

How to use Python to convert pictures into character paintings

The above is the detailed content of How to use Python to convert pictures into character paintings. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete