【coco】掩膜mask影像转coco格式txt(含python代码)

2023-12-14 19:28

本文主要是介绍【coco】掩膜mask影像转coco格式txt(含python代码),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

        最近在做实例分割,遇到二值掩膜影像——coco格式txt的实例分割转换问题,困扰很久,不知道怎么转换,转出来的txt没法用代码成功读取。一系列问题,索性记录下自己的结局路程,方便大家python代码自取。

 


目录

📞📞1.coco格式示例

📗 images模块

📘 categories模块

📙annotation模块

📷📷2.环境准备

📢📢3.maskToanno函数定义

⏰⏰4.images模块内容写入txt

📡📡5.categories模块内容写入txt

🛁🛁6.annotation模块内容写入txt

🔋🔋7.完整python代码

整理不易,欢迎一键三连!!!

送你们一条美丽的--分割线--


📞📞1.coco格式示例

        coco格式txt文件示例:

        主要包含三个模块:

  • images
  • categories
  • annotations

        其中每个模块都由好多个分块组成,images和categories比较简单。

📗 images模块

        images里主要记录的是每张image的长宽,id和文件名信息,注意此处的文件名必须是images文件名,labels也得是相同的文件名,不然索引不到。id从1开始,依次向下编号。

images[
{"height": 512,"width": 512,"id": 1,"file_name": "1.png"
}
...
...
...
{"height": 512,"width": 512,"id": 100,"file_name": "100.png"
}]

📘 categories模块

        categories模块记录的是所有样本的类别信息,name为类别名称,id从1开始,依次向下编号,supercategory表示该类别的从属类别,理解起来比较简单,比如name为bus,supercategory就可以为car,name为cat,supercategory就可以为animal。如果没有多级类别,可以将name和supercategory写出相同的,像我下面写的。

"categories": [
{"supercategory": "land","id": 1,"name": "land"
}
{"supercategory": "land","id": 2,"name": "land2"
}
...
...
...
{"supercategory": "land","id": n,"name": "landn"
}
],

📙annotation模块

         annotation模块主要记录的是label信息,也是最关键的内容,此处以实例分割为例进行讲解,因为coco格式可以做的任务太多,此处仅限实例分割或者语义分割。

annotation模块的一个完整内容包括:

  • segmentation记录目标的边界坐标点位置信息,可以是很长但是要记得是双[[...]];
  • area记录得是目标得面积信息,这个可以自动计算,后面会细讲;
  • iscrowd代表一个目标是否被切分成多块,比如一个猫得身体和尾巴被一只狗头挡住,分开成2部分。0代表没有切分,1代表切分;
  • image_id表示这个目标所对应得原始影像得id编号,与images模块里的id是一一对应的关系;
  • bbox指这个目标的外界矩形框的位置信息;
  • category_id表示这个目标的类别信息,与categories模块里的id是一一对应的关系;
  • id代表目标的编号信息,可以与images个数不一致,因为一张图上很可能会有多个目标。
"annotations": [
{"segmentation": [[276,286,275,287,274,287,273,287,]],"area": 2148,"iscrowd": 0,"image_id": 2,"bbox": [233.0,286.0,49.0,68.0],"category_id": 1,"id": 1
},...{"segmentation": [[276,286,275,287,274,287,273,287,]],"area": 248,"iscrowd": 0,"image_id": 5,"bbox": [233.0,286.0,49.0,68.0],"category_id": 2,"id":100
},

📷📷2.环境准备

        代码所需环境包有:json、numpy、pycocotools、OpenCV、os、sys

        包导入命令:

import jsonimport numpy as npfrom pycocotools import maskimport cv2import osimport sys

📢📢3.maskToanno函数定义

输入:round_truth_binary_mask, ann_count, category_id

输出:annotations

        python代码如下:

def maskToanno(ground_truth_binary_mask, ann_count, category_id):contours, _ = cv2.findContours(ground_truth_binary_mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)  # 根据二值图找轮廓annotations = [] #一幅图片所有的annotatonsglobal segmentation_id# print(ann_count)# 对每个实例进行处理for i in range(len(contours)):# print(i)# 生成二值的黑色图片x = np.zeros((512, 512))cv2.drawContours(x, contours, i, (1, 1, 1), -1)  # 将单个mask表示为二值图的形式ground_truth_binary_mask_id = np.array(x, dtype=object).astype(np.uint8)fortran_ground_truth_binary_mask = np.asfortranarray(ground_truth_binary_mask_id)# 求每个mask的面积和框encoded_ground_truth = mask.encode(fortran_ground_truth_binary_mask)ground_truth_area = mask.area(encoded_ground_truth)ground_truth_bounding_box = mask.toBbox(encoded_ground_truth)contour, _ = cv2.findContours(ground_truth_binary_mask_id, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)# contour = measure.find_contours(ground_truth_binary_mask_id, 0.5)# print(contour)annotation = {"segmentation": [],"area": ground_truth_area.tolist(),"iscrowd": 0,"image_id": ann_count,"bbox": ground_truth_bounding_box.tolist(),"category_id": category_id,"id": segmentation_id}#print(contour)# 求segmentation部分contour = np.flip(contour, axis=0)segmentation = contour.ravel().tolist()if len(segmentation)<=4:continueannotation["segmentation"].append(segmentation)annotations.append(annotation)segmentation_id = segmentation_id + 1return annotations

⏰⏰4.images模块内容写入txt

输入:jsonpath

输出:jsonpath

        将jsonpath路径下的txt文件打开,若image存在且对应文件名的label文件存在,就可以写image的images模块信息,python代码如下:

with io.open(jsonPath, 'w', encoding='utf8') as output:# 那就全部写在一个文件夹好了# 先写images的信息output.write(unicode('{\n'))output.write(unicode('"images": [\n'))for image in rgb_image_files:if os.path.exists(os.path.join(block_mask_path, image)):output.write(unicode('{'))annotation = {"height": 512,"width": 512,"id": imageCount,"file_name": image}str_ = json.dumps(annotation, indent=4)str_ = str_[1:-1]if len(str_) > 0:output.write(unicode(str_))imageCount = imageCount + 1if (image == rgb_image_files[-1]):output.write(unicode('}\n'))else:output.write(unicode('},\n'))

📡📡5.categories模块内容写入txt

输入:jsonpath

输出:jsonpath

        将jsonpath路径下的txt文件打开,将categories模块里的supercategory、id、name信息写入txt,此处的categories信息只是示例,可以根据自己的类别信息修改,python代码如下:

with io.open(jsonPath, 'w', encoding='utf8') as output:output.write(unicode('"categories": [\n'))output.write(unicode('{\n'))categories = {"supercategory": "land","id": 1,"name": "land"}str_ = json.dumps(categories, indent=4)str_ = str_[1:-1]if len(str_) > 0:output.write(unicode(str_))output.write(unicode('}\n'))output.write(unicode('],\n'))

🛁🛁6.annotation模块内容写入txt

输入:jsonpath

输出:jsonpath

        将jsonpath路径下的txt文件打开,若label存在且对应文件名的image文件存在,就可以把annotation模块里的信息写入txt,python代码如下:

with io.open(jsonPath, 'w', encoding='utf8') as output:output.write(unicode('"annotations": [\n'))for i in range(len(block_mask_image_files)):if os.path.exists(os.path.join(path, block_mask_image_files[i])):block_image = block_mask_image_files[i]# 读取二值图像block_im = cv2.imread(os.path.join(block_mask_path, block_image), 0)_, block_im = cv2.threshold(block_im, 100, 1, cv2.THRESH_BINARY)if not block_im is None:block_im = np.array(block_im, dtype=object).astype(np.uint8)block_anno = maskToanno(block_im, annCount, 1)for b in block_anno:str_block = json.dumps(b, indent=4)str_block = str_block[1:-1]if len(str_block) > 0:output.write(unicode('{\n'))output.write(unicode(str_block))if (block_image == rgb_image_files[-1] and b == block_anno[-1]):output.write(unicode('}\n'))else:output.write(unicode('},\n'))annCount = annCount + 1else:print(block_image)

🔋🔋7.完整python代码

        二值掩膜mask影像转coco格式的实例分割txt完整python代码如下:

import json
import numpy as np
from pycocotools import mask
import cv2
import os
import sysif sys.version_info[0] >= 3:unicode = strimport io
# 实例的id,每个图像有多个物体每个物体的唯一id
global segmentation_id
segmentation_id = 1
# annotations部分的实现
def maskToanno(ground_truth_binary_mask, ann_count, category_id):contours, _ = cv2.findContours(ground_truth_binary_mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)  # 根据二值图找轮廓annotations = [] #一幅图片所有的annotatonsglobal segmentation_id# print(ann_count)# 对每个实例进行处理for i in range(len(contours)):# print(i)# 生成二值的黑色图片x = np.zeros((512, 512))cv2.drawContours(x, contours, i, (1, 1, 1), -1)  # 将单个mask表示为二值图的形式ground_truth_binary_mask_id = np.array(x, dtype=object).astype(np.uint8)fortran_ground_truth_binary_mask = np.asfortranarray(ground_truth_binary_mask_id)# 求每个mask的面积和框encoded_ground_truth = mask.encode(fortran_ground_truth_binary_mask)ground_truth_area = mask.area(encoded_ground_truth)ground_truth_bounding_box = mask.toBbox(encoded_ground_truth)contour, _ = cv2.findContours(ground_truth_binary_mask_id, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)# contour = measure.find_contours(ground_truth_binary_mask_id, 0.5)# print(contour)annotation = {"segmentation": [],"area": ground_truth_area.tolist(),"iscrowd": 0,"image_id": ann_count,"bbox": ground_truth_bounding_box.tolist(),"category_id": category_id,"id": segmentation_id}#print(contour)# 求segmentation部分contour = np.flip(contour, axis=0)segmentation = contour.ravel().tolist()if len(segmentation)<=4:continueannotation["segmentation"].append(segmentation)annotations.append(annotation)segmentation_id = segmentation_id + 1return annotations# mask图像路径
block_mask_path = '/labels_512'
block_mask_image_files = sorted(os.listdir(block_mask_path))# coco json保存的位置
jsonPath = "/data/temp.json"
annCount = 1
imageCount = 1
# 原图像的路径, 原图像和mask图像的名称是一致的。
path = "/images_512"
rgb_image_files = sorted(os.listdir(path))with io.open(jsonPath, 'w', encoding='utf8') as output:# 那就全部写在一个文件夹好了# 先写images的信息output.write(unicode('{\n'))output.write(unicode('"images": [\n'))for image in rgb_image_files:if os.path.exists(os.path.join(block_mask_path, image)):output.write(unicode('{'))annotation = {"height": 512,"width": 512,"id": imageCount,"file_name": image}str_ = json.dumps(annotation, indent=4)str_ = str_[1:-1]if len(str_) > 0:output.write(unicode(str_))imageCount = imageCount + 1if (image == rgb_image_files[-1]):output.write(unicode('}\n'))else:output.write(unicode('},\n'))output.write(unicode('],\n'))# 接下来写cateoutput.write(unicode('"categories": [\n'))output.write(unicode('{\n'))categories = {"supercategory": "land","id": 1,"name": "land"}str_ = json.dumps(categories, indent=4)str_ = str_[1:-1]if len(str_) > 0:output.write(unicode(str_))output.write(unicode('}\n'))output.write(unicode('],\n'))# 写annotationsoutput.write(unicode('"annotations": [\n'))for i in range(len(block_mask_image_files)):if os.path.exists(os.path.join(path, block_mask_image_files[i])):block_image = block_mask_image_files[i]# 读取二值图像block_im = cv2.imread(os.path.join(block_mask_path, block_image), 0)_, block_im = cv2.threshold(block_im, 100, 1, cv2.THRESH_BINARY)if not block_im is None:block_im = np.array(block_im, dtype=object).astype(np.uint8)block_anno = maskToanno(block_im, annCount, 1)for b in block_anno:str_block = json.dumps(b, indent=4)str_block = str_block[1:-1]if len(str_block) > 0:output.write(unicode('{\n'))output.write(unicode(str_block))if (block_image == rgb_image_files[-1] and b == block_anno[-1]):output.write(unicode('}\n'))else:output.write(unicode('},\n'))annCount = annCount + 1else:print(block_image)output.write(unicode(']\n'))output.write(unicode('}\n'))

有问题,欢迎评论区交流~~~

整理不易,欢迎一键三连!!!

送你们一条美丽的--分割线--


🌷🌷🍀🍀🌾🌾🍓🍓🍂🍂🙋🙋🐸🐸🙋🙋💖💖🍌🍌🔔🔔🍉🍉🍭🍭🍋🍋🍇🍇🏆🏆📸📸⛵⛵⭐⭐🍎🍎👍👍🌷🌷

 

这篇关于【coco】掩膜mask影像转coco格式txt(含python代码)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/493696

相关文章

使用Python将PDF表格自动提取并写入Word文档表格

《使用Python将PDF表格自动提取并写入Word文档表格》在实际办公与数据处理场景中,PDF文件里的表格往往无法直接复制到Word中,本文将介绍如何使用Python从PDF文件中提取表格数据,并将... 目录引言1. 加载 PDF 文件并准备 Word 文档2. 提取 PDF 表格并创建 Word 表格

使用Python实现局域网远程监控电脑屏幕的方法

《使用Python实现局域网远程监控电脑屏幕的方法》文章介绍了两种使用Python在局域网内实现远程监控电脑屏幕的方法,方法一使用mss和socket,方法二使用PyAutoGUI和Flask,每种方... 目录方法一:使用mss和socket实现屏幕共享服务端(被监控端)客户端(监控端)方法二:使用PyA

Python列表的创建与删除的操作指南

《Python列表的创建与删除的操作指南》列表(list)是Python中最常用、最灵活的内置数据结构之一,它支持动态扩容、混合类型、嵌套结构,几乎无处不在,但你真的会创建和删除列表吗,本文给大家介绍... 目录一、前言二、列表的创建方式1. 字面量语法(最常用)2. 使用list()构造器3. 列表推导式

Python使用Matplotlib和Seaborn绘制常用图表的技巧

《Python使用Matplotlib和Seaborn绘制常用图表的技巧》Python作为数据科学领域的明星语言,拥有强大且丰富的可视化库,其中最著名的莫过于Matplotlib和Seaborn,本篇... 目录1. 引言:数据可视化的力量2. 前置知识与环境准备2.1. 必备知识2.2. 安装所需库2.3

HTML5的input标签的`type`属性值详解和代码示例

《HTML5的input标签的`type`属性值详解和代码示例》HTML5的`input`标签提供了多种`type`属性值,用于创建不同类型的输入控件,满足用户输入的多样化需求,从文本输入、密码输入、... 目录一、引言二、文本类输入类型2.1 text2.2 password2.3 textarea(严格

Python数据验证神器Pydantic库的使用和实践中的避坑指南

《Python数据验证神器Pydantic库的使用和实践中的避坑指南》Pydantic是一个用于数据验证和设置的库,可以显著简化API接口开发,文章通过一个实际案例,展示了Pydantic如何在生产环... 目录1️⃣ 崩溃时刻:当你的API接口又双叒崩了!2️⃣ 神兵天降:3行代码解决验证难题3️⃣ 深度

Python+FFmpeg实现视频自动化处理的完整指南

《Python+FFmpeg实现视频自动化处理的完整指南》本文总结了一套在Python中使用subprocess.run调用FFmpeg进行视频自动化处理的解决方案,涵盖了跨平台硬件加速、中间素材处理... 目录一、 跨平台硬件加速:统一接口设计1. 核心映射逻辑2. python 实现代码二、 中间素材处

python中的flask_sqlalchemy的使用及示例详解

《python中的flask_sqlalchemy的使用及示例详解》文章主要介绍了在使用SQLAlchemy创建模型实例时,通过元类动态创建实例的方式,并说明了如何在实例化时执行__init__方法,... 目录@orm.reconstructorSQLAlchemy的回滚关联其他模型数据库基本操作将数据添

JAVA项目swing转javafx语法规则以及示例代码

《JAVA项目swing转javafx语法规则以及示例代码》:本文主要介绍JAVA项目swing转javafx语法规则以及示例代码的相关资料,文中详细讲解了主类继承、窗口创建、布局管理、控件替换、... 目录最常用的“一行换一行”速查表(直接全局替换)实际转换示例(JFramejs → JavaFX)迁移建

Python实现快速扫描目标主机的开放端口和服务

《Python实现快速扫描目标主机的开放端口和服务》这篇文章主要为大家详细介绍了如何使用Python编写一个功能强大的端口扫描器脚本,实现快速扫描目标主机的开放端口和服务,感兴趣的小伙伴可以了解下... 目录功能介绍场景应用1. 网络安全审计2. 系统管理维护3. 网络故障排查4. 合规性检查报错处理1.