删除无目标的labelme格式的json文件和对应的图片使得处理后的图片和json一一对应

文件夹里有很多图片以及对图片使用labelme标注生成的json文件,并不是所有的图片都进行了标注,有json文件对应的图片也可能存在没有目标的情况,相应的json文件内shapes为空列表,需要筛选出所有有标注且标注json内存在目标的图片

并基于筛选的结果,把未删选出来的图片和对应的json删除,代码见下:

import os
import json

def check_annotation(json_path):
    with open(json_path, 'r') as f:
        data = json.load(f)
        return bool(data.get('shapes'))

def get_annotated_images(folder_path):
    annotated_images = []
    for root, _, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.json'):
                json_path = os.path.join(root, file)
                image_path = os.path.splitext(json_path)[0] + '.jpg'
                if os.path.exists(image_path) and check_annotation(json_path):
                    annotated_images.append(image_path)
    return annotated_images

def delete_unannotated_files(folder_path, annotated_images):
    for root, _, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.json') or file.endswith('.jpg'):
                file_path = os.path.join(root, file)
                if file.split(".")[0] not in annotated_images:
                    os.remove(file_path)

if __name__ == "__main__":
    # 用法示例
    folder_path = '/path/to/your/folder'
    annotated_images = get_annotated_images(folder_path)
    pick = [os.path.basename(img.split(".")[0]) for img in annotated_images]
    delete_unannotated_files(folder_path, pick)

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值