網(wǎng)站首頁 編程語言 正文
一、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
相關(guān)推薦
- 2023-01-10 golang實現(xiàn)簡單的tcp數(shù)據(jù)傳輸_Golang
- 2022-04-30 C#操作DataGridView獲取或設(shè)置當前單元格的內(nèi)容_C#教程
- 2022-03-27 Python?提速器numba_python
- 2022-12-30 詳解C語言中的預處理命令_C 語言
- 2022-03-14 Failed to load ApplicationContext異常的解決思路
- 2022-11-15 如何使用ASP.NET?Core?配置文件_實用技巧
- 2022-09-02 selenium動態(tài)數(shù)據(jù)獲取的方法實現(xiàn)_python
- 2022-08-15 當添加一個鍵值對元素時,HashMap發(fā)生了什么?
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支