Python Opencv面积

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python Opencv面积

Vertira   2022-05-28 我要评论

一、cv2.contourArea

起初使用该函数的时候看不懂返回的面积,有0有负数的,于是研究了一下。

opencv计算轮廓内面积函数使用的是格林公式计算轮廓内面积的,公式如下:

由于格林公式计算单连通域面积是以逆时针为正方向的,而有时候我们输入的边缘数组是按照顺时针输入的,所以导致计算面积会出现负数;计算面积存在0的情况一般是只存在一个像素点作为边缘点,所以面积为0。

 代码如下:

img = cv2.imread('test.png', 0)
contours, hierarchy = cv2.findContours(img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_L1)
area = []
topk_contours =[]
for i in range(len(contours)):
    a = cv2.contourArea(contours[i], True)
    area.append(abs(a))
topk = 2 #取最大面积的个数
for i in range(2):
    top = area.index(max(area))
    area.pop(top)
    topk_contours.append(contours[top])
x, y = img.shape
mask = np.zeros((x, y, 3))
mask_img = cv2.drawContours(mask, topk_contours, -1, (255, 255, 255), 1)
cv2.imwrite('mask_img.png', mask_img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
cv2.imshow('mask_img:', mask_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果如下:

二、按像素个数计算连通域面积

这边再给出一种用边缘内像素个数来计算连通域面积的方法:

img = cv2.imread('test.png', 0)
contours, hierarchy = cv2.findContours(img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_L1)
area = []
topk_contours =[]
x, y = img.shape
for i in range(len(contours)):
    # 对每一个连通域使用一个掩码模板计算非0像素(即连通域像素个数)
    single_masks = np.zeros((x, y)) 
    fill_image = cv2.fillConvexPoly(single_masks, contours[i], 255)
    pixels = cv2.countNonZero(fill_image)
    area.append(pixels)
topk = 2 #取最大面积的个数
for i in range(2):
    top = area.index(max(area))
    area.pop(top)
    topk_contours.append(contours[top])
mask = np.zeros((x,y,3))
mask_img = cv2.drawContours(mask, topk_contours, -1, (255, 255, 255), 1)
cv2.imwrite('mask_img.png', mask_img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
cv2.imshow('mask_img:', mask_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们