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

學(xué)無(wú)先后,達(dá)者為師

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

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

作者:Vertira ? 更新時(shí)間: 2022-06-01 編程語(yǔ)言

一、cv2.contourArea

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

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

由于格林公式計(jì)算單連通域面積是以逆時(shí)針為正方向的,而有時(shí)候我們輸入的邊緣數(shù)組是按照順時(shí)針輸入的,所以導(dǎo)致計(jì)算面積會(huì)出現(xiàn)負(fù)數(shù);計(jì)算面積存在0的情況一般是只存在一個(gè)像素點(diǎn)作為邊緣點(diǎn),所以面積為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 #取最大面積的個(gè)數(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é)果如下:

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

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

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)):
    # 對(duì)每一個(gè)連通域使用一個(gè)掩碼模板計(jì)算非0像素(即連通域像素個(gè)數(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 #取最大面積的個(gè)數(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

欄目分類
最近更新