Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

python - How to do template matching corrctly on the 7-Segments images?

I have a 7-segment image, and a template, I've tried to do template matching, but there was no matching for the provided template, can you please tell me how to improve the matching?

  • should the template be 100% as same as the desired pattern to be detected in the image?

Template

image

import numpy as np
import matplotlib.pyplot as plt
import cv2

R = cv2.imread('image.png')
R = cv2.Canny(R, 50, 200)

template = cv2.imread('templ.png',0)
template = cv2.Canny(template, 50, 200)

h, w = template.shape

res = cv2.matchTemplate(R,template,cv2.TM_CCOEFF_NORMED)

threshold = 0.8

loc = np.where( res >= threshold)
for pt in zip(*loc):
    cv2.rectangle(R, pt, (pt[0] + w, pt[1] + h), 200, 2)

plt.subplot(221)
plt.imshow(R, cmap='gray')
plt.subplot(222)
plt.imshow(template, cmap='gray')
plt.show()

question from:https://stackoverflow.com/questions/65836234/how-to-do-template-matching-corrctly-on-the-7-segments-images

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your result will depend on the method you use for template matching, since in your case the values are binary (0 or 255), I expected the cross correlation to work well, I tried it and voilà:

Result using cv2.TM_CCORR

It seems that it's not well documented how each method works.

But a good debugging method for these problems is to see the result of the matching to see where it's giving the maximum values, in your case the res variable.

I followed the tutorial in this website, my final code is:

import numpy as np
import matplotlib.pyplot as plt
import cv2

R = cv2.imread('image.png')
R = cv2.Canny(R, 50, 200)


template = cv2.imread('templ.png',0)
template = cv2.Canny(template, 50, 200)
w, h = template.shape[::-1]


res = cv2.matchTemplate(R,template,cv2.TM_CCORR )
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(R,top_left, bottom_right, 255, 2)

cv2.imwrite( './result.png', R)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...