图像
因此,哈里斯角检测的结果是一个带有这些分数的灰度图像。合适的阈值给你的图像的角。我们将用一个简单的图像来做。
位于OpenCV的哈里斯角探测器
OpenCV有这个功能的cv.cornerHarris()。它的参数是:
img-输入图像,应该是灰度和浮动32型。
blockSize——它是被认为是角落检测的邻居的大小
ksize-使用的Sobel衍生物的孔径参数。
k-哈里斯探测器在方程中自由参数。
看下面的例子:
import numpy as np
import cv2 as cv
filename = 'xiangqi.jpg'
img = cv.imread(filename)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv.cornerHarris(gray,2,3,0.2)
#result is dilated for marking the corners, not important
dst = cv.dilate(dst,None)
# Threshold for an optimal value, it may vary depending on the image.
img[dst>0.01*dst.max()]=[0,0,255]
cv.imshow('dst',img)
if cv.waitKey(0) & 0xff == 27:
cv.destroyAllWindows()
转角遇到亚像素精度
有时,你可能需要找到最精确的角落。OpenCV有一个功能cv.cornerSubPix(),它进一步改进了用亚像素精度检测到的角。下面是一个例子。像往常一样,我们需要先找到哈里斯角。然后我们传递这些角的中心体(在一个角落可能有一堆像素,我们取它们的质心)来完善它们。哈里斯角以红色像素为标志,精致的角落以绿色像素标记。对于这个函数,我们必须定义何时停止迭代的标准。我们在指定的迭代次数之后停止它,或者达到一定的精度,无论哪个先发生。我们还需要定义邻居的大小,它会搜索角落。
import numpy as np
import cv2 as cv
filename = 'xiangqi.jpg'
img = cv.imread(filename)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
# find Harris corners
gray = np.float32(gray)
dst = cv.cornerHarris(gray,2,3,0.04)
dst = cv.dilate(dst,None)
ret, dst = cv.threshold(dst,0.01*dst.max(),255,0)
dst = np.uint8(dst)
# find centroids
ret, labels, stats, centroids = cv.connectedComponentsWithStats(dst)
# define the criteria to stop and refine the corners
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 100, 0.001)
corners = cv.cornerSubPix(gray,np.float32(centroids),(5,5),(-1,-1),criteria)
# Now draw them
res = np.hstack((centroids,corners))
res = np.int0(res)
img[res[:,1],res[:,0]]=[0,0,255]
img[res[:,3],res[:,2]] = [0,255,0]
cv.imshow('subpixel5.png',img)