0

I have a code from OpenCV docs regarding template matching as follows:

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

img = cv2.imread('pathtomyimage',0)
img2 = img.copy()
template = cv2.imread('pathtomyTemplate',0)
w, h = template.shape[::-1]
    
# All the 6 methods for comparison in a list
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
            'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']

for meth in methods:
    img = img2.copy()
    method = eval(meth)

    # Apply template Matching
    res = cv2.matchTemplate(img,template,method)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

    # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
    if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)

    cv2.rectangle(img,top_left, bottom_right, 255, 2)

    plt.subplot(121),plt.imshow(res,cmap = 'gray')
    plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
    plt.subplot(122),plt.imshow(img,cmap = 'gray')
    plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
    plt.suptitle(meth)

    plt.show()

Right now the rectangle drawn on my image is not filled, I would like to fill the area of the cv2.rectangle with some image. How to achive this?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
igy234
  • 59
  • 1
  • 7
  • Related: https://stackoverflow.com/questions/57576686/how-to-overlay-segmented-image-on-top-of-main-image-in-python and https://stackoverflow.com/questions/58248121/opencv-python-how-to-overlay-an-image-into-the-centre-of-another-image – Confused Learner May 18 '21 at 16:41

1 Answers1

0

If you are filling the rectangle with the template image, then the dimensions of the template are the same as the rectangle and all you need to do is insert it using Numpy. So

img[top:bottom, left:right] = template

That puts the template image into the region of img defined by the rectangle.

Of course you can use any image in place of template, so long as you crop it to the same width and height as defined by left:right and top:bottom.

fmw42
  • 46,825
  • 10
  • 62
  • 80
  • Since the cv2.rectangle function needs the pairs of coordinates (in this example represented as top_left, bottom_right). How do i get "top", "bottom", "left" and "right" parameters? – igy234 May 20 '21 at 15:22
  • top=top-left-y, bottom=bottom-right-y, left=top-left-x, right=bottom-right-x. Draw a rectangle and mark the two corners and see which are the min and max x and y. Those define the top, bottom, left and right values. – fmw42 May 20 '21 at 15:29
  • Okay I got it, the correct line should be: "img[top_left[0]:top_left[0]+template.shape[0], top_left[1]:top_left[1]+template.shape[1]] = img3" where img3 is the image of appropriate size that can be put inside rectangle region. – igy234 May 20 '21 at 16:30