coco_extract_car_2_voc/kitti

本文介绍如何将COCO数据集中的汽车类别提取并转换为VOC和KITTI格式,涉及Python脚本实现,包括类别过滤、图片筛选及XML文件生成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

coco数据集提取car,转化为voc格式

分三步:

提取你需要的类别

python filter.py

移除不需要的图片

python get_image.py

写成voc格式

python get_xml.py

话不多少直接上代码:

filter.py
import json

className = {
            3:'car'
            }

classNum = [3]

def writeNum(Num):
    with open("COCO_train2014.json","a+") as f:
        f.write(str(Num))

inputfile = []
inner = {}

with open("instances_train2014.json","r+") as f:
    allData = json.load(f)
    data = allData["annotations"]
    print(data[1])
    print("read ready")

for i in data:
    if(i['category_id'] in classNum):
        inner = {
            "filename": str(i["image_id"]).zfill(6),
            "name": className[i["category_id"]],
            "bndbox":i["bbox"]
        }
        inputfile.append(inner)
inputfile = json.dumps(inputfile)
writeNum(inputfile)

get_image.py

#!/usr/bin/env python  
# -*- coding: utf-8 -*-  
# @Time    : 2018/4/24 22:46  
# @Author  : ma xiangjun  
# @Site    :   
# @File    : 根据目标图片id筛选图片.py  
# @Software: PyCharm  

import json  
import os  

nameStr = []  

with open("COCO_train.json","r+") as f:  
    data = json.load(f)  
    print("read ready")  

for i in data: 
    imgName = "COCO_train2014_" + str(i["filename"]) + ".jpg"  
    nameStr.append(imgName)  

nameStr = set(nameStr)  
print(nameStr)  
print(len(nameStr))  

path = "/home/panlu/ext_work/YOLO/darknet/scripts/coco/images/train2014/"  

for file in os.listdir(path):  
     if(file not in nameStr):  
        os.remove(path+file)  

get_xml.py

import xml.dom
import xml.dom.minidom
import os
import cv2
import json

_AUTHOR= 'maxiangjun'
_SEGMENTED= '0'
_DIFFICULT= '0'
_TRUNCATED= '0'
_POSE= 'Unspecified'

def createElementNode(doc,tag, attr):
    element_node = doc.createElement(tag)
    text_node = doc.createTextNode(attr)
    element_node.appendChild(text_node)
    return element_node

def createChildNode(doc,tag, attr,parent_node):
    child_node = createElementNode(doc, tag, attr)
    parent_node.appendChild(child_node)

def createObjectNode(doc,attrs):
    object_node = doc.createElement('object')
    createChildNode(doc, 'name', attrs['name'],
                    object_node)
    createChildNode(doc, 'pose',
                    _POSE, object_node)
    createChildNode(doc, 'truncated',
                    _TRUNCATED, object_node)
    createChildNode(doc, 'difficult',
                    _DIFFICULT, object_node)
    bndbox_node = doc.createElement('bndbox')
    createChildNode(doc, 'xmin', str(int(attrs['bndbox'][0])),
                    bndbox_node)
    createChildNode(doc, 'ymin', str(int(attrs['bndbox'][1])),
                    bndbox_node)
    createChildNode(doc, 'xmax', str(int(attrs['bndbox'][0]+attrs['bndbox'][2])),
                    bndbox_node)
    createChildNode(doc, 'ymax', str(int(attrs['bndbox'][1]+attrs['bndbox'][3])),
                    bndbox_node)
    object_node.appendChild(bndbox_node)
    return object_node

def writeXMLFile(doc,filename):
    tmpfile =open('tmp.xml','w')
    doc.writexml(tmpfile, addindent=''*4,newl = '\n',encoding = 'utf-8')
    tmpfile.close()
    fin =open('tmp.xml')
    fout =open(filename, 'w')
    lines = fin.readlines()
    for line in lines[1:]:
        if line.split():
            fout.writelines(line)
    fin.close()
    fout.close()

if __name__ == "__main__":
    img_path = "/home/panlu/ext_work/YOLO/darknet/scripts/coco/images/train2014/"
    fileList = os.listdir(img_path)
    if fileList == 0:
        print("Do not find images in your img_path")
        os._exit(-1)

    with open("COCO_train.json", "r") as f:
        ann_data = json.load(f)

    current_dirpath = os.path.dirname(os.path.abspath('__file__'))

    if not os.path.exists('Annotations'):
        os.mkdir('Annotations')

    for imageName in fileList:
        saveName= imageName.strip(".jpg")
        print(saveName)

        xml_file_name = os.path.join('Annotations', (saveName + '.xml'))

        img=cv2.imread(os.path.join(img_path,imageName))
        print(os.path.join(img_path,imageName))
        height,width,channel=img.shape
        print(height,width,channel)

        my_dom = xml.dom.getDOMImplementation()

        doc = my_dom.createDocument(None, 'annotation', None)

        root_node = doc.documentElement
        #print(root_node)
        #input()
        createChildNode(doc, 'folder', 'COCO2014', root_node)

        createChildNode(doc, 'filename', saveName+'.jpg',root_node)

        source_node = doc.createElement('source')

        createChildNode(doc, 'database', 'LOGODection', source_node)

        createChildNode(doc, 'annotation', 'COCO2014', source_node)

        createChildNode(doc, 'image','flickr', source_node)

        createChildNode(doc, 'flickrid','NULL', source_node)

        root_node.appendChild(source_node)

        owner_node = doc.createElement('owner')

        createChildNode(doc, 'flickrid','NULL', owner_node)

        createChildNode(doc, 'name',_AUTHOR, owner_node)

        root_node.appendChild(owner_node)

        size_node = doc.createElement('size')

        createChildNode(doc, 'width',str(width), size_node)

        createChildNode(doc, 'height',str(height), size_node)

        createChildNode(doc, 'depth',str(channel), size_node)

        root_node.appendChild(size_node)

        createChildNode(doc, 'segmented',_SEGMENTED, root_node)

        count = 0
        for ann in ann_data:
            if(saveName==("COCO_train_2014" + ann["filename"].zfill(12))):
                count = 1
                object_node = createObjectNode(doc, ann)
                root_node.appendChild(object_node)
            else:
                continue

        if count ==1:
    writeXMLFile(doc, xml_file_name)

最后得到的目录如下:

这里写图片描述

下一步转化为kitti格式参考这里:voc2007_extract_car_2_kitti

看到这里发现nvidia 一个demo里提供了coco直接转化为kitti的python代码,OK,如果目的是coco2kitti 前面可以不用看了,下面这个简单:

coco直接提取需要的类别转化KITTI,python代码如下,略作修改:

"""coco2kitti.py: Converts MS COCO annotation files to
                  Kitti format bounding box label files
__author__ = "ma xiang jun"
"""

import os
from pycocotools.coco import COCO

def coco2kitti(catNms, annFile):

    # initialize COCO api for instance annotations
    coco = COCO(annFile)

    # Create an index for the category names
    cats = coco.loadCats(coco.getCatIds())
    cat_idx = {}
    for c in cats:
        cat_idx[c['id']] = c['name']

    for img in coco.imgs:

        # Get all annotation IDs for the image
        catIds = coco.getCatIds(catNms=catNms)
        annIds = coco.getAnnIds(imgIds=[img], catIds=catIds)

        # If there are annotations, create a label file
        if len(annIds) > 0:
            # Get image filename
            img_fname = coco.imgs[img]['file_name']
            # open text file
            with open('./labels/' + img_fname.split('.')[0] + '.txt','w') as label_file:
                anns = coco.loadAnns(annIds)
                for a in anns:
                    bbox = a['bbox']
                    # Convert COCO bbox coords to Kitti ones
                    bbox = [bbox[0], bbox[1], bbox[2] + bbox[0], bbox[3] + bbox[1]]
                    bbox = [str(b) for b in bbox]
                    catname = cat_idx[a['category_id']]
                    # Format line in label file
                    # Note: all whitespace will be removed from class names
                    out_str = [catname.replace(" ","")
                               + ' ' + ' '.join(['0']*3)
                               + ' ' + ' '.join([b for b in bbox])
                               + ' ' + ' '.join(['0']*8)
                               +'\n']
                    label_file.write(out_str[0])

