Harris角点检测python代码
时间: 2023-12-15 08:29:44 浏览: 140
Harris角点检测是一种计算机视觉算法,用于检测图像中的角点。以下是Harris角点检测的Python代码:
1. 首先需要导入必要的库:
```
from PIL import Image
from numpy import *
from pylab import *
```
2. 定义计算Harris响应函数的函数:
```
def compute_harris_response(im, sigma=3):
""" 在一幅灰度图像中,对每个像素计算Harris角点检测器响应函数 """
# 计算导数
imx = zeros(im.shape)
filters.gaussian_filter(im, (sigma,sigma), (0,1), imx)
imy = zeros(im.shape)
filters.gaussian_filter(im, (sigma,sigma), (1,0), imy)
# 计算Harris矩阵的分量
Wxx = filters.gaussian_filter(imx*imx, sigma)
Wxy = filters.gaussian_filter(imx*imy, sigma)
Wyy = filters.gaussian_filter(imy*imy, sigma)
# 计算特征值和迹
Wdet = Wxx*Wyy - Wxy**2
Wtr = Wxx + Wyy
return Wdet / Wtr
```
3. 定义获取Harris角点的函数:
```
def get_harris_points(harrisim, min_distance=10, threshold=0.1):
""" 从一幅Harris响应图像中返回角点。min_distance为分割角点和图像边界的最小像素数目 """
# 寻找高于阈值的候选角点
corner_threshold = harrisim.max() * threshold
harrisim_t = (harrisim > corner_threshold) * 1
# 得到候选点的坐标
coords = array(harrisim_t.nonzero()).T
# 以及它们的Harris响应值
candidate_values = [harrisim[c[0],c[1]] for c in coords]
# 对候选点按照Harris响应值进行排序
index = argsort(candidate_values)
# 将可行点的位置保存到数组中
allowed_locations = zeros(harrisim.shape)
allowed_locations[min_distance:-min_distance,min_distance:-min_distance] = 1
# 按照最小距离原则,选择最佳Harris点
filtered_coords = []
for i in index:
if allowed_locations[coords[i,0],coords[i,1]] == 1:
filtered_coords.append(coords[i])
allowed_locations[(coords[i,0]-min_distance):(coords[i,0]+min_distance),
(coords[i,1]-min_distance):(coords[i,1]+min_distance)] = 0
return filtered_coords
```
4. 定义绘制Harris角点的函数:
```
def plot_harris_points(image, filtered_coords):
""" 绘制图像中检测到的角点 """
figure()
gray()
imshow(image)
plot([p[1] for p in filtered_coords], [p[0] for p in filtered_coords], '*', color='r')
axis('off')
show()
```
5. 最后,可以使用以下代码来运行Harris角点检测:
```
# 读入图像
im = array(Image.open(r"C:\Users\13121\Desktop\test.jpg").convert('L'))
# 计算Harris响应函数
harrisim = compute_harris_response(im)
# 获取Harris角点
filtered_coords = get_harris_points(harrisim, 6, 0.01)
# 绘制Harris角点
plot_harris_points(im, filtered_coords)
```
阅读全文