日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Python+Opencv實現(xiàn)計算閉合區(qū)域面積_python

作者:Vertira ? 更新時間: 2022-06-01 編程語言

一、cv2.contourArea

起初使用該函數(shù)的時候看不懂返回的面積,有0有負數(shù)的,于是研究了一下。

opencv計算輪廓內(nèi)面積函數(shù)使用的是格林公式計算輪廓內(nèi)面積的,公式如下:

由于格林公式計算單連通域面積是以逆時針為正方向的,而有時候我們輸入的邊緣數(shù)組是按照順時針輸入的,所以導致計算面積會出現(xiàn)負數(shù);計算面積存在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 #取最大面積的個數(shù)
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()

結(jié)果如下:

二、按像素個數(shù)計算連通域面積

這邊再給出一種用邊緣內(nèi)像素個數(shù)來計算連通域面積的方法:

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像素(即連通域像素個數(shù))
    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 #取最大面積的個數(shù)
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()

原文鏈接:https://blog.csdn.net/Vertira/article/details/123815246

欄目分類
最近更新