Cityscapes数据集下载与使用全指南:从零开始掌握计算机视觉基准数据

1次阅读
没有评论

共计 2989 个字符,预计需要花费 8 分钟才能阅读完成。

image.webp

背景介绍

Cityscapes 是自动驾驶和城市场景理解领域最权威的公开数据集之一,包含来自 50 个城市的街景图像,涵盖 30 个语义类别的高质量像素级标注。它的价值在于:

Cityscapes 数据集下载与使用全指南:从零开始掌握计算机视觉基准数据

  • 提供 5000 张精细标注图像(fine annotation)和 20000 张粗标注图像(coarse annotation)
  • 包含语义分割、实例分割和全景分割三种标注类型
  • 图像分辨率高达 2048×1024,能充分考验算法的细节处理能力

对于想入门计算机视觉的新手来说,掌握 Cityscapes 数据集的使用是进阶自动驾驶领域的必经之路。

下载指南

官方 vs 镜像源速度对比

  1. 官方源 :注册后通过 官网 下载,但国内直连速度可能只有 100KB/ s 左右
  2. 镜像源:推荐使用国内高校镜像(如清华源),速度可达 10MB/s+

断点续传技巧

使用 aria2c 工具实现多线程加速下载(示例下载 leftImg8bit_trainvaltest.zip):

aria2c -x16 -s16 \
  https://mirror.tsinghua.edu.cn/cityscapes/leftImg8bit_trainvaltest.zip \
  --continue=true

关键参数说明:

  • -x16:最大 16 个连接
  • --continue:自动断点续传

文件校验方法

下载完成后务必验证文件完整性(官方提供 MD5 校验码):

md5sum leftImg8bit_trainvaltest.zip
# 对比输出与官网提供的 d1b0e5b7f7a3d5b9e7a7

数据结构解析

目录结构

解压后典型结构如下:

cityscapes/
├── leftImg8bit/
│   ├── train/
│   ├── val/
│   └── test/
└── gtFine/
    ├── train/
    └── val/

核心目录说明:

  • leftImg8bit:原始 RGB 图像(8bit 色深)
  • gtFine:精细标注(JSON 格式)
  • train/val/test:标准数据划分

标注格式详解

JSON 标注文件包含以下关键字段:

{
  "objects": [
    {
      "label": "car",
      "polygon": [[x1,y1], [x2,y2], ...]
    }
  ]
}

转换多边形标注到掩膜的示例代码:

import numpy as np
import cv2

def poly2mask(polygon, height, width):
    mask = np.zeros((height, width), dtype=np.uint8)
    cv2.fillPoly(mask, [np.array(polygon)], 1)
    return mask

实战代码

可视化语义分割标注

import matplotlib.pyplot as plt

def visualize_segmentation(img_path, json_path):
    img = cv2.imread(img_path)
    with open(json_path) as f:
        ann = json.load(f)

    # 创建空白掩膜
    h, w = img.shape[:2]
    seg_map = np.zeros((h, w, 3))

    # 为每个类别着色
    for obj in ann["objects"]:
        color = CLASS_COLORS[obj["label"]]
        mask = poly2mask(obj["polygon"], h, w)
        seg_map[mask==1] = color

    plt.imshow(cv2.addWeighted(img, 0.7, seg_map, 0.3, 0))

转换为 COCO 格式

def cityscapes2coco(src_dir, dst_json):
    coco = {"images": [],
        "annotations": [],
        "categories": []}

    # 遍历所有图像
    for img_file in Path(src_dir).glob("**/*.png"):
        # 解析图像信息
        img_id = len(coco["images"])
        img = cv2.imread(str(img_file))
        coco["images"].append({
            "id": img_id,
            "file_name": img_file.name,
            "height": img.shape[0],
            "width": img.shape[1]
        })

        # 处理对应标注
        json_file = img_file.parent.parent / "gtFine" / img_file.parent.name / (img_file.stem + "_gtFine_polygons.json")
        with open(json_file) as f:
            ann_data = json.load(f)

        for obj in ann_data["objects"]:
            # 转换多边形格式
            segmentation = [coord for point in obj["polygon"] for coord in point]
            coco["annotations"].append({
                "image_id": img_id,
                "category_id": CLASS2ID[obj["label"]],
                "segmentation": [segmentation],
                "area": cv2.contourArea(np.array(obj["polygon"])),
                "bbox": list(cv2.boundingRect(np.array(obj["polygon"]))),
                "iscrowd": 0
            })

    # 保存结果
    with open(dst_json, 'w') as f:
        json.dump(coco, f)

避坑指南

内存优化

处理高分辨率图像时:

  1. 使用生成器(Generator)逐张加载
  2. 采用 cv2.IMREAD_REDUCED 降低读取分辨率
  3. 对大数据集使用 LMDB 或 TFRecord 格式存储

常见错误

  • 标签映射错误 :注意traffic sign 和traffic light是不同类别
  • 图像尺寸不匹配:验证标注与原始图像尺寸是否一致
  • 坐标系混淆 :OpenCV 的(y,x) 与 numpy 的 (x,y) 注意区分

多 GPU 训练

使用torch.utils.data.distributed.DistributedSampler:

train_sampler = DistributedSampler(dataset, shuffle=True)
dataloader = DataLoader(
    dataset,
    batch_size=64,
    sampler=train_sampler,
    num_workers=4
)

延伸思考

自定义数据集开发

  1. 保留原始目录结构
  2. 遵循相同命名规则(如{city}_{seq}_{frame}_leftImg8bit.png)
  3. 使用官方提供的 cityscapesscripts 工具验证标注格式

多数据集联合

与 BDD100K 联合训练时的建议:

  • 统一标签体系(映射相似类别)
  • 调整图像分辨率到相同尺寸
  • 使用加权采样平衡数据分布

学习资源

  1. 官方文档
  2. 论文《The Cityscapes Dataset for Semantic Urban Scene Understanding》
  3. GitHub 热门项目:
  4. cityscapesScripts
  5. mmsegmentation

通过本指南,希望你能避开我踩过的那些坑,快速掌握这个强大数据集的核心用法。如果在实践过程中遇到新问题,不妨在官方论坛或 GitHub 社区交流,计算机视觉的学习之路需要大家共同探索。

正文完
 0
评论(没有评论)