前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >OpenCV 查找轮廓

OpenCV 查找轮廓

作者头像
GoCoding
发布2021-06-22 19:31:39
8570
发布2021-06-22 19:31:39
举报
文章被收录于专栏:GoCodingGoCoding

本文将结合实例代码,介绍 OpenCV 如何查找轮廓、获取边界框。

  • 代码: contours.py[1]

OpenCV 提供了 findContours[2] 函数查找轮廓,需要以二值化图像作为输入、并指定些选项调用即可。

我们以下图作为示例:

二值化图像

代码工程 data/ 提供了小狗和红球的二值化掩膜图像:

其使用预训练好的实例分割模型来生成的,脚本可见 detectron2_seg_threshold.py[3]。模型检出结果,如下:

模型用的 Mask R-CNN 已有预测边框。但其他模型会有只出预测掩膜的,此时想要边框就可以使用 OpenCV 来提取。

本文代码也提供了根据色域来获取红球掩膜的办法:

代码语言:javascript
复制
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]))

# 清除小点(可选)
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3), (1, 1))
thres = cv.morphologyEx(thres, cv.MORPH_OPEN, kernel)

查找轮廓

代码语言:javascript
复制
# 查找轮廓
#  cv.RETR_EXTERNAL: 只查找外部轮廓
contours, hierarchy = cv.findContours(
  threshold, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

# 近似轮廓,减点(可选)
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 获取边界框,并绘制:

代码语言:javascript
复制
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 获取边界圈,并绘制:

代码语言:javascript
复制
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[4]

脚注

[1]

contours.py: https://github.com/ikuokuo/start-opencv/blob/master/src/python/processing/contours.py

[2]

findContours: https://docs.opencv.org/master/d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0

[3]

detectron2_seg_threshold.py: https://github.com/ikuokuo/start-opencv/blob/master/scripts/detectron2_seg_threshold.py

[4]

OpenCV Tutorials / Image Processing: https://docs.opencv.org/master/d7/da8/tutorial_table_of_content_imgproc.html

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-06-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 GoCoding 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 二值化图像
  • 查找轮廓
  • 获取边界框
  • 参考
    • 脚注
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档