I have a code from OpenCV docs regarding template matching as follows:
JavaScript
x
38
38
1
import cv2
2
import numpy as np
3
from matplotlib import pyplot as plt
4
5
img = cv2.imread('pathtomyimage',0)
6
img2 = img.copy()
7
template = cv2.imread('pathtomyTemplate',0)
8
w, h = template.shape[::-1]
9
10
# All the 6 methods for comparison in a list
11
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
12
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
13
14
for meth in methods:
15
img = img2.copy()
16
method = eval(meth)
17
18
# Apply template Matching
19
res = cv2.matchTemplate(img,template,method)
20
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
21
22
# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
23
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
24
top_left = min_loc
25
else:
26
top_left = max_loc
27
bottom_right = (top_left[0] + w, top_left[1] + h)
28
29
cv2.rectangle(img,top_left, bottom_right, 255, 2)
30
31
plt.subplot(121),plt.imshow(res,cmap = 'gray')
32
plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
33
plt.subplot(122),plt.imshow(img,cmap = 'gray')
34
plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
35
plt.suptitle(meth)
36
37
plt.show()
38
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
JavaScript
1
2
1
img[top:bottom, left:right] = template
2
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.