Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kazoo04
Last active March 3, 2016 11:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazoo04/9ee948ba9533ed2ef5cd to your computer and use it in GitHub Desktop.
Save kazoo04/9ee948ba9533ed2ef5cd to your computer and use it in GitHub Desktop.
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