一、需求:
给出一张图片,估算最外轮廓区域面积
二、步骤:
1、读取图片信息
2、利用open-cv,自适应分割图片
3、提取最外轮廓像素值
4、利用像素值标记轮廓
5、计算轮廓面积
三、代码:
import cv2# 读取图片信息
img_path = r"D:\Desktop\img\out1.png"# 读取文件
mat_img = cv2.imread(img_path)
mat_img2 = cv2.imread(img_path, cv2.CV_8UC1)# 自适应分割
dst = cv2.adaptiveThreshold(mat_img2, 210, cv2.BORDER_REPLICATE, cv2.THRESH_BINARY_INV, 3, 10)
# 提取轮廓
contours, heridency = cv2.findContours(dst, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# 标记轮廓
cv2.drawContours(mat_img, contours, -1, (255, 0, 255), 3)x_list = []
y_list = []
for c in contours:for i in c:x_list.append(i[0][0])y_list.append(i[0][1])print(min(x_list), max(x_list))
print(min(y_list), max(y_list))# 计算轮廓面积
area = 0
for i in contours:area += cv2.contourArea(i)
print(area)# 图像show
cv2.imshow("window1", mat_img)
cv2.waitKey(0)
四、结果: