实现一下harris角点检测
时间: 2023-11-03 12:06:43 浏览: 23
这里提供一份Python代码实现Harris角点检测:
```python
import numpy as np
import cv2
def harris_corner_detector(gray_img, k=0.04, threshold=0.01, window_size=3):
# 计算图像中每个像素的梯度
dx = cv2.Sobel(gray_img, cv2.CV_64F, 1, 0, ksize=5)
dy = cv2.Sobel(gray_img, cv2.CV_64F, 0, 1, ksize=5)
# 计算矩阵M的每个元素
Ixx = dx ** 2
Ixy = dx * dy
Iyy = dy ** 2
# 计算每个像素的响应函数R
height, width = gray_img.shape
response = np.zeros((height, width))
offset = window_size // 2
for y in range(offset, height - offset):
for x in range(offset, width - offset):
# 计算矩阵M的和
Sxx = np.sum(Ixx[y-offset:y+offset+1, x-offset:x+offset+1])
Sxy = np.sum(Ixy[y-offset:y+offset+1, x-offset:x+offset+1])
Syy = np.sum(Iyy[y-offset:y+offset+1, x-offset:x+offset+1])
# 计算响应函数R
det = Sxx * Syy - Sxy ** 2
trace = Sxx + Syy
response[y, x] = det - k * trace ** 2
# 非极大值抑制
max_response = np.max(response)
threshold_response = threshold * max_response
corner_points = []
for y in range(offset, height - offset):
for x in range(offset, width - offset):
if response[y, x] > threshold_response and \
response[y, x] == np.max(response[y-offset:y+offset+1, x-offset:x+offset+1]):
corner_points.append((x, y))
return corner_points
```
使用方法如下:
```python
# 读入图像并转为灰度图
img = cv2.imread('image.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 检测角点
corner_points = harris_corner_detector(gray_img)
# 在图像上显示角点
for point in corner_points:
cv2.circle(img, point, 3, (0, 0, 255), -1)
# 显示结果
cv2.imshow('Harris Corner Detection', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```