![](/img/trans.png)
[英]How to get pixel coordinates from Feature Matching in OpenCV Python
[英]How to determine pixel coordinates on an image after template matching in 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)
我認為這個模板匹配在這里不會很好。 正如您可能在輸入圖像中注意到的那樣,從左下角到右上角有一個漸變,圖像似乎在該方向上逐漸消失。 因此,在左上角,對於模板匹配有效地工作來說,這些特征並不是那么明顯。 我建議首先使用 AdaptiveThreshold 技術將此圖像轉換為二進制圖像:
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)
一旦你有了看起來一致的二元圖像,即不包含任何漸變,你可以遵循模板匹配路徑,或者在這種情況下,我選擇遵循檢測直線的替代方法,然后將它們的交點視為點出於興趣。
現在可以使用cv2.HoughLinesP
來檢測線條,但它有自己的一組參數,需要對其進行適當調整才能使其正常工作,所以我只需分別計算每行和每列中存在的 while 像素數並過濾本地最大值點。 也就是說,我選擇了比鄰居有更多白色像素數的行,並且對每一列也做了同樣的事情。
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, cv2.COLOR_BGR2GRAY)
img_adaptive = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 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, np.greater, 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.