How to use Python to convert pictures into character paintings

王林
Release: 2023-05-17 14:34:06
forward
1645 people have browsed it

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

1
Copy after login
Gray = 0.2126 × R + 0.7152 × G + 0.0722 × B
Copy after login

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
Copy after login
from PIL import Image
#设置显示的字符集
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`&#39;. ")    
WIDTH = 130
HEIGHT = 50
def get_char(r,g,b,alpha = 256):
    if alpha == 0:
        return &#39; &#39;
    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__ == &#39;__main__&#39;:
    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 += &#39;\n&#39;
    print(txt)
Copy after login

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
Copy after login
with open(OUTPUT, &#39;w&#39;) as f:
    f.write(txt)
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template