OpenCV Python 轮廓属性
【目标】
- 宽高比
- 扩展度
- 紧致度
- 等效直径
- 方向
【代码】
import cv2
import numpy as np
img = cv2.imread("Australia.png", 0)
imgcolor = cv2.imread("Australia.png", 1)
# 二值化
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
# 查找轮廓
contours, hier = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
# 画轮廓
cv2.drawContours(imgcolor, contours, -1, (0, 255, 0), 2, cv2.LINE_4)
# 宽高比
x, y, w, h = cv2.boundingRect(cnt)
aspect_ratio = float(w) / h
print('宽高比:', aspect_ratio)
# 扩展度
## 轮廓面积与外接矩形面积比
area = cv2.contourArea(cnt)
rect_area = w * h
extend = (float)(area)/rect_area
print('扩展度:', extend)
# 紧致度
## 轮廓面积与凸包面积比
hull = cv2.convexHull(cnt)
hull_area = cv2.contourArea(hull)
solidity = (float)(area) / hull_area
print('紧致度:', solidity)
cv2.drawContours(imgcolor, [hull], 0, (0, 128, 128), 2, cv2.LINE_4)
# 等效直径
equi_diameter = np.sqrt(4 * area / np.pi)
print("等效直径:", equi_diameter)
# circularity = (4 * area ) / (equi_diameter * equi_diameter * np.pi)
# print("圆度:", circularity)
# 方向
# 椭圆拟合的返回值,旋转矩形
## center: 中心
## size: 矩形的宽高
## angle: 旋转角度
ellipse = cv2.fitEllipse(cnt)
(x, y), (MajorA, MinorA), angle = ellipse
# 画椭圆和中心
cv2.ellipse(imgcolor, ellipse, (100, 0, 255), 2)
cv2.circle(imgcolor, (int(x), int(y)), 3, (255, 0, 255), 2)
print("角度:", angle)
# 找到全局中最大值和最小值
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(img, mask=~thresh)
cv2.circle(imgcolor, min_loc, 3, (0, 0, 255), 2)
cv2.circle(imgcolor, max_loc, 3, (0, 0, 255), 2)
print("最大值、最小值以及对应的位置", min_val, max_val, min_loc, max_loc)
# 平均颜色和亮度
mean_val = cv2.mean(img, mask=~thresh)
print(mean_val)
# 最左,最右,最上,最下的顶点
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])
print(leftmost, rightmost, topmost, bottommost)
cv2.circle(imgcolor, leftmost, 3, (0, 128, 255), 3)
cv2.circle(imgcolor, rightmost, 3, (0, 128, 255), 3)
cv2.circle(imgcolor, topmost, 3, (0, 128, 255), 3)
cv2.circle(imgcolor, bottommost, 3, (0, 128, 255), 3)
cv2.imshow("thresh", ~thresh)
cv2.imshow("imgcolor", imgcolor)
cv2.waitKey(0)
cv2.destroyAllWindows()
【接口】
见 【OpenCV-Python】教程:3-9 轮廓(2)轮廓特征