Advertisement
abdulfatirs

ImageDecoder.py | Decode Text from Images

Mar 14th, 2014
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. #! /usr/bin/env python
  2. # ImageDecoder.py
  3. # Author: Abdul Fatir
  4. # E-Mail: abdulfatirs@gmail.com
  5.  
  6. from PIL import Image
  7. import optparse
  8.  
  9. morse_dict={
  10.     'A':'.-','B':'-...','C':'-.-.','D':'-..','E':'.','F':'..-.',
  11.     'G':'--.','H':'....','I':'..','J':'.---','K':'-.-','L':'.-..',
  12.     'M':'--','N':'-.','O':'---','P':'.--.','Q':'--.-','R':'.-.',
  13.     'S':'...','T':'-','U':'..-','V':'...-','W':'.--','X':'-..-',
  14.     'Y':'-.--','Z':'--..','0':'-----','1':'.----','2':'..---','3':'...--',
  15.     '4':'....-','5':'.....','6':'-....','7':'--...','8':'---..','9':'----.',
  16.     '.':'.-.-.-',',':'--..--','?':'..--..',"'":'.----.','/':'-..-.','(':'-.--.-',
  17.     ')':'-.--.-',':':'---...',';':'-.-.-.','=':'-...-','+':'.-.-.','-':'-....-',
  18.     '_':'..--.-','"':'.-..-.','$':'...-..-','':''
  19.     }
  20. def getLetterForMorse(l):
  21.    
  22.     for key, value in morse_dict.iteritems():
  23.         if(value == l):
  24.             return str(key)
  25. def Main():
  26.     parser = optparse.OptionParser('usage: python ImageDecoder.py -i <input PNG image name>')
  27.     parser.add_option('-i',dest='inPNG',type='string',help='Please specify the input image file')
  28.     (options,arg) = parser.parse_args()
  29.     if (options.inPNG == None):
  30.         print parser.usage
  31.         exit(0)
  32.     else:
  33.         inPNG = options.inPNG
  34.     _img = Image.open(inPNG)
  35.     W = _img.size[0]
  36.     H = _img.size[1]
  37.     _pixs = _img.load()
  38.     lastOff = 0
  39.     _letter = ""
  40.     answer = ""
  41.  
  42.     for y in range(H):
  43.         for x in range(W):
  44.             if(_pixs[x,y] == (255,255,255)):
  45.                 offset = y*100 + x - lastOff
  46.                 lastOff = y*100 + x
  47.                 _char = chr(offset)
  48.                 if(_char != ' '):
  49.                     _letter += _char
  50.                 else:
  51.                     answer += getLetterForMorse(_letter)
  52.                     _letter = ""
  53.  
  54.     print answer
  55.    
  56. if __name__ == '__main__':
  57.     Main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement