跑模型,图片和标签数量对不上怎么办?代码直接拿来用

基础语法

  1. os.path.join()

    路径拼接
  2. os.listdir()

    返回一个list,list里面是括号内文件夹里的文件(夹)的名字
  3. os.path.splitext(file)

    分离文件名和扩展名
    例:dog.jpg,文件名=dog,扩展名='.jpg'
  4. os.path.exists()

    返回True或False,判断存不存在
  5. shutil.move(file_path_0, file_path_1)

    填【文件】的前后【路径】(位置)

代码

我的标签是VOC格式,所以用root拼接路径比较方便。大家按需修改,也可以直接写两个folder的绝对路径

import os
import shutil

root = 'X:/path/...'
img_folder = os.path.join(root, 'DOG_img')  # 改成自己的文件名
xml_folder = os.path.join(root, 'Annotations')  # 改成自己的文件名

# 如果没有文件夹则创建
img_destination_folder = os.path.join(img_folder, 'img 没有标签')
xml_destination_folder = os.path.join(xml_folder, '标签没有对应img')

for folder in [img_destination_folder, xml_destination_folder]:
    if not os.path.exists(folder):
        os.makedirs(folder)


def move_files(source_folder, comparison_folder, destination_folder):
    source_files = os.listdir(source_folder)
    comparison_files = os.listdir(comparison_folder)

    jpg_or_xml_files = [file for file in source_files if file.endswith((".jpg", ".xml"))]
    for file in jpg_or_xml_files:
        name, ext = os.path.splitext(file)  # 分离文件名和扩展名。
                                            # dog.jpg,name=dog, ext='.jpg'
        # 开始匹配
        if ext == '.jpg':
            name = name + '.xml'
        else:
            name = name + '.jpg'

        if name not in comparison_files:
            source_file_path = os.path.join(source_folder, file)
            destination_file_path = os.path.join(destination_folder, file)
            if os.path.exists(source_file_path):  # 如果路径存在则继续运行代码
                shutil.move(source_file_path, destination_file_path)
                print(f"Moved file: {file} to {destination_folder}")


if __name__ == '__main__':
    move_files(img_folder, xml_folder, img_destination_folder)
    move_files(xml_folder, img_folder, xml_destination_folder)

拓展

if __name__ == '__main__' 如何正确理解? - 知乎

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值