In [79]:
import cv2
See here, a tiny image of the football. The goal (dohohoho) is to transform this image into ascii art.
Tools used:
OpenCV for image reading, and the built-in numpy array of OpenCV.
Images are typically represented by an array of numbers in the form of [R,G,B]
Example: [0,255,17]
That would be a more or less green pixel.
A football it is ideal for working with grayscale since it is already black and white. A grayscale array of numbers is easier to work with because instead of 3 colors/values, we're working with one value per pixel (essentially saying how dark/light a pixel is going to show).
In [80]:
img = cv2.imread("football-ball.jpg",0)
print img
In [83]:
img.shape
Out[83]:
As expected, we have rows and columns of numbers. Exactly 30 rows and 40 columns because our image is 30x40 pixels.
To convert an image into ascii, we need to map/draw a letter or ascii symbol for each number in the image. It is also not displayed the same as an image because we're saving it to a text file or just printing it straight to the console.
Below here I have a mapping set up for these numbers. I chose a very simple scheme to use:
Numbers 0-180 are represented by a 'W'
Numbers 180+ are represented by a '!'
This essentially creates a binary ascii image since there are only two symbols at play in any transformation.
In [81]:
def setupAsciiMapping():
characterSet = list(('W'*18)+'!!!!!!!!')
for i in range(26):
for j in range(10):
asciiToNum[i*10+j]=characterSet[i]
asciiToNum = {}
setupAsciiMapping()
print asciiToNum
Above here I automated the task of creating a dictionary for this mapping.
Now onto the actual transformation...
In the bottom and final block of code, we see here that I am iterating through the image row by row to transform each number into the appropriate symbol of 'W' or '!' and then appending that into a list, which is then added to the list of transformedAscii. The variable transformedAscii is a list of lists, where each list is a row. It is essentially an array of the transformed symbols.
From that list, I join the characters into a long string, and add a new line character at the end of each row to display the string properly.
Pretty picture!
In [82]:
transformedAscii = []
for i in img:
temp = []
for j in i:
temp.append(asciiToNum[j])
transformedAscii.append(temp)
ascii = ''
for i in transformedAscii:
ascii+= ' '.join(i)
ascii+='\n'
print ascii