I made a program to convert images into ASCII art with Python and OpenCV

Introduction

The other day, I found an interesting site called ASCII Camera. picture_pc_3c309a4cbd82ecc52c545a04da630a0b.png In this way, it gets the camera image from the browser and converts it to an ASCII character string.

I thought that I could make it myself, so I decided to make a program to convert images to ASCII art.

How it works

The mechanism is as follows.

  1. Convert the image to grayscale
  2. Get the color intensity of each pixel and determine the text accordingly
  3. Line break for each column

Python and OpenCV make these things pretty easy.

Convert to grayscale

The path of the image to be read should be obtained by input. This will convert it to grayscale and the gray will contain the density (0-255) for each pixel.

import cv2

imgpath = input("Path: ")
img = cv2.imread(imgpath)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Determine ASCII characters

You need to determine the ASCII characters for each pixel density (0-255), but there are not 256 ASCII characters that you can actually use. I couldn't help it, so I carefully selected 64 characters to use, and decided to select the characters by dividing the density into 4 parts. For example, if the density is 0 to 3, it is "M", if it is 252 to 255, it is "(blank)", and so on.

Below are 64 letters arranged in "high density" order.

MWN$@%#&B89EGA6mK5HRkbYT43V0JL7gpaseyxznocv?jIftr1li*=-~^`':;,. 

It was quite difficult to decide this order. The order is just decided by appearance, so it's super suitable.

The conversion process looks like this.


colorset = "MWN$@%#&B89EGA6mK5HRkbYT43V0JL7gpaseyxznocv?jIftr1li*=-~^`':;,. "

for gray2 in gray:
    output += "\n"
    for dark in gray2:
        output += colorset[dark // 4] * 2

You can get the colorset index just right by dividing the density by 4 and truncating it. Since the aspect ratio of ASCII characters is 2: 1, the characters to be written are doubled.

Complete

The completed program looks like this. The result is output to a file.

import cv2

colorset = "MWN$@%#&B89EGA6mK5HRkbYT43V0JL7gpaseyxznocv?jIftr1li*=-~^`':;,. "

imgpath = input("Path:")
img = cv2.imread(imgpath)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
output = ""

for gray2 in gray:
    output += "\n"
    for dark in gray2:
        output += colorset[dark // 4] * 2

with open("output.txt", mode="w") as f:
    f.write(output)

I will try to convert my icon (this ↓). nico.png Result is...

スクリーンショット (148).png

Like this. I was surprised that I was able to convert it properly.

Next, I will try a free image of the natural scenery of northern England received from Mr. Pakutaso converted to 300 x 200px. elly20160701265118_TP_V.jpg Result is...

スクリーンショット (146).png Yeah ... I think it's a good line.

Finally, I got it from This person does not exist, a site where AI automatically generates a face photo. image.jpg Let's convert this image to 250x250px and run it.

Result is...

スクリーンショット (147).png It feels pretty good! This is good ... it was worth the effort ...

in conclusion

That's why it was possible with just 12 lines of code. I first touched OpenCV this time, but I didn't find it so convenient. It might be interesting to try the same thing in Unicode with 256 characters.

References

Recommended Posts

I made a program to convert images into ASCII art with Python and OpenCV
I made a program to collect images in tweets that I liked on twitter with Python
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
I made a network to convert black and white images to color images (pix2pix)
I made a LINE BOT with Python and Heroku
I want to exe and distribute a program that resizes images Python3 + pyinstaller
I made a package to filter time series with python
I wrote a program quickly to study DI with Python ①
I made a fortune with Python.
Image processing with Python (I tried binarizing it into a mosaic art of 0 and 1)
Convert images passed to Jason Statham-like in Python to ASCII art
Convert video to black and white with ffmpeg + python + opencv
I made a daemon with Python
I made a server with Python socket and ssl and tried to access it from a browser
I made a simple circuit with Python (AND, OR, NOR, etc.)
I made a library to easily read config files with Python
How to make a surveillance camera (Security Camera) with Opencv and Python
I made a Nyanko tweet form with Python, Flask and Heroku
I tried to make a periodical process with Selenium and Python
I tried to create Bulls and Cows with a shell program
[Python] Try to recognize characters from images with OpenCV and pyocr
I made a payroll program in Python!
I made a character counter with Python
Capturing images with Pupil, python and OpenCV
I made a Hex map with Python
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a neuron simulator with Python
I made a tool to automatically browse multiple sites with Selenium (Python)
I made a CLI tool to convert images in each directory to PDF
I tried to discriminate a 6-digit number with a number discrimination application made with python
I made a script in python to convert .md files to Scrapbox format
I made a program to input what I ate and display calories and sugar
I made a tool to convert Jupyter py to ipynb with VS Code
I made a program to check the size of a file in Python
I made a competitive programming glossary with Python
I made a weather forecast bot-like with Python.
I made a GUI application with Python + PyQt5
Convert PDFs to images in bulk with Python
I made a Twitter fujoshi blocker with Python ①
I want to make a game with Python
[Python] I made a Youtube Downloader with Tkinter.
I want to write to a file with Python
I made a Caesar cryptographic program in Python.
I made a bin picking game with Python
I made a Mattermost bot with Python (+ Flask)
I ran GhostScript with python, split the PDF into pages, and converted it to a JPEG image.
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
[ES Lab] I tried to develop a WEB application with Python and Flask ②
I made a module in C language to filter images loaded by Python
A story that I was addicted to when I made SFTP communication with python
Introduction to AI creation with Python! Part 3 I tried to classify and predict images with a convolutional neural network (CNN)
I generated a lot of images like Google Calendar favicon with Python and incorporated it into Vue's project
I made a program in Python that reads CSV data of FX and creates a large amount of chart images
I made a system that automatically decides whether to run tomorrow with Python and adds it to Google Calendar.
I made a Twitter BOT with GAE (python) (with a reference)
I made a prime number generation program in Python
I want to handle optimization with python and cplex
I tried to draw a route map with Python
I made a net news notification app with Python