# 4.3. 轮廓特性¶

（注：质心、面积、周长等也属于这一类，但我们在上一章已经看到了）

## 4.3.1. 1. 纵横比¶

$Aspect \; Ratio = \frac{Width}{Height}$
>>> %matplotlib inline
>>> import matplotlib.pyplot as plt
>>>
>>> import cv2
>>> import numpy as np
>>> 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)

>>> pixelpoints

array([[205, 323],
[205, 324],
[206, 322],
...,
[399, 637],
[399, 638],
[399, 639]])


## 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.11. 练习¶

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