本文將結(jié)合實(shí)例代碼,介紹 OpenCV 如何查找輪廓、獲取邊界框。
代碼: contours.py
OpenCV 提供了 findContours 函數(shù)查找輪廓,需要以二值化圖像作為輸入、并指定些選項(xiàng)調(diào)用即可。
![](/d/20211017/c321389016362ef5f746d4fdcd18fe4b.gif)
我們以下圖作為示例:
![](/d/20211017/747e65590e92049c91a9b42e13775a86.gif)
二值化圖像
代碼工程 data/
提供了小狗和紅球的二值化掩膜圖像:
![](/d/20211017/69ac82636ff25a36bc5b0206f27cd23d.gif)
![](/d/20211017/d274ed3d9edea462189b120717dddfd9.gif)
其使用預(yù)訓(xùn)練好的實(shí)例分割模型來生成的,腳本可見 detectron2_seg_threshold.py。模型檢出結(jié)果,如下:
![](/d/20211017/f2538355056daf99fa0365bcccf8456b.gif)
模型用的 Mask R-CNN 已有預(yù)測邊框。但其他模型會(huì)有只出預(yù)測掩膜的,此時(shí)想要邊框就可以使用 OpenCV 來提取。
本文代碼也提供了根據(jù)色域來獲取紅球掩膜的辦法:
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)
![](/d/20211017/f4b93527743fdee201c83cd6406c3704.gif)
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)
![](/d/20211017/63358fc6388da046e1f7e8e5d1754234.gif)
參考
OpenCV Tutorials / Image Processing
到此這篇關(guān)于OpenCV實(shí)現(xiàn)查找輪廓的實(shí)例的文章就介紹到這了,更多相關(guān)OpenCV 查找輪廓內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Python OpenCV 基于圖像邊緣提取的輪廓發(fā)現(xiàn)函數(shù)
- Python OpenCV 圖像區(qū)域輪廓標(biāo)記(框選各種小紙條)
- python 基于opencv 繪制圖像輪廓
- Python+OpenCV圖像處理——實(shí)現(xiàn)輪廓發(fā)現(xiàn)
- Python Opencv輪廓常用操作代碼實(shí)例解析
- opencv python 圖像輪廓/檢測輪廓/繪制輪廓的方法
- Python Opencv實(shí)現(xiàn)圖像輪廓識(shí)別功能
- python+opencv輪廓檢測代碼解析
- OpenCV-Python實(shí)現(xiàn)輪廓檢測實(shí)例分析