基于Python和OpenCV的面积计算

基于Python和OpenCV的面积计算

import cv2
import numpy as np

image1 = cv2.imread("F:\\Python\\Image\\1.png",-1)
#灰度转换CV_RGB2GRAY
ColorImage1 = cv2.cvtColor(image1,cv2.COLOR_RGB2GRAY)
#二值化
ret,ThresholdImage1=cv2.threshold(ColorImage1, 20, 255, cv2.THRESH_BINARY)
#取反
ThresholdImage1 = cv2.bitwise_not(ThresholdImage1)

ret, labels, stats, centroid = cv2.connectedComponentsWithStats(ThresholdImage1)
max_area = sorted(stats, key = lambda s : s[-1], reverse = False)[-2]

for i, stat in enumerate(stats):
    #获取最大
    max_area = sorted(stats, key = lambda s : s[-1], reverse = False)[-2]
    #绘制连通区域
    cv2.rectangle(image1, (max_area[0], max_area[1]), (max_area[0] + max_area[2], max_area[1] + max_area[3]), (25, 25, 255), 3)
    #按照连通区域的索引来打上标签
    cv2.putText(image1, str(i+1), (max_area[0], max_area[1] + 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 25, 25), 2)
    

cv2.imshow("threshold",ThresholdImage1)
cv2.imshow('connectedComponent', image1)

cv2.waitKey(0)
cv2.destroyAllWindows()

你可能感兴趣的:(opencv,计算机视觉,python)