if __name__ == '__main__':

    # These settings assume this script is in the annotations directory
    dataDir = '/home/mahnx0/datasets/coco/'
    dataType = 'train2014'
    annFile = '%s/annotations/instances_%s.json' % (dataDir, dataType)

    # If this list is populated then label files will only be produced
    # for images containing the listed classes and only the listed classes
    # will be in the label file
    # EXAMPLE:
    #catNms = ['person', 'dog', 'skateboard']
    catNms = ['car','bus','truck']

    # Check if a labels file exists and, if not, make one
    # If it exists already, exit to avoid overwriting
    if os.path.isdir('./labels'):
        print('Labels folder already exists - exiting to prevent badness')
    else:
        os.mkdir('./labels')
        coco2kitti(catNms, annFile)

如果发现格式或者数据哪里不对,这里有两个很方便的sh命令
(在当前目录下所有文件内容中查找bus,并替换为car)
sed -i “s/bus/car/g” grep bus -rl ./
根据文件名批量查找文件并且移到其它目录
find ./ -type f ! -name “passwd” -exec rm {} \; (删除passwd之外的文件)

#

./表示从当前目录找
-type f,表示只找file,文件类型的,目录和其他字节不要
-exec 把find到的文件名作为参数传递给后面的命令行,代替{}的部分
-exec后跟的命令行,必须用“ \;”结束
经典的移动:man mv
find ./ -type f -name “*.sh”|xargs mv -t /opt/
find ./ -type f -name “*.sh”|xargs -i mv {} /opt/
find ./ -type f -name “*.sh” -exec mv {} /opt/ \;  =====>\转意符号。否则 ; 不被shell识别。
mv find ./ -type f -name "*.sh" /opt/ 或者 cp $(find ./ -type f -name “*.sh” ) /opt/

