


Detailed explanation of how to use Python to convert images into character paintings
This article mainly introduces the example of converting pictures into character paintings in Python. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
Character painting is really interesting. Character painting is generated by replacing the pixels in the picture with characters.
But pixels have different colors. How do we encode pixels with different colors into corresponding characters?
Conversion method:
Convert color images into grayscale images
According to the color depth RGB value (the value range is from 0 to 255, where 0 is black and 255 is white)
Involves your favorite character set
According to the character set sequence and character set length, the RGB value is encoded into the corresponding character.
RGB
RGB color mode is based on three color channels: red (R), green (G), and blue (B). RGB represents the colors of the three channels of red, green, and blue. This standard includes almost all colors that can be perceived by human vision.
Normally, RGB each has 256 levels of brightness, expressed numerically from 0, 1, 2... until 255. Note that although the highest number is 255, 0 is also one of the values, so there are 256 levels in total.
Grayscale image
Grayscale image refers to an image that only contains brightness information and does not contain color information, just like the black and white photos we usually see: brightness From dark to light, the change is continuous.
Therefore, to represent a grayscale image, the brightness value needs to be quantized. It is usually divided into 256 levels from 0 to 255, of which 0 is the darkest (completely black) and 255 is the brightest (completely white). In the method of expressing color, in addition to RGB, the conversion formula from RGB in color pictures to gray value Gray is:
#在PIL中,从模式“RGB”转换为“L”模式(灰度模式) Gray = 0.299R+0.587G+0.114B
For example, we use 26 lowercase English letters as Our character set. The character set capacity is 26 (the value interval width corresponding to one character = 256/character set length)
The interval width here is 256/26=9.8),
The corresponding relationship between gray and the character set :
Gray interval corresponding characters
[0.0, 9.8)这|a [9.8, 19.6)|b [19.6, 29.4)|c ...|... [225.6, 235.4]|x [235.4, 245.2]|y [245.2, 255.0]|z
RGB conversion function
char_string = 'abcdefghijklmnopqrstuvwxyz' def rgb2char(r, g, b): length = len(char_string) gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) # 每个字符对应的gray值区间宽度 unit = (256.0 + 1) / length # gray值对应到char_string中的位置(索引值) idx = int(gray / unit) return char_string[idx]
Preprocessing
If the size is too large or too small, we will not be able to recognize the character paintings when we open the txt file. So you need to adjust the image size appropriately first. Note here that you can change the scaling coefficient delta coefficient as needed
from PIL import Image #预处理(将图片尺寸压缩,并转为灰度图) def preprocess(img_path,delta=100): img = Image.open(img_path) # 获取图片尺寸 width, height = img.size # 获取图片最大边的长度 if width > height: max = width else: max = height # 伸缩倍数scale scale = max / delta width, height = int(width / scale), int(height / scale) img = img.resize((width, height)) return img
Picture to character
Read the picture and obtain it according to the coordinates An rgb tuple of the pixel, encoded as the characters
def img2char(img_obj, savepath): txt = '' width, height = img_obj.size # 获取像素点的rgb元组值,如(254, 0, 0),并将其转化为字符 for i in range(height): line = '' for j in range(width): line += rgb2char(*img_obj.getpixel((j, i))) txt = txt + line + '\n' # 保存字符画 with open(savepath, 'w+', encoding='utf-8') as f: f.write(txt) img_obj = preprocess(img_path) img2char(img_obj, savepath)
Insert image
The above is the detailed content of Detailed explanation of how to use Python to convert images into character paintings. For more information, please follow other related articles on the PHP Chinese website!

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

The methods to debug the shebang problem include: 1. Check the shebang line to make sure it is the first line of the script and there are no prefixed spaces; 2. Verify whether the interpreter path is correct; 3. Call the interpreter directly to run the script to isolate the shebang problem; 4. Use strace or trusts to track the system calls; 5. Check the impact of environment variables on shebang.

Pythonlistscanbemanipulatedusingseveralmethodstoremoveelements:1)Theremove()methodremovesthefirstoccurrenceofaspecifiedvalue.2)Thepop()methodremovesandreturnsanelementatagivenindex.3)Thedelstatementcanremoveanitemorslicebyindex.4)Listcomprehensionscr

Pythonlistscanstoreanydatatype,includingintegers,strings,floats,booleans,otherlists,anddictionaries.Thisversatilityallowsformixed-typelists,whichcanbemanagedeffectivelyusingtypechecks,typehints,andspecializedlibrarieslikenumpyforperformance.Documenti

Pythonlistssupportnumerousoperations:1)Addingelementswithappend(),extend(),andinsert().2)Removingitemsusingremove(),pop(),andclear().3)Accessingandmodifyingwithindexingandslicing.4)Searchingandsortingwithindex(),sort(),andreverse().5)Advancedoperatio

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
