在学习OpenCV-python实现的过程中,第六章的练习内容如下:
创建一个滑动条用来为SURF实例提供Hessian阈值,可以看到特征会随阈值的增加而减少。
修改了很久的代码一直没能得到满意的效果,虽然能够实现滑动条控制Hessian值,但是可视化处理效果达不到预期,每次的Hessian值的drawKeypoints都叠加在一起,导致画面极度混乱,后发现问题出现在drawKeypoints函数的outImage值上,将其与image值用两个不同变量保存即可解决问题,代码如下:
import cv2
def update(val = 0):
Hessian = cv2.getTrackbarPos('Hessian', 'keypoints')
# 创建SURF对象,计算关键点和描述符并绘制
fd_alg = cv2.xfeatures2d.SURF_create(Hessian)
keypoints, descriptor = fd_alg.detectAndCompute(gray, None)
cv2.drawKeypoints(image=img, outImage=_img, keypoints=keypoints, flags=4, color=(51, 163, 236))
cv2.imshow('keypoints', _img)
if __name__ == "__main__":
cv2.namedWindow('keypoints', cv2.WINDOW_NORMAL)
# Hessian滚动条初值及最大值
Hessian = 8000
max_Hessian = 50000
imgpath = r"E:\opencv\pycv\images\varese.jpg"
img = cv2.imread(imgpath)
_img = cv2.imread(imgpath)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 创建窗口和滚动条
cv2.namedWindow('keypoints')
cv2.createTrackbar('Hessian', 'keypoints', Hessian, max_Hessian, update)
update()
cv2.waitKey()
cv2.destroyAllWindows()
下面是原始有漏洞的版本:
cv2.drawKeypoints(image=img, outImage=img, keypoints=keypoints, flags=4, color=(51, 163, 236))