Home > database >  Dimension issues in 'Template Matching'
Dimension issues in 'Template Matching'

Time:11-24

I'm comparing two images - a complete image & a small part of the same image. If a match is found, then a rectangular box is drawn around that part of the image which contains the smaller image.

To implement this, I have used the 'matchTemplate' method.

The code works as expected, but if the original image's dimensions are 1000 PPI or above, then the image gets cut when displaying the output, hence, the sub-image cannot be highlighted.

Is there a way to fix this?

My code -->

import cv2
import numpy as np
img = cv2.imread("C:\Images\big_image.png")
grey_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
template = cv2.imread("C:\Images\sub_image.png", 0)
w, h = template.shape[::-1]

res = cv2.matchTemplate(grey_img, template, cv2.TM_CCOEFF_NORMED)
print(res)
threshold = 0.9;
loc = np.where(res >= threshold)
print(loc)
for pt in zip(*loc[::-1]):
    cv2.rectangle(img, pt, (pt[0]   w, pt[1]   h), (0, 0, 255), 2)

cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

CodePudding user response:

Before imshow, call namedWindow() with the WINDOW_NORMAL flag. That makes it resizable and scales the image to the size of the window.

cv.namedWindow("img", cv.WINDOW_NORMAL)
# then imshow()...
  • Related