Friday, January 23, 2009

OCR-ing and Image manipulation with Python

Its fun and easy to experiment with Optical Character Recognition (OCR) in Python. Aside from the standard installation of Python (I'm using 2.6 on Windows XP) there are only two modules you need to install and 5 lines of code to write! I've tested this on Windows, but I assume *nix users will be able to augment these steps slightly to get it working on their platform.

Step 1) Install Python Image Library or PIL for your platform and specific Python version, if you are using the same as me you can use this one: http://effbot.org/downloads/PIL-1.1.6.win32-py2.6.exe otherwise you will need to select from this list: http://effbot.org/downloads/
Step 2) Download and unzip: http://pytesser.googlecode.com/files/pytesser_v0.0.1.zip
Step 3) Open the command prompt and move into the directory where you extracted pytesser (you should be able to list the files and see pytesser.py).
Step 4) Invoke the python interpreter by typing python
Step 5) Paste the following code:

from pytesser import *
image = Image.open('fnord.tif') # Open image object using PIL
print image_to_string(image) # OCR it!

# Now lets rotate it, for more things you can do with PIL, check out the below URL
# http://www.pythonware.com/library/pil/handbook/image.htm

image.rotate(45).show() # Rotate it 45 degrees and open in the default image viewer
image.rotate(45).save("newImage.jpg", "JPEG") # Rotate it 45 degrees and save it in a different format

Here is a screen shot of the finished product:










That's it!

No comments:

Post a Comment