基于Python和OpenCV的面积计算
import cv2
import numpy as np
image1 = cv2.imread("F:\\Python\\Image\\1.png",-1)
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()