python中Harris角点检测

基本思想

1、选择在图像上任意方向的固定窗口进行滑动,如果灰度变化较大,则认为该窗口内部存在角点。

2、步骤,读图并将其转换为灰度图。估计响应函数。根据响应值选择角度。画出原始图上的检测角点。

实例

frompylabimport*
fromnumpyimport*
fromscipy.ndimageimportfilters


defcompute_harris_response(im,sigma=3):
"""ComputetheHarriscornerdetectorresponsefunction
foreachpixelinagraylevelimage."""

#derivatives
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)

#computecomponentsoftheHarrismatrix
Wxx=filters.gaussian_filter(imx*imx,sigma)
Wxy=filters.gaussian_filter(imx*imy,sigma)
Wyy=filters.gaussian_filter(imy*imy,sigma)

#determinantandtrace
Wdet=Wxx*Wyy-Wxy**2
Wtr=Wxx+Wyy

returnWdet/Wtr


defget_harris_points(harrisim,min_dist=10,threshold=0.1):
"""ReturncornersfromaHarrisresponseimage
min_dististheminimumnumberofpixelsseparating
cornersandimageboundary."""

#findtopcornercandidatesaboveathreshold
corner_threshold=harrisim.max()*threshold
harrisim_t=(harrisim>corner_threshold)*1

#getcoordinatesofcandidates
coords=array(harrisim_t.nonzero()).T

#...andtheirvalues
candidate_values=[harrisim[c[0],c[1]]forcincoords]

#sortcandidates(reversetogetdescendingorder)
index=argsort(candidate_values)[::-1]

#storeallowedpointlocationsinarray
allowed_locations=zeros(harrisim.shape)
allowed_locations[min_dist:-min_dist,min_dist:-min_dist]=1

#selectthebestpointstakingmin_distanceintoaccount
filtered_coords=[]
foriinindex:
ifallowed_locations[coords[i,0],coords[i,1]]==1:
filtered_coords.append(coords[i])
allowed_locations[(coords[i,0]-min_dist):(coords[i,0]+min_dist),
(coords[i,1]-min_dist):(coords[i,1]+min_dist)]=0

returnfiltered_coords


defplot_harris_points(image,filtered_coords):
"""Plotscornersfoundinimage."""

figure()
gray()
imshow(image)
plot([p[1]forpinfiltered_coords],
[p[0]forpinfiltered_coords],'*')
axis('off')
show()
fromPILimportImage
fromnumpyimport*
#这就是为啥上述要新建一个的原因,因为现在就可以import
importHarris_Detector
frompylabimport*
fromscipy.ndimageimportfilters

#filename
im=array(Image.open(r"").convert('L'))
harrisim=Harris_Detector.compute_harris_response(im)
filtered_coords=Harris_Detector.get_harris_points(harrisim)
Harris_Detector.plot_harris_points(im,filtered_coords)

以上就是python中Harris角点检测的方法,希望对大家有所帮助。更多Python学习指路:Python基础教程

发表回复