使用 Python OpenCV 中的 Harris 角点检测器检测角点
opencvpythonserver side programmingprogramming
在 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 角点检测器检测到的角点。角点以红色显示。