OpenCV-Python Tutorials (7) ~Image Processing in OpenCV~

OpenCV-Python Tutorialsの記事,Image Processing in OpenCV の章の Contours in OpenCV を見ていく. 今回は,Contours : Contour Properties の内容のメモ.

公式:Image Processing in OpenCV — OpenCV-Python Tutorials 1 documentation

この中で試したコードはGitHubに置いておくことに.

github.com

輪郭のプロパティ

ここでは,頻出するSolidity, Equivalent Diameter, Mask image, Mean Intensityなどのプロパティを学ぶ.他の特徴については,Matlab regionprops documentationを見たらわかる.

1. Aspect Ratio

これは,対象物を囲む四角形の横と縦の比だ.


Aspect \ Ratio = \frac{Width}{Height}

x, y, w, h = cv2.boundingRect(cnt)
aspect_ratio = float(w)/h

2. Extent

Extentは輪郭で囲まれた領域の面積と外接長方形の面積の比だ.


Extent = \frac{Object Area}{Bounding Rectangle Area}

area = cv2.contourArea(cnt)
x, y, w, h = cv2.boundingRect(cnt)
rect_area = w*h
extent = float(area)/rect_area

3. Solidity

Solidityは輪郭で囲まれた領域の面積と凸包の面積の比だ.


Solidity = \frac{Contour Area}{Convex Hull Area}

area = cv2.contourArea(cnt)
hull = cv2.convexHull(cnt)
hull_area = cv2.contourArea(hull)
solidity = float(area)/hull_area

print("solidity:" + str(solidity))

4. Equivalent Diameter

Equivalent Diameterは輪郭で囲まれた領域と同じ面積を持つ円の直径である.


Equivalent \ Diameter = \sqrt{\frac{4 \times Contour \ Area}{\pi}}

area = cv2.contourArea(cnt)
equi_diameter = np.sqrt(4*area/np.pi)

print("equi_diameter:" + str(equi_diameter))

5. Orientation

Orientationは対象物が向いている方向だ.次の手法は長軸と短軸の長さも与えてくれる.

(x,y),(MA,ma),angle = cv2.fitEllipse(cnt)

6. Mask and Pixel Points

ある場合では,対象物を構成する全ての点が必要となるかもしれない.それは次のようにしてできる:

mask = np.zeros(imgray.shape, np.uint8)
cv2.drawContours(mask, [cnt], 0, 255, -1)
pixelpoints = np.transpose(np.nonzero(mask))
#pixelpoints = cv2.findNonZero(mask)

ここでは,2つの手法があり,1つはNumpyの関数を使うもの,もう1つはOpenCVの関数を使うもの(最後の行のもの)で,同じことをするようになっている.結果はほぼ同じだが,少し違いが有る.Numpyは(row, column)の方式での座標で,一方OpenCV(x,y)の方式での座標だ.よって基本的に答えは交換可能である.row = x, column = yであることに注意しておこう.

7. Maximum Value, Minimum Value and their locations

これらのパラメーターはmask画像を用いて求めることができる.

min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(imgray,mask = mask)

8. Mean Color or Mean Intensity

ここでは対象物の色の平均を求める.また,グレースケールのモードでは対象物の強度の平均となる.ここでもmaskを使って行う.

mean_val = cv2.mean(im,mask = mask)

9. Extreme Points

Extreme Pointsとは,対象物の最上点,最下点,最右点,最左点のことである.

leftmost = tuple(cnt[cnt[:,:,0].argmin()][0])
rightmost = tuple(cnt[cnt[:,:,0].argmax()][0])
topmost = tuple(cnt[cnt[:,:,1].argmin()][0])
bottommost = tuple(cnt[cnt[:,:,1].argmax()][0])

練習

他にもいくつかの特徴量がmatlabにある.実行して試してみよう.