“The ancients’ knowledge is weak, but their Kung Fu can only be achieved when they are young and old.”
Character imaging, the original image is processed by Python to generate an image completely composed of pure characters. Indoorsman brother official account, character imaging makes your photos not leak. Flying rabbit’s brother’s public address has more reptiles actual combat, special effects teaching, welcome attention. If this article can bring you a little help, hope to fly brother rabbit a key three links, support, thank you, little partners.
catalogue
1、 Special effects Preview
Before treatment
After treatment
When the detail is enlarged
2、 Program principle
-
Map the 256 gray level of the picture to the corresponding characters
-
That is, the RGB value is converted to the corresponding character
-
Then write the characters to the file
Do you understand?
3、 Program source code
#!/usr/bin/env python
# encoding: utf-8
from PIL import Image
class charsetPicture:
'''
This is a main Class, the file contains all documents.
One document contains paragraphs that have several sentences
It loads the original file and converts the original file to new content
Then the new content will be saved by this class
'''
def __init__(self):
self.char = list("[email protected]%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
self.width = 160
self.height = 60
def hello(self):
'''
This is a welcome speech
:return: self
'''
print('*' * 50)
Print ('* 18 +' convert picture to character picture ')
print(' ' * 5 + 'Author: autofelix Date: 2022-01-07 13:14')
print('*' * 50)
return self
def get_char(self, r, g, b, alpha=256):
'''
Map 256 grayscale to 70 characters, that is, the function of RGB value to character
: Alpha: transparency
:return: self
'''
if alpha == 0:
return ' '
length = len(self.char)
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unit = (256.0 + 1) / length
return self.char[int(gray / unit)]
def run(self):
'''
The program entry
'''
im = Image.open('assets/aaa.jpeg')
im = im.resize((self.width, self.height), Image.NEAREST)
txt = ''
for i in range(self.height):
for j in range(self.width):
txt += self.get_char(*im.getpixel((j, i)))
txt += '\n'
print(txt)
with open('handler.txt', 'w') as f:
f.write(txt)
if __name__ == '__main__':
charsetPicture().hello().run()