Harris角点检测代码复现python
时间: 2024-11-14 18:14:26 浏览: 49
harris角点检测python实现及基于opencv实现
5星 · 资源好评率100%
Harris角点检测是一种用于图像特征检测的经典技术,它基于局部图像的灰度梯度信息来寻找兴趣点。在Python中,你可以使用开源库如OpenCV来实现Harris角点检测算法。以下是一个简单的步骤:
1. **导入必要的库**:
```python
import cv2
import numpy as np
```
2. **读取图像**:
```python
image = cv2.imread('your_image.jpg', cv2.IMREAD_GRAYSCALE)
```
3. **计算图像梯度**:
```python
gx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3) # Sobel x
gy = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3) # Sobel y
```
4. **计算Harris响应矩阵**:
```python
def harris_response(Ix, Iy):
# 计算Ix*Ix 和 Iy*Iy 的局部平均值
Rxx = cv2.boxFilter(Ix * Ix, -1, (3, 3))
Ryy = cv2.boxFilter(Iy * Iy, -1, (3, 3))
# 计算Ix*Iy的局部平均值
Rxy = cv2.boxFilter(Ix * Iy, -1, (3, 3))
# Harris算子
A = Rxx + Ryy - k * (Rxy**2)
D = Rxx * Ryy - (Rxy**2)
return A, D
k = 0.04 # Harris算子常数,通常设置为0.04~0.08
A, D = harris_response(gx, gy)
```
5. **非极大值抑制和阈值处理**:
```python
# 检测角点并应用非极大值抑制
corners = cv2.cornerHarris(A, 2, 3, k)
# 将响应转换为原图尺寸,然后设置阈值并找出角点位置
_, corners = cv2.threshold(corners, 0.01 * corners.max(), 255, 0)
```
6. **标记角点到原图上**:
```python
corners = np.uint8(corners)
top_left = tuple(np.argwhere(corners == 255).flatten())
bottom_right = tuple(np.flipud(np.argwhere(corners == 255)).flatten())
for pt in zip(top_left, bottom_right):
cv2.circle(image, pt, 2, (0, 0, 255), thickness=2)
```
7. **显示结果**:
```python
cv2.imshow("Original Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文