本文將結(jié)合實(shí)例代碼,介紹 OpenCV 如何查找輪廓、獲取邊界框。
代碼: contours.py
OpenCV 提供了 findContours 函數(shù)查找輪廓,需要以二值化圖像作為輸入、并指定些選項(xiàng)調(diào)用即可。
我們以下圖作為示例:
代碼工程 data/
提供了小狗和紅球的二值化掩膜圖像:
其使用預(yù)訓(xùn)練好的實(shí)例分割模型來(lái)生成的,腳本可見(jiàn) detectron2_seg_threshold.py。模型檢出結(jié)果,如下:
模型用的 Mask R-CNN 已有預(yù)測(cè)邊框。但其他模型會(huì)有只出預(yù)測(cè)掩膜的,此時(shí)想要邊框就可以使用 OpenCV 來(lái)提取。
本文代碼也提供了根據(jù)色域來(lái)獲取紅球掩膜的辦法:
import cv2 as cv import numpy as np # 讀取圖像 img = cv.imread(args.image, cv.IMREAD_COLOR) # HSV 閾值,獲取掩膜 def _threshold_hsv(image, lower, upper): hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV) mask = cv.inRange(hsv, lower, upper) result = cv.bitwise_and(image, image, mask=mask) return result, mask _, thres = _threshold_hsv(img, np.array([0,110,190]), np.array([7,255,255])) # 清除小點(diǎn)(可選) kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3), (1, 1)) thres = cv.morphologyEx(thres, cv.MORPH_OPEN, kernel)
# 查找輪廓 # cv.RETR_EXTERNAL: 只查找外部輪廓 contours, hierarchy = cv.findContours( threshold, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) # 近似輪廓,減點(diǎn)(可選) contours_poly = [cv.approxPolyDP(c, 3, True) for c in contours] # 繪制輪廓 h, w = threshold.shape[:2] drawing = np.zeros((h, w, 3), dtype=np.uint8) for i in range(len(contours)): cv.drawContours(drawing, contours_poly, i, (0, 255, 0), 1, cv.LINE_8, hierarchy)
boundingRect
獲取邊界框,并繪制:
for contour in contours_poly: rect = cv.boundingRect(contour) cv.rectangle(drawing, (int(rect[0]), int(rect[1])), (int(rect[0]+rect[2]), int(rect[1]+rect[3])), (0, 255, 0), 2, cv.LINE_8)
minEnclosingCircle
獲取邊界圈,并繪制:
for contour in contours_poly: center, radius = cv.minEnclosingCircle(contour) cv.circle(drawing, (int(center[0]), int(center[1])), int(radius), (0, 255, 0), 2, cv.LINE_8)
OpenCV Tutorials / Image Processing
到此這篇關(guān)于OpenCV實(shí)現(xiàn)查找輪廓的實(shí)例的文章就介紹到這了,更多相關(guān)OpenCV 查找輪廓內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:聊城 揚(yáng)州 牡丹江 撫州 六盤(pán)水 迪慶 南寧 楊凌
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python中OpenCV實(shí)現(xiàn)查找輪廓的實(shí)例》,本文關(guān)鍵詞 Python,中,OpenCV,實(shí)現(xiàn),查找,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。