# Joshua R. Davis' solution to Exam 2 Question C import cImage def glyph(image): """Given a grayscale image, returns the corresponding glyph.""" result = () width = image.getWidth() height = image.getHeight() for row in range(height): # Load a row of pixels into a tuple. resultRow = () for col in range(width): resultRow += (image.getPixel(col, row).getRed(),) result += (resultRow,) return result def text(image, glyphs, threshold): """Given a grayscale image, a list of 26 glyphs corresponding to the 26 uppercase English letters (in order), and a threshold value, returns the string of text that is pictured in the image.""" # The result string will accumulate the answer. result = "" # Loop through all interior pixels of the image. width = image.getWidth() height = image.getHeight() for row in range(4, height - 4): for col in range(3, width - 3): # Find the glyph that best matches this chunk of the image. best = -1 bestTotal = threshold + 1 for k in range(len(glyphs)): # Matching is measured by the sum of squares of differences of pixel intensities. total = 0 for i in range(7): for j in range(9): red = image.getPixel(col + i - 3, row + j - 4).getRed() total += (red - glyphs[k][j][i])**2 if total < bestTotal and total <= threshold: bestTotal = total best = k #print "row", row, "col", col, "best", chr(best + 65), "bestTotal", bestTotal # If the best glyph matches well, then put it in result. if bestTotal <= threshold: result += chr(best + 65) return result if __name__ == "__main__": print "Loading files..." glyphs = [] for i in range(26): #print "Loading glyph", i glyphs.append(glyph(cImage.FileImage(chr(i + 65) + ".gif"))) image = cImage.FileImage("long.gif") print "Analyzing image..." print text(image, glyphs, 100**2)