将图像分割的 mask 转换成目标检测的 bbox

本文介绍了一种基于连通组件分析的目标检测方法,通过OpenCV库实现图像中多个目标的定位与绘制边界框,展示了如何使用Python进行图像处理和目标识别。

在这里插入图片描述

def find_bbox(mask):
    _, labels, stats, centroids = cv2.connectedComponentsWithStats(mask.astype(np.uint8))
    stats = stats[stats[:,4].argsort()]
    return stats[:-1]

mask = label[4]
ax = plt.axes()
plt.imshow(mask,cmap='bone')
bboxs = find_bbox(mask)
for j in bboxs: 
    rect = patches.Rectangle((j[0],j[1]),j[2],j[3],linewidth=1,edgecolor='r',facecolor='none')
    ax.add_patch(rect)
plt.show() 

### 将图像分割结果(Mask)转换为JSON文件 为了实现从mask到JSON文件的转换,通常需要编写一段Python脚本处理此过程。该操作涉及读取mask图像并解析其像素值来构建相应的多边形或边界框表示形式,最终将这些几何对象及其属性序列化至JSON结构中。 #### 使用`mask_to_json.py`工具进行转换 对于批量转换任务,可以直接利用命令行调用专门编写的Python脚本来完成工作: ```bash python mask_to_json.py 输入文件夹或单张mask图片 输出文件夹 ``` 上述指令将会遍历指定目录下的所有mask图像,并将其逐一转换为目标格式——即COCO JSON标注样式的数据集[^1]。 #### Mask转JSON的具体流程 具体来说,在执行转换的过程中涉及到以下几个方面的工作: - **加载mask图像**:通过PIL库或其他方式打开二值化的mask图像; - **提取轮廓信息**:基于OpenCV等计算机视觉库识别前景区域边缘; - **创建JSON结构体**:定义好用于存储各类元数据以及形状描述符的对象模板; - **写入目标文件**:最后一步就是把准备好的字典序列化成字符串并保存下来。 下面给出了一段简化版代码片段作为参考: ```python import cv2 from pycocotools import mask as cocomask import numpy as np import json def binary_mask_to_polygon(binary_mask, tolerance=0): """Converts a binary mask to COCO polygon representation""" padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0) contours, _ = cv2.findContours(padded_binary_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours = np.subtract(contours, 1) segmentations = [] for contour in contours: # Filter out small objects if contour.size >= 6: segmentation = contour.flatten().tolist() segmentations.append(segmentation) return segmentations image_id = "example_image" height, width = image.shape[:2] annotations = [] for category_id, class_name in enumerate(classes_of_interest): binary_mask = (cv2.imread(mask_file_path, cv2.IMREAD_GRAYSCALE) == category_id).astype(np.uint8) polygons = binary_mask_to_polygon(binary_mask) annotation = { 'id': len(annotations), 'image_id': image_id, 'category_id': category_id, 'segmentation': polygons, 'bbox': list(cv2.boundingRect(np.array(polygons))), 'area': sum([cocomask.area(cocomask.frPyObjects([p], height, width)) for p in polygons]), 'iscrowd': 0 } annotations.append(annotation) output_dict = {"images": [{"file_name": file_name, "height": height, "width": width}], "annotations": annotations} with open(output_json_path, 'w') as f: json.dump(output_dict, f) ``` 这段程序展示了如何从给定的一组类别标签对应的mask映射关系出发,逐步建立起符合COCO标准的JSON文档框架[^3]。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颹蕭蕭

白嫖?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值