Home Backend Development Python Tutorial Detailed explanation of how to use Python to convert images into character paintings

Detailed explanation of how to use Python to convert images into character paintings

Aug 22, 2017 pm 01:24 PM
python picture accomplish

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
Copy after login

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
Copy after login

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]
Copy after login

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
Copy after login

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)
Copy after login

Insert image

##Change char_string and transform the effect you want

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles