Python中OpenCV实现查找轮廓的实例
作者:GoCodingInMyWay 时间:2023-12-05 05:26:24
本文将结合实例代码,介绍 OpenCV 如何查找轮廓、获取边界框。
代码: contours.py
OpenCV 提供了 findContours 函数查找轮廓,需要以二值化图像作为输入、并指定些选项调用即可。
我们以下图作为示例:
二值化图像
代码工程 data/
提供了小狗和红球的二值化掩膜图像:
其使用预训练好的实例分割模型来生成的,脚本可见 detectron2_seg_threshold.py。模型检出结果,如下:
模型用的 Mask R-CNN 已有预测边框。但其他模型会有只出预测掩膜的,此时想要边框就可以使用 OpenCV 来提取。
本文代码也提供了根据 * 来获取红球掩膜的办法:
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)
查找轮廓
# 查找轮廓
# 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
获取边界框,并绘制:
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
来源:https://www.cnblogs.com/gocodinginmyway/p/14860999.html
标签:OpenCV,查找轮廓
0
投稿
猜你喜欢
Python+Pygame实战之吃豆豆游戏的实现
2022-10-01 17:29:39
python生成requirements.txt文件的推荐方法
2021-02-04 01:02:30
PDO::inTransaction讲解
2023-06-06 08:32:27
详解用 python-docx 创建浮动图片
2021-07-16 13:32:12
解决python3.6用cx_Oracle库连接Oracle的问题
2023-06-12 02:38:46
Django创建项目+连通mysql的操作方法
2024-01-12 17:16:42
客户端限制只能上传jpg格式图片的js代码
2023-07-16 00:56:04
JavaScript中把数字转换为字符串的程序代码
2024-05-03 15:59:46
利用Python实现原创工具的Logo与Help
2021-06-03 20:43:05
python使用Tkinter显示网络图片的方法
2021-09-26 18:25:38
javascript demo 基本技巧
2024-04-29 13:24:45
为什么不压缩 HTML
2010-05-07 12:37:00
PHP图片上传类带图片显示
2024-05-22 10:06:19
Python help()函数用法详解
2022-09-15 13:15:34
用户体验设计答疑对话(半吊子和纯外行)
2010-11-30 21:27:00
coreseek 搜索英文的问题详解
2023-11-20 14:12:10
python TKinter弹出式菜单的实例方法
2023-03-25 05:59:54
在python里创建一个任务(Task)实例
2023-09-12 23:24:16
JS模拟简易滚动条效果代码(附demo源码)
2024-04-23 09:22:45
php输出xml必须header的解决方法
2023-09-11 20:00:16