将cv2.matchTemplate封装为新的函数,使其具有旋转和尺度适应性,写出代码
时间: 2024-02-20 20:00:34 浏览: 21
以下是将cv2.matchTemplate封装为新的函数,使其具有旋转和尺度适应性的Python代码示例:
```python
import cv2
import numpy as np
def matchTemplateRotatedScaled(img, template, angle, scale):
# 缩放模板图像
resized_template = cv2.resize(template, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
# 旋转模板图像
(h, w) = resized_template.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated_template = cv2.warpAffine(resized_template, M, (w, h))
# 进行模板匹配
result = cv2.matchTemplate(img, rotated_template, cv2.TM_CCOEFF_NORMED)
# 找到最佳匹配位置
(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(result)
(topLeft, bottomRight) = (maxLoc, (maxLoc[0] + w, maxLoc[1] + h))
# 返回最佳匹配位置和匹配度
return (topLeft, bottomRight, maxVal)
# 测试函数
img = cv2.imread('image.jpg', 0)
template = cv2.imread('template.jpg', 0)
(topLeft, bottomRight, maxVal) = matchTemplateRotatedScaled(img, template, 45, 0.5)
cv2.rectangle(img, topLeft, bottomRight, 255, 2)
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在上述代码中,我们封装了一个名为matchTemplateRotatedScaled的新函数,该函数接受原始图像、模板图像、旋转角度和缩放系数作为输入,然后自动完成缩放和旋转操作,并返回最佳匹配位置和匹配度。
在测试代码中,我们首先读取原始图像和模板图像,然后调用matchTemplateRotatedScaled函数进行模板匹配,并使用cv2.rectangle函数在原始图像中标记最佳匹配位置。