[英]Remove key points from edges of an object
我正在處理帶有對象的圖像。 我使用精明的邊緣檢測和輪廓來檢測和繪制其中對象的邊緣。 然后我同時使用 SIFT 和 SURF 來檢測對象中的關鍵點。 這是我一直在處理的示例代碼。
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread(image)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray, 100,200)
image, contours, hierarchy = cv.findContours(edges, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
outimg = cv.drawContours(img, contours, -1, (0,255,0), 3)
sift = cv.xfeatures2d_SIFT.create()
kp, des = sift.detectAndCompute(outimg,None)
有沒有辦法去除邊緣的關鍵點? 以示例回答將非常有幫助。 謝謝。
您可以使用pointPolygonTest方法來過濾檢測到的關鍵點。 使用檢測到的輪廓作為邊界多邊形。 您還可以定義所需的保證金。
簡單示例(4 點輪廓):
def inside_point(self, point, rect):
# point is a list (x, y)
# rect is a contour with shape [4, 2]
rect = rect.reshape([4, 1, 2]).astype(np.int64)
dist = cv2.pointPolygonTest(rect,(point[0], point[1]),True)
if dist>=0:
# print(dist)
return True
else:
return False
您還可以在蒙版圖像上繪制輪廓並檢查點是否在輪廓內,只需檢查點坐標的像素值,如果不是 0 則點有效。
似乎一切都很好:我沒有 xfeatures2d,所以在這里使用 ORB 功能。
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread('image.jpg')
#img = cv.resize(img,(512,512))
img = cv.copyMakeBorder(img,20,20,20,20, 0)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
_ , gray = cv.threshold(gray,20,255,cv.THRESH_TOZERO)
gray=cv.erode(gray,np.ones( (5,5), np.int8) )
edges = cv.Canny(gray, 100,200)
contours, hierarchy = cv.findContours(edges, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
orb = cv.ORB_create(nfeatures=10000)
kp, des = orb.detectAndCompute(gray,None)
outimg = cv.drawContours(img, contours, -1, (0,255,0), 3)
k = []
for cont in contours:
for i in kp:
(x, y) =i.pt
dist = cv.pointPolygonTest(cont, (x,y), True)
if dist>=0:
k.append(i)
for i in k:
pt=(int(i.pt[0]),int(i.pt[1]) )
cv.circle(outimg,pt,3, (255,255,255),-1)
cv.imwrite('result.jpg',outimg)
cv.imshow('outimg',outimg)
cv.waitKey()
我仍然發現很難從給定的圖像中刪除關鍵點。 如果關鍵點不在輪廓中,我嘗試將關鍵點附加到新列表中,但在使用 cv2.drawKeypoints 函數時顯示錯誤,因為新列表不是關鍵點類型。 這是我迄今為止所做的工作。
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread(image)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray, 100,200)
image, contours, hierarchy = cv.findContours(edges, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
outimg = cv.drawContours(img, contours, -1, (0,255,0), 3)
sift = cv.xfeatures2d_SIFT.create()
kp, des = sift.detectAndCompute(outimg,None)
k = cv.KeyPoint()
for i in kp:
(x, y) =i.pt
dist = cv.pointPolygonTest(contours[0], (x,y), True)
if dist>=0:
k1.append(k)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.