[MMDetection]COCO数据集可视化验证


在使用MMDetection训练之前,需要对图像进行可视化验证,验证数据和标签是否对齐。

# 数据集可视化
import os
import matplotlib.pyplot as plt
from PIL import Image

original_images = []
images = []
texts = []
plt.figure(figsize=(16,12))

image_paths = [filename for filename in os.listdir(r"E:\****************************")][:8]   # 取前8张图片

for i, filename in enumerate(image_paths):
    name = os.path.splitext(filename)[0]

    image = Image.open(os.path.join(r"E:\***************************",filename)).convert("RGB")

    plt.subplot(4,2,i+1)
    plt.imshow(image)
    plt.title(f"{filename}")
    plt.xticks([])   # 设置坐标轴
    plt.yticks([])
plt.tight_layout()
plt.show()

以上代码 提供了数据集图片查看的功能,需要加入自己对应的图片路径。

以下代码 提供了COCO数据集标签与图片的显示功能,从数据集中随机选取了8张图片进行展示,以可视化数据集图片与标签是否对准。需要填入json路径和image的保存路径。

# COCO 数据集可视化
from pycocotools.coco import COCO
import numpy as np
import os.path as osp
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
from PIL import Image

def apply_exif_orientation(image):
    _ExIF_ORIENT = 274
    if not hasattr(image,'getexif'):
        return image
    
    try:
        exif = image.getexif()
    except Exception:
        exif = None
    
    if exif is None:
        return image
    
    orientation = exif.get(_ExIF_ORIENT)

    method = {
        2: Image.FLIP_LEFT_RIGHT,
        3: Image.ROTATE_180,
        4: Image.FLIP_TOP_BOTTOM,
        5: Image.TRANSPOSE,
        6: Image.ROTATE_270,
        7: Image.TRANSVERSE,
        8: Image.ROTATE_90,
    }.get(orientation)

    if method is not None:
        return image.transpose(method)
    return image


def show_bbox_only(coco, anns, show_label_bbox = True, is_filling = True):
    if len(anns) == 0:
        return
    
    ax = plt.gca()
    ax.set_autoscale_on(False) # 自动调整坐标轴范围

    image2color = dict()
    for cat in coco.getCatIds():
        image2color[cat] = (np.random.random((1, 3)) * 0.7 + 0.3).tolist()[0]

    polygons = []
    colors = []

    for ann in anns:
        color = image2color[ann["category_id"]]
        bbox_xmin, bbox_ymin, bbox_w, bbox_h = ann['bbox']
        poly = [[bbox_xmin, bbox_ymin],[bbox_xmin, bbox_ymin+bbox_h],
                [bbox_xmin+bbox_w, bbox_ymin+bbox_h], [bbox_xmin+bbox_w, bbox_ymin]]
        polygons.append(Polygon(np.array(poly).reshape((4,2))))
        colors.append(color)

        if show_label_bbox:
            label_bbox = dict(facecolor = color)
        else:
            label_bbox = None
        ax.text(
            bbox_xmin,
            bbox_ymin,
            "%s" % (coco.loadCats(ann['category_id'])[0]['name']),
            color = 'white',
            bbox = label_bbox)
    
    if is_filling:
        p = PatchCollection(
            polygons, facecolor = colors, linewidths = 0, alpha = 0.4)
        ax.add_collection(p)

    p = PatchCollection(
        polygons, facecolor = None, linewidths = 0, alpha = 0.4)
    ax.add_collection(p)

coco = COCO(r'E:\*******保存的json文件夹\test.json')
image_ids = coco.getImgIds()
np.random.shuffle(image_ids)

plt.figure(figsize=(16,12))

for i in range(8):
    image_data = coco.loadImgs(image_ids[i])[0]
    image_path = osp.join(r'E:\保存的图片文件夹',image_data['file_name'])
    annotation_ids = coco.getAnnIds(
        imgIds=image_data['id'], catIds=[], iscrowd=0
    )
    annotations = coco.loadAnns(annotation_ids)
    ax = plt.subplot(4,2,i+1)
    image = Image.open(image_path).convert('RGB')

    image = apply_exif_orientation(image)

    ax.imshow(image)
    show_bbox_only(coco, annotations)

    plt.title(f"{filename}")
    plt.xticks([])
    plt.yticks([])

plt.tight_layout()
plt.show()

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

开始学AI

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值