<think>好的,我需要回答用户关于运行`python -m pcdet.datasets.kitti.kitti_dataset create_kini_infos tools/cfgs/dataset_configs/kitti_dataset.yaml`这个命令所涉及的文件的问题。首先,我得分解这个命令的各个部分,理解每个部分的作用,然后确定相关的文件。 首先,用户运行的是一个Python模块,路径是`pcdet.datasets.kitti.kitti_dataset`,调用了`create_kitti_infos`函数,并传入了一个配置文件`kitti_dataset.yaml`。这说明该命令主要用于生成KITTI数据集的信息文件,可能用于3D目标检测任务,比如PointPillars或SECOND等模型的数据预处理。 接下来,我需要考虑这个命令执行过程中会涉及哪些文件。首先,配置文件`kitti_dataset.yaml`肯定是关键,因为它通常包含数据集的路径、类别、训练验证拆分等信息。然后,KITTI数据集本身的原始数据文件,比如图像、点云、标签等,这些通常在配置文件中指定的路径下。 然后,生成的infos文件,比如`kitti_infos_train.pkl`、`kitti_infos_val.pkl`和`kitti_infos_test.pkl`,这些文件保存了数据集的元信息,比如每个样本的路径、标注、校准参数等。此外,可能还有`kitti_dbinfos_train.pkl`,用于数据库增强的数据。 还有,`kitti_dataset.py`这个Python文件本身,里面定义了数据集类以及`create_kitti_infos`函数,负责处理原始数据并生成infos文件。可能还有相关的工具函数或类,比如数据预处理、数据增强的代码,或者与点云处理相关的模块。 另外,可能需要检查数据集目录结构是否正确,比如KITTI的标准目录结构是否包含`training`和`testing`子目录,里面分别有`image_2`、`velodyne`、`label_2`等文件夹。配置文件中的路径是否正确指向这些目录,否则会导致程序无法找到数据文件。 还可能涉及一些工具脚本或工具函数,比如数据预处理中的点云转换、标注解析等代码,这些可能在`pcdet.datasets`的其他模块中,比如`common_utils.py`或者`kitti_utils.py`等。 另外,生成infos的过程中可能需要读取校准文件(calib),比如每个帧的校准参数,这些通常位于`calib`文件夹中。标签文件(label)中的标注信息也需要被正确解析。 总结一下,涉及的文件主要包括: 1. 配置文件`kitti_dataset.yaml`:指定数据集路径、参数等。 2. KITTI原始数据集文件:图像、点云、标签、校准文件。 3. 生成的infos文件:保存处理后的元信息。 4. 数据集处理代码`kitti_dataset.py`中的`create_kitti_infos`函数。 5. 可能的工具脚本或辅助函数。 需要验证这些文件的存在和正确性,特别是配置文件中路径是否正确,原始数据是否按KITTI结构存放,是否有权限访问这些文件,以及Python代码是否正确安装或导入。 如果用户遇到问题,比如命令运行失败,可能的原因包括配置文件路径错误、数据集路径配置错误、缺少必要的依赖库或数据文件,或者代码中存在bug。需要根据错误提示具体分析,比如文件未找到、解析错误等,逐步排查。</think>运行命令 `python -m pcdet.datasets.kitti.kitti_dataset create_kitti_infos tools/cfgs/dataset_configs/kitti_dataset.yaml` 主要用于生成 KITTI 数据集的信息文件(如训练/验证/测试集的元数据),其执行过程依赖以下关键文件: --- ### **1. 配置文件** - **`kitti_dataset.yaml`** - **路径**: `tools/cfgs/dataset_configs/kitti_dataset.yaml` - **作用**: 定义数据集路径、类别名称、训练/验证/测试集划分规则等参数。 - **关键配置项**: ```yaml DATA_PATH: 'data/kitti' # KITTI数据集根目录 CLASS_NAMES: ['Car', 'Pedestrian', 'Cyclist'] # 目标类别 SPLIT: { # 数据划分规则 train: 'train', val: 'val', test: 'test' } ``` --- ### **2. KITTI 原始数据集文件** 需确保 KITTI 数据集按标准结构存放,路径需与 `kitti_dataset.yaml` 中的 `DATA_PATH` 一致: ``` data/kitti/ ├── training/ │ ├── image_2/ # 左视图RGB图像(.png) │ ├── velodyne/ # 点云数据(.bin) │ ├── label_2/ # 标注文件(.txt) │ └── calib/ # 标定参数(.txt) └── testing/ # 测试集(结构类似training) ``` --- ### **3. 生成的 Infos 文件** 命令执行后会在 `DATA_PATH` 下生成以下文件: - **`kitti_infos_train.pkl`**: 训练集的元数据(样本路径、标注、标定参数等) - **`kitti_infos_val.pkl`**: 验证集的元数据 - **`kitti_infos_test.pkl`**: 测试集的元数据(若测试集存在) - **`kitti_dbinfos_train.pkl`**: 用于数据增强的数据库信息(如目标物体的点云片段) --- ### **4. 代码文件** - **`kitti_dataset.py`** - **路径**: `pcdet/datasets/kitti/kitti_dataset.py` - **作用**: 包含 `create_kitti_infos` 函数,负责解析原始数据并生成 `.pkl` 文件。 - **关键流程**: 1. 按 `SPLIT` 配置读取训练/验证/测试集的文件列表。 2. 解析每帧的点云、图像、标注和标定参数。 3. 将元数据序列化保存为 `.pkl` 文件。 --- ### **5. 依赖工具函数** - **`data_utils.py`** 或 **`kitti_utils.py`** - **路径**: 通常位于 `pcdet/datasets/kitti/` 或 `pcdet/utils/` - **作用**: 提供点云读取、标注解析、坐标转换等底层函数,供 `kitti_dataset.py` 调用。 --- ### **执行流程总结** 1. **读取配置**: 从 `kitti_dataset.yaml` 加载数据集路径和参数。 2. **遍历数据**: 根据 `DATA_PATH` 和 `SPLIT` 配置找到所有训练/验证/测试样本。 3. **解析数据**: 对每个样本解析点云、标注、标定参数,生成结构化元数据。 4. **保存信息**: 将元数据序列化为 `.pkl` 文件,供后续训练/测试直接加载。 --- ### **常见问题排查** - **报错 `DATA_PATH not found`**: 检查 `kitti_dataset.yaml` 中的路径是否与实际数据集路径一致。 - **标注解析失败**: 确认 `label_2/` 文件格式符合 KITTI 标准(每行包含类别、位置、尺寸等)。 - **依赖缺失**: 确保已安装 `pypcd`(点云处理)和 `pickle5`(序列化)等库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值