Ask Your Question
0

Help to accomplish template matching please

asked 2020-01-08 05:43:00 -0600

Ajoy gravatar image

updated 2020-01-08 08:45:24 -0600

supra56 gravatar image

image description

import cv2
import numpy as np
img_rgb = cv2.imread('1.jpeg')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('template.jpg', 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.80
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("result.jpg", img_rgb)

Can I please get a helping hand in accomplishing template detection please. The above code is not working for a similar template image ( attached )

C:\fakepath\template.jpg

edit retag flag offensive close merge delete

Comments

1

follow tutorial

LBerger gravatar imageLBerger ( 2020-01-08 06:33:08 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
0

answered 2020-01-08 08:41:15 -0600

supra56 gravatar image

updated 2020-01-08 14:55:00 -0600

Don't used output of 1.jpeg. Use original w/out rectangle. Try this with images and see what happend:

I also removed threshold too. Here is code:

import cv2
import numpy as np

img = cv2.imread("simpsons.jpg")
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
template = cv2.imread("barts_face.jpg", 0)
w, h = template.shape[::-1]

result = cv2.matchTemplate(gray_img, template, cv2.TM_CCOEFF_NORMED)
loc = np.where(result >= 0.4)

for pt in zip(*loc[::-1]):
    cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 3)

cv2.imwrite('Result1.jpg', img)
cv2.imshow("img", img)

cv2.waitKey(0)
cv2.destroyAllWindows()

image of 1.jpeg: image description

And template too: image description

And output: image description

edit flag offensive delete link more

Comments

Thank you Supra. I think I need an appropriate template image. I've been struggling to get the right template image. Your code holds good, but unfortunately because my template image is not effective, my results also fail miserably. :(

Ajoy gravatar imageAjoy ( 2020-01-08 10:21:48 -0600 )edit

@Ajoy. Can you post original images? You can't used black template to match original image. Did you try images as above?

supra56 gravatar imagesupra56 ( 2020-01-08 13:15:47 -0600 )edit

The original image is as same as the image above without the Red Rectangles and the template is the black single inverted triangle I have shown. I am taking your point regarding the black template and am going to try it with the white template.

Ajoy gravatar imageAjoy ( 2020-01-08 17:25:48 -0600 )edit

:( even a non black template does not give expected results

Ajoy gravatar imageAjoy ( 2020-01-08 18:23:50 -0600 )edit

Yes!. It will return.

supra56 gravatar imagesupra56 ( 2020-01-08 20:18:20 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2020-01-08 05:41:24 -0600

Seen: 240 times

Last updated: Jan 08 '20