Skip to content
Advertisement

Fill a rectangle area with an image

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement