OpenCV template recognition from http://docs.opencv.org/master/d4/dc6/tutorial_py_template_matching.html#gsc.tab=0
In [ ]:
! wget http://docs.opencv.org/master/res_mario.jpg
In [ ]:
import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image as PIL_Image
from IPython.display import Image as IpyImage
IpyImage(filename='res_mario.jpg')
Crop the image to make an initial test case
In [ ]:
img_full = PIL_Image.open('res_mario.jpg')
img_half = img_full.crop((0,0,img_full.size[0]/2,img_full.size[1]))
img_half.save('mario_test1.jpg')
IpyImage(filename='mario_test1.jpg')
next grab a gold coin as template
In [ ]:
source = PIL_Image.open('mario_test1.jpg')
coin = source.crop((100,113,110,129))
coin.save('coin.jpg')
IpyImage(filename = 'coin.jpg')
next process template
In [ ]:
img_rgb = cv2.imread('mario_test1.jpg')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('coin.jpg',0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
cv2.imwrite('res.jpg',img_rgb)
IpyImage(filename = 'res.jpg')