[英]Fill a rectangle area with an image
I have a code from OpenCV docs regarding template matching as follows:我有来自 OpenCV 文档的关于模板匹配的代码,如下所示:
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.现在我的图像上绘制的矩形没有被填充,我想用一些图像填充cv2.rectangle
的区域。 How to achive this?如何做到这一点?
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.如果您使用模板图像填充矩形,则模板的尺寸与矩形相同,您需要做的就是使用 Numpy 插入它。 So所以
img[top:bottom, left:right] = template
That puts the template image into the region of img defined by the rectangle.这会将模板图像放入矩形定义的 img 区域中。
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.当然,您可以使用任何图像代替模板,只要将其裁剪为与 left:right 和 top:bottom 定义的相同的宽度和高度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.