labelme转coco数据集的那些事·其一

发布时间 2023-08-13 17:39:45作者: E_sheep

1.因为发现布置的任务的具体要求没有被组员理解,导致所有180反转后的标签都变为了:
image
一个json文件有好几个这样的标签
image
那如果人手一个个这样处理,真的是要累死,所以就写了这个代码

import os
import json
path = 'J:\\final_tomato_data\\test'


json_files = sorted([pos_json for pos_json in os.listdir(path) if pos_json.endswith('.json')])

for index, js in enumerate(json_files):
    with open(os.path.join(path, js)) as json_file:

        data = json.load(json_file)

        if "shapes" in data:
            data['shapes']['label'] = "Bacterial_spot"
    with open(os.path.join(path, js), 'w') as json_file:
        json.dump(data, json_file)

但是会运行报错,然后我们看下报错信息:
image
接下来定位到位置单步调试:
image
发现在第二次进入时出现了报错,
image

那么查看data的结构,
image
找到了data
image
点开shape
image
点开0
image

综上所述
image

label在dict_data的shapes键值为0,1两个dict组成的一个list内的一对key-value对内

image

那么问题就很明显了,改为image
就可以指定好对应的位置。
啊哈,原来问题是看json文件内容虽然只有两层
image

但是实际上是经过python处理后又多了一层

所见非真,此见即幻!这便是code的奥秒

再次运行:
image

不再报错!
看看json:
image

处理成功!

因为我们只是指定了第一个,image
下面所有都没变,那么就在加层循环。

image

大功告成!
运行成功!
image
所有的都被修改了:
image

这里放上最终的代码:

import os
import json
path = '*****'


json_files = sorted([pos_json for pos_json in os.listdir(path) if pos_json.endswith('.json')])

for index, js in enumerate(json_files):
    with open(os.path.join(path, js)) as json_file:

        data = json.load(json_file)

        if "shapes" in data:
        	data1= data['shapes']
		for i in data1:
			i['label']= "Bacterial_spot"
    with open(os.path.join(path, js), 'w') as json_file:
        json.dump(data, json_file)