4.3. 轮廓特性

在这里,我们将学习提取物体的一些常用属性,如固体、等效直径、掩模图像、平均强度等 Matlab regionprops documentation .

(注:质心、面积、周长等也属于这一类,但我们在上一章已经看到了)

4.3.1. 1. 纵横比

它是对象的边界矩形的宽高比。

\[Aspect \; Ratio = \frac{Width}{Height}\]
>>> %matplotlib inline
>>> import matplotlib.pyplot as plt
>>>
>>> import cv2
>>> import numpy as np
>>> img = cv2.imread('/cvdata/star.png', 0)
>>> ret,thresh = cv2.threshold(img,127,255,0)
>>> contours,hierarchy,aa = cv2.findContours(thresh, 1, 2)
>>> for cnt in hierarchy:
>>>     area = cv2.contourArea(cnt)
>>>     print(area)
4.0
4.0
2.0
2.0
8.5
2.0
2.0
2.0
2.0
2.0
2.0
2.0
2.0
2.0
2.0
2.0
2.0
2.0
2.0
2.0
2.0
76185.5
>>> x,y,w,h = cv2.boundingRect(cnt)
>>> aspect_ratio = float(w)/h
>>> aspect_ratio
3.282051282051282

4.3.2. 2. 范围

区段是等高线面积与边框面积之比。

\[范围=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
>>> extent
0.6104607371794872

4.3.3. 3. 坚固性

坚固性是外形面积与其凸面船体面积的比值。

\[坚固性=frac{Contour;Area}{凸面;外壳;Area}\]
>>> area = cv2.contourArea(cnt)
>>> hull = cv2.convexHull(cnt)
>>> hull_area = cv2.contourArea(hull)
>>> solidity = float(area)/hull_area
>>> solidity
0.7952723438902691

4.3.4. 4. 当量直径

等效直径是其面积与轮廓面积相同的圆的直径。

\[等效直径\]
>>> area = cv2.contourArea(cnt)
>>> equi_diameter = np.sqrt(4*area/np.pi)
>>> equi_diameter
311.45206908193876

4.3.5. 5. 方向

方向是物体被指向的角度。下面的方法也给出了长轴和短轴的长度。

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

4.3.6. 6. 遮罩和像素点

在某些情况下,我们可能需要包含该对象的所有点。具体操作如下:

>>> mask = np.zeros(img.shape,np.uint8)
>>> cv2.drawContours(mask,[cnt],0,255,-1)
>>> pixelpoints = np.transpose(np.nonzero(mask))
>>> #pixelpoints = cv.findNonZero(mask)
>>> pixelpoints
array([[205, 323],
       [205, 324],
       [206, 322],
       ...,
       [399, 637],
       [399, 638],
       [399, 639]])

这里,给出了两种方法,一种使用Numpy函数,另一种使用OpenCV函数(最后一个注释行)来完成相同的操作。结果也一样,但略有不同。Numpy给出坐标 (行,列) 格式,而OpenCV提供坐标 (x,y) 格式。所以基本上答案是可以互换的。请注意, row = xcolumn = y .

4.3.7. 7. 最大值、最小值及其位置

我们可以用掩模图像来找到这些参数。

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

4.3.8. 8. 平均颜色或平均强度

在这里,我们可以找到一个物体的平均颜色。也可以是灰度模式下对象的平均强度。我们又用了同样的面具。

>>> mean_val = cv2.mean(img,mask = mask)
>>> mean_val
(160.09079561559767, 0.0, 0.0, 0.0)

4.3.9. 9. 极值点

极值点是指对象的最上面、最下面、最右边和最左边的点。

>>> 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])

例如,如果我把它应用到印度地图上,我会得到以下结果:

4.3.10. 额外资源

4.3.11. 练习

  1. MatlabRegionProps文档中还有一些特性。试着去实现它们。