1. 程式人生 > >《python+opencv實踐》四、影象特徵提取與描述——30Harris 角點檢測

《python+opencv實踐》四、影象特徵提取與描述——30Harris 角點檢測

目標
• 理解Harris 角點檢測的概念

• 學習函式:cv2.cornerHarris(),cv2.cornerSubPix()

原理

在上一節我們已經知道了角點的一個特性:向任何方向移動變化都很大。Chris_Harris 和Mike_Stephens 早在1988 年的文章《A Combined Corner and Edge Detector》中就已經提出了角點檢測的方法,被稱為Harris 角點檢測。他把這個簡單的想法轉換成了數學形式。將視窗向各個方向移動(u,v)然後計算所有差異的總和。表示式如下:


視窗函式可以是正常的矩形視窗也可以是對每一個畫素給予不同權重的高斯視窗。

角點檢測中要使E (u; v) 的值最大。這就是說必須使方程右側的第二項的取值最大。對上面的等式進行泰勒級數展開然後再通過幾步數學換算(可以參考其他標準教材),我們得到下面的等式:



其中:


這裡Ix 和Iy 是影象在x 和y 方向的導數。(可以使用函式cv2.Sobel()計算得到)。
然後就是主要部分了。他們根據一個用來判定視窗內是否包含角點的等式進行打分。


其中:




所以根據這些特徵中我們可以判斷一個區域是否是角點,邊界或者是平面。



可以用下圖來表示我們的結論:


所以Harris 角點檢測的結果是一個由角點分數構成的灰度影象。選取適當的閾值對結果影象進行二值化我們就檢測到了影象中的角點。我們將用一個簡單的圖片來演示一下。

30.1 OpenCV 中的Harris 角點檢測

Open 中的函式cv2.cornerHarris(src, blockSize, ksize, k[, dst[, borderType]]) → dst

可以用來進行角點檢測。引數如下:

Parameters:

  • src – Input single-channel 8-bit or floating-point image.
  • dst – Image to store the Harris detector responses. It has the typeCV_32FC1 and the same size assrc .
  • blockSize – Neighborhood size (see the details oncornerEigenValsAndVecs() ).
  • ksize – Aperture parameter for the
    Sobel()
    operator.
  • k – Harris detector free parameter. See the formula below.
  • borderType – Pixel extrapolation method. SeeborderInterpolate() .

      • img - 資料型別為float32 的輸入影象。
      • blockSize - 角點檢測中要考慮的領域大小。
      • ksize - Sobel 求導中使用的視窗大小
      • k - Harris 角點檢測方程中的自由引數,取值引數為[0,04,0.06].
例子如下:

# -*- coding: utf-8 -*-
"""
Created on Mon Jan 20 18:53:24 2014
@author: duan
"""
import cv2
import numpy as np
filename = 'chessboard.jpg'
img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
# 輸入影象必須是float32,最後一個引數在0.04 到0.05 之間
dst = cv2.cornerHarris(gray,2,3,0.04)
#result is dilated for marking the corners, not important
dst = cv2.dilate(dst,None)
# Threshold for an optimal value, it may vary depending on the image.
img[dst>0.01*dst.max()]=[0,0,255]
cv2.imshow('dst',img)
if cv2.waitKey(0) & 0xff == 27:
    cv2.destroyAllWindows()
                                   

30.2 亞畫素級精確度的角點
有時我們需要最大精度的角點檢測。OpenCV 為我們提供了函式cv2.cornerSubPix(),它可以提供亞畫素級別的角點檢測。下面是一個例子。首先我們要找到Harris角點,然後將角點的重心傳給這個函式進行修正。Harris 角點用紅色畫素標出,綠色畫素是修正後的畫素。在使用這個函式是我們要定義一個迭代停止條件。當迭代次數達到或者精度條件滿足後迭代就會停止。我們同樣需要定義進
行角點搜尋的鄰域大小。

# -*- coding: utf-8 -*-
"""
Created on Mon Jan 20 18:55:47 2014
@author: duan
"""
import cv2
import numpy as np
filename = 'chessboard2.jpg'
img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# find Harris corners
gray = np.float32(gray)
dst = cv2.cornerHarris(gray,2,3,0.04)
dst = cv2.dilate(dst,None)
ret, dst = cv2.threshold(dst,0.01*dst.max(),255,0)
dst = np.uint8(dst)
# find centroids
#connectedComponentsWithStats(InputArray image, OutputArray labels, OutputArray stats,
#OutputArray centroids, int connectivity=8, int ltype=CV_32S)
ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)
# define the criteria to stop and refine the corners
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)
#Python: cv2.cornerSubPix(image, corners, winSize, zeroZone, criteria)
#zeroZone – Half of the size of the dead region in the middle of the search zone
#over which the summation in the formula below is not done. It is used sometimes
# to avoid possible singularities of the autocorrelation matrix. The value of (-1,-1)
# indicates that there is no such a size.
# 返回值由角點座標組成的一個數組(而非影象)
corners = cv2.cornerSubPix(gray,np.float32(centroids),(5,5),(-1,-1),criteria)
# Now draw them
res = np.hstack((centroids,corners))
#np.int0 可以用來省略小數點後面的數字(非四五入)。
res = np.int0(res)
img[res[:,1],res[:,0]]=[0,0,255]
img[res[:,3],res[:,2]] = [0,255,0]
cv2.imwrite('subpixel5.png',img)

結果如下,為了方便檢視我們對角點的部分進行了放大: