欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中OpenCV實(shí)現(xiàn)查找輪廓的實(shí)例

 更新時(shí)間:2021年06月08日 08:32:23   作者:GoCodingInMyWay  
本文將結(jié)合實(shí)例代碼,介紹 OpenCV 如何查找輪廓、獲取邊界框。具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文將結(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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論