【实例分割】可视化COCO格式Mask分割标注

可视化代码:

import json
import os
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageColor

def visualise_coco_segmentation(json_file_path, image_dir, output_dir, label_dir, categories, colors):
    category_colors = {category: (color[0], color[1], color[2], 128) for category, color in zip(categories, colors)}

    with open(json_file_path, 'r') as f:
        coco_data = json.load(f)

    images = coco_data['images']
    annotations = coco_data['annotations']
    categories = coco_data['categories']

    for image_info in images:
        image_id = image_info['id']
        image_filename = image_dir + '/' + image_info['file_name']
        image_annotations = [ann for ann in annotations if ann['image_id'] == image_id]
        img = Image.open(image_filename).convert('RGBA')
        overlay = Image.new('RGBA', img.size)
        draw = ImageDraw.Draw(overlay)

        for ann in image_annotations:
            category_id = ann['category_id']
            category = next((cat for cat in categories if cat['id'] == category_id), None)
            if category is None:
                continue

            segmentation = ann['segmentation']
            label = category['name']
            color = category_colors.get(label, (255, 255, 255, 128))

            for segment in segmentation:
                reshaped_polygon = np.array(segment).reshape(-1, 2)
                pil_polygon = [tuple(point) for point in reshaped_polygon]
                draw.polygon(pil_polygon, fill=color)

        img = Image.alpha_composite(img, overlay)
        img = cv2.cvtColor(np.array(img), cv2.COLOR_RGBA2BGRA)

        label_file = f'{label_dir}/{os.path.splitext(image_info["file_name"])[0]}.txt'
        with open(label_file, 'r') as f:
            cnt_info = f.readlines()

        new_cnt_info = [line.replace("\n", "").split(" ") for line in cnt_info]
        height, width, _ = img.shape

        for new_info in new_cnt_info:
            cls_index = int(new_info[0])
            cls = categories[cls_index]['name']
            color = tuple(reversed(colors[cls_index][:3])) + (255,)

            s = [int(float(num) * (width if i % 2 == 0 else height)) for i, num in enumerate(new_info[1:])]
            vertices = np.array(s).reshape(-1, 2)
            x, y, w, h = cv2.boundingRect(vertices)
            # cv2.rectangle(img, (x, y), (x + w, y + h), color, 6)

        output_filename = os.path.splitext(image_info['file_name'])[0] + '.jpg'
        output_path = os.path.join(output_dir, output_filename)
        cv2.imwrite(output_path, img)

        print(f'Image with bounding box processed and saved to {output_path}')

if __name__ == '__main__':
    categories = ['class 1', 'class 2', 'class 3']
    colors = [(255, 0, 217), (39, 26, 213), (140, 224, 56)]
    visualise_coco_segmentation(json_file_path='D:\\coco\\annotations\\instances_test2017.json',
                                image_dir="D:\\YOLO\\images\\test",
                                output_dir='D:\\Ground-truth',
                                label_dir="D:\\YOLO\\labels\\test",
                                categories=categories,
                                colors=colors)

