Last active
March 3, 2016 11:51
-
-
Save kazoo04/9ee948ba9533ed2ef5cd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
def create_template(): | |
templates = [] | |
for text in list('0123456789'): | |
img = np.zeros((200,200,1), dtype=np.uint8) | |
cv2.putText(img, text, (100, 100), cv2.FONT_HERSHEY_DUPLEX, 2, 255, 5) | |
contours, _ = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
x, y, w, h = cv2.boundingRect(contours[0]) | |
img = 255 - img | |
templates.append(img[y-2:y+h+2, x-2:x+w+2]) | |
return templates | |
templates = create_template() | |
img = cv2.imread('test.jpg') | |
dst = img.copy() | |
height, width, _ = img.shape[:3] | |
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
_, img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) | |
contours, _ = cv2.findContours(img.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) | |
pallet = [ (0, 0, 0), (0, 0, 255), (0, 255, 0), (0, 255, 255), (255, 0, 0), (255, 0, 255), (255, 255, 0), (0, 0, 128), (0, 128, 0), (0, 128, 128)] | |
for c in contours: | |
x, y, w, h = cv2.boundingRect(c) | |
if(h < 10 or h > 50 or w < 5 or w > 50 or x > width / 2 or w > h): | |
continue | |
test = img[y:y+h, x:x+w] | |
num = max_score = 0 | |
for i, t in enumerate(templates): | |
tmp = cv2.resize(t, (w, h)) | |
count = [tmp[yy, xx] == test[yy, xx] for xx in xrange(w) for yy in xrange(h)].count(True) | |
score = count / float(w * h) | |
if score > max_score: | |
max_score, num = score, i | |
if max_score > 0.75: | |
cv2.rectangle(dst, (x, y), (x + w, y + h), pallet[num], 1) | |
cv2.imshow('test', dst) | |
cv2.waitKey(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment