微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在python中进行模板匹配后如何确定图像上的像素坐标?

如何解决在python中进行模板匹配后如何确定图像上的像素坐标?

我有一个 3D 电影图像,它本身具有星状图形。我有一个形状为 (21,21,1) 的模板,它有助于找到图像上的初始点(矩形)。我已经完成了块匹配部分,并且能够确定一些匹配的坐标,由于图像的不同像素强度,这些坐标有时是正确的和不正确的。图片和模板都是灰色的。以下是我的代码结果预期结果。任何解决此问题的帮助(想法)都将得到承认 模板匹配代码

image = cv2.imread('45_gray.jpg',0 )
template = cv2.imread('45tmpl.jpg',0)
(tW,tH) = template.shape[::-1]

result = cv2.matchTemplate(image,template,cv2.TM_CCOEFF_norMED)
#print(result)

threshold = 0.8
(yCoords,xCoords) = np.where(result >= threshold)
clone = image.copy()
#print(yCoords,xCoords)


for (x,y) in zip(xCoords,yCoords):
    # draw the bounding Box on the image
    cv2.rectangle(clone,(x,y),(x + tW,y + tH),(255,247,263),3)
    # show our output image *before* applying non-maxima suppression
#cv2.imshow("Before NMS",clone)
#cv2.waitKey(0)
cv2.imwrite('output match.jpg',clone)

解决方法

我不认为这种模板匹配在这里效果很好。正如您在输入图像中可能注意到的那样,从左下角到右上角有一个渐变,图像似乎在那个方向淡出。因此,左上角的特征对于模板匹配的有效工作来说并不是那么明显。我建议首先使用自适应阈值技术将此图像转换为二进制图像:

img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

img_adaptive = cv2.adaptiveThreshold(img_gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,15,5)

enter image description here

一旦你有看起来一致的二元图像,即不包含任何渐变,你可以遵循模板匹配路径,或者在这种情况下,我选择遵循检测直线然后处理它们的交点的替代方法作为兴趣点。

现在可以使用 cv2.HoughLinesP 来检测线条,但它有自己的一组参数,需要正确调整才能使其正常工作,所以我只是计算了每行和每列中存在的像素数分别过滤局部最大值点。也就是说,我选择了白色像素数比邻居多的行,并且对每一列也做了同样的处理。

import cv2
import numpy as np
from scipy.signal import argrelextrema

img = cv2.imread("/home/anmol/Downloads/x5JQF.jpg")
img = cv2.resize(img,None,fx=0.4,fy=0.4)
img_gray = cv2.cvtColor(img,11,5)

cv2.imwrite("./debug.png",img_adaptive)

row_white_pixel_count = np.array([np.count_nonzero(img_adaptive[i,:]) for i in range(img_adaptive.shape[0])])
col_white_pixel_count = np.array([np.count_nonzero(img_adaptive[:,i]) for i in range(img_adaptive.shape[1])])

row_maxima = argrelextrema(row_white_pixel_count,np.greater,order=50)[0]
col_maxima = argrelextrema(col_white_pixel_count,order=50)[0]

all_intersection_coords = []
for row_idx in row_maxima:
    for col_idx in col_maxima:
        all_intersection_coords.append((col_idx,row_idx))

for coord in all_intersection_coords:
    img = cv2.circle(img,coord,10,(0,240,0),2)

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。