<think>嗯,用户想找关于COCO实例分割数据集可视化的工具或方法。首先,我需要回忆一下之前学过的相关知识,以及参考提供的引用内容。根据引用[1],提到了COCO Viewer这个工具,基于Tkinter开发的,可以展示图像、标签、边界框和掩模。应该是个不错的选择。然后引用[2]中提到了一个Jupyter notebook,COCO_Image_Viewer.ipynb,可以用来验证转化后的数据质量,这也是一个可视化方法。引用[3]和[4]则提到了CSDN的博客,可能有代码示例或者教程。 用户的问题有两个可能的表达方式:如何对COCO实例分割数据集进行可视化,或者有什么工具可以使用。我需要先列出现有的工具和方法,然后分步骤说明。比如,使用COCO Viewer、使用官方API、使用Jupyter notebook、以及自定义脚本。这些都是常见的方法。 另外,要注意用户可能需要具体的操作步骤,比如安装步骤、代码示例等。比如,COCO Viewer可能需要安装Tkinter和相关依赖,而官方API可能需要安装pycocotools。对于不同的工具,需要给出具体的操作指南,确保用户能够按照步骤实现可视化。 同时,用户可能关心这些工具的优缺点,比如是否易于安装,是否需要编程基础,或者是否支持交互式操作。例如,COCO Viewer有图形界面,适合非编程用户,而使用Matplotlib自定义脚本则更适合需要灵活调整的开发人员。 还需要考虑用户可能的后续问题,比如如何处理数据转换,或者如何验证数据是否正确,这些在引用[2]和[4]中提到的工具可能相关,可以适当提及,但主要专注于可视化部分。 另外,注意回答的结构要清晰,分点说明,每个工具或方法单独作为一部分,包括简介、使用步骤、优缺点,这样用户容易理解。可能还需要给出示例代码,比如使用pycocotools加载数据集并显示标注的代码片段,帮助用户快速上手。 最后,相关问题部分需要考虑用户可能进一步的问题,比如数据转换、标注验证、与其他格式的互转,或者如何自定义可视化样式,这些都可以作为相关问题列出,帮助用户深入探索。</think>### 对COCO实例分割数据集的可视化方法及工具 #### 1. 使用**COCO Viewer**(基于Tkinter的图形化工具) - **简介**:COCO Viewer是一款开源工具,支持本地快速浏览COCO数据集中的图像、标签、边界框和分割掩模[^1]。 - **步骤**: 1. 下载项目代码:访问其GitHub仓库(需搜索相关开源项目)。 2. 安装依赖:确保Python环境已安装`tkinter`和`Pillow`库。 3. 加载JSON文件:输入COCO格式标注文件(如`instances_train2017.json`)和图像目录。 4. 交互式浏览:通过界面切换图像,查看实例分割掩模及类别标签。 - **优点**:无需编程,适合快速验证数据质量。 #### 2. 通过**COCO官方API**(pycocotools) - **简介**:COCO官方提供的Python API(`pycocotools`)支持加载数据集并绘制标注。 - **代码示例**: ```python from pycocotools.coco import COCO import matplotlib.pyplot as plt import cv2 # 初始化COCO API coco = COCO('annotations/instances_val2017.json') image_id = 139 # 示例图像ID img_info = coco.loadImgs([image_id])[0] image = cv2.imread(f'val2017/{img_info["file_name"]}') # 绘制标注 plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) ann_ids = coco.getAnnIds(imgIds=image_id) annotations = coco.loadAnns(ann_ids) coco.showAnns(annotations) plt.show() ``` - **优点**:灵活性强,适合开发中的调试[^3]。 #### 3. 使用**Jupyter Notebook工具**(COCO_Image_Viewer) - **简介**:通过Jupyter Notebook脚本(如`COCO_Image_Viewer.ipynb`)逐张查看图像及标注[^2]。 - **步骤**: 1. 安装依赖:`jupyterlab`, `matplotlib`, `pycocotools`。 2. 运行notebook:加载JSON和图像路径,遍历可视化。 - **优点**:适合需要代码交互的开发者。 #### 4. 自定义脚本(Matplotlib + OpenCV) - **简介**:手动解析COCO JSON文件,使用OpenCV或Matplotlib绘制边界框和掩模。 - **关键代码**: ```python import json import numpy as np # 加载标注文件 with open('annotations.json') as f: data = json.load(f) # 遍历标注并绘制掩模 for ann in data['annotations']: mask = coco.annToMask(ann) # 将多边形转换为二值掩模 plt.imshow(mask, alpha=0.5) ``` - **优点**:完全自定义可视化样式[^4]。 --- ### 工具对比 | 方法 | 适用场景 | 编程需求 | 交互性 | |--------------------|-----------------------|----------|-------------| | COCO Viewer | 快速数据验证 | 低 | 图形化界面 | | pycocotools API | 开发调试 | 高 | 代码控制 | | Jupyter Notebook | 分步数据检查 | 中 | 部分交互 | | 自定义脚本 | 特殊需求(如动画生成)| 高 | 无 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值