abdulfatirs

ImageDecoder.py | Decode Text from Images

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