在 OpenCV 中查找图像上的角点是一个常见的任务,它可以用于各种应用,如图像匹配、三维重建和运动追踪。在 OpenCV 中有几种方法可以用于检测角点,但最常用的是 Harris 角点检测和 Shi-Tomasi 角点检测(也被称为 Good Features to Track)。下面我将详细介绍这两种方法的应用。
1. Harris 角点检测器
Harris 角点检测算法是一种经典的角点检测方法,它基于图像的局部窗口的自相关函数的响应来进行角点检测。当窗口在角点周围移动时,自相关函数会有明显的变化。
实现步骤:
- 将图像转换为灰度图,因为角点检测通常在单通道图像上进行。
- 使用函数
cv2.cornerHarris()
应用 Harris 角点检测算法。 - 用阈值处理结果,以确定哪些地方的响应强度足以被认为是角点。
- 在原图上标记这些角点。
代码示例:
pythonimport cv2 import numpy as np # 读取图像 img = cv2.imread('image.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Harris 角点检测 gray = np.float32(gray) dst = cv2.cornerHarris(gray, blockSize=2, ksize=3, k=0.04) # 结果膨胀,以便标记 dst = cv2.dilate(dst, None) # 门限设定,标记角点 img[dst > 0.01 * dst.max()] = [0, 0, 255] # 显示图像 cv2.imshow('Harris Corners', img) cv2.waitKey(0) cv2.destroyAllWindows()
2. Shi-Tomasi 角点检测器(Good Features to Track)
Shi-Tomasi 方法是对 Harris 角点检测的一个改进。它改变了评价角点的评分函数,通常能得到更好的结果。
实现步骤:
- 转换图像为灰度。
- 使用函数
cv2.goodFeaturesToTrack()
应用 Shi-Tomasi 角点检测。 - 标记检测到的角点到原图上。
代码示例:
pythonimport cv2 import numpy as np # 读取图像 img = cv2.imread('image.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Shi-Tomasi 角点检测 corners = cv2.goodFeaturesToTrack(gray, maxCorners=100, qualityLevel=0.01, minDistance=10) corners = np.int0(corners) # 标记角点 for i in corners: x, y = i.ravel() cv2.circle(img, (x, y), 3, 255, -1) # 显示图像 cv2.imshow('Shi-Tomasi Corners', img) cv2.waitKey(0) cv2.destroyAllWindows()
在这两种方法中,可以根据应用需求调整相关参数,例如角点检测的敏感度、角点的最大数量等。这些方法都是在计算机视觉和图像处理项目中广泛使用的技术。