OpenCV Python Harris角点检测器检测角点
在OpenCV中,Harris角点检测器是使用cv2.cornerHarris()函数实现的。它接受四个参数:img、blockSize、ksize和k。其中,img是灰度输入图像,数据类型为float32;blockSize是用于角点检测的邻域大小;ksize是Sobel导数的孔径参数;k是Harris检测器方程中的自由参数。
步骤
要使用Harris角点检测器在图像中检测角点,你可以按照以下步骤进行:
- 导入所需的库OpenCV和NumPy。确保你已经安装了它们。
-
使用cv2.imread()方法读取输入图像。指定图像的完整路径。使用cv2.cvtColor()方法将输入图像转换为灰度图像。将灰度图像的数据类型转换为np.float32。
-
对灰度图像(float32)应用cv2.cornerHarris()方法。将合适的blockSize、ksize和k作为参数传递给该方法。
-
膨胀结果以标记角点,并应用阈值来获得最佳值。
-
显示带有检测到的角点的图像。
让我们来看一些使用Harris角点检测器检测图像中角点的示例。
输入图像
我们在下面的示例中使用此图像作为输入文件。
示例
此程序演示了如何使用Harris角点检测器算法在图像中检测角点。
# import required libraries
import cv2
import numpy as np
# load the input image
img = cv2.imread('sudoku.jpg')
# convert the input image into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# modify the data type setting to 32-bit floating point
gray = np.float32(gray)
# apply the cv2.cornerHarris method to detect the corners
corners = cv2.cornerHarris(gray, 2, 3, 0.05)
#result is dilated for marking the corners
corners = cv2.dilate(corners, None)
# Threshold for an optimal value.
img[corners > 0.01 * corners.max()]=[0, 0, 255]
# the window showing output image with corners
cv2.imshow('Image with Corners', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
输出
当我们执行上面的代码时,将会产生以下的输出窗口:
上面的输出图片显示了使用Harris角点检测器检测到的角点。角点用红色显示。