因此,我正在尝试使用opencv中的Harris角落检测来找到对象的角落。我应该得到5个确切的角点,但我却得到6个角点。似乎有问题。

    import cv2
import numpy as np

def find_centroids(dst):
    ret, dst = cv2.threshold(dst, 0.01 * dst.max(), 255, 0)
    dst = np.uint8(dst)

    # find centroids
    ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)
    # define the criteria to stop and refine the corners
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100,
                0.001)
    corners = cv2.cornerSubPix(gray,np.float32(centroids),(5,5),
              (-1,-1),criteria)
    return corners

image = cv2.imread("C:\\Users\\Jimit\\Desktop\\Project\\lmao.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

gray = np.float32(gray)

dst = cv2.cornerHarris(gray, 3, 3, 0.04)

dst = cv2.dilate(dst, None)

# Threshold for an optimal value, it may vary depending on the image.
# image[dst > 0.01*dst.max()] = [0, 0, 255]

# Get coordinates
corners = find_centroids(dst)
# To draw the corners
for corner in corners:
    image[int(corner[1]), int(corner[0])] = [0, 0, 255]
int_corners = np.asarray(corners, dtype = int)
print (int_corners)
print ("Pixels for corner 1 is: ", int_corners[0])
print ("Pixels for corner 2 is: ", int_corners[1])
print ("Pixels for corner 3 is: ", int_corners[2])

cv2.imshow('dst', image)
cv2.imwrite('corners.jpg', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

原始图片

所需的输出角点

额外的角落

6个角像素

最佳答案

您的问题在这一行:

ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)

您假定所有质心/标签都针对每个角...但是实际上是一个背景(标签0),如documentation中所述:



并且:



现在,知道了这一点,解决方案就很容易了,只需替换以下说明:
corners = cv2.cornerSubPix(gray,np.float32(centroids),(5,5),
          (-1,-1),criteria)

与:
corners = cv2.cornerSubPix(gray,np.float32(centroids[1:]),(5,5),
          (-1,-1),criteria)

注意[1:]中的centroids。这将为您提供以下几点:
[[223 121]
 [153 191]
 [290 194]
 [152 275]
 [287 277]]

如您所见,第一个点已删除。

10-02 04:45