json文件解析并修改值
针对使用 anylabeling 对数据标记,会出现标签错误情况,修改json文件的label(针对单类)。如果不会使用该方法标记,可查看这篇博客。
[ ] 表示一个数组,{ } 表示一个对象,在对象中还可以包含对象的属性,属性也可能是另外一个类。" " 代表的是属性值,:代表是前后的关系,冒号前是属性的名称,后面是属性的值,这个值可以是基本数据类型,可以是引用类数据类型。
代码如下:
{
"version": "0.3.3",
"flags": {},
"shapes": [
{
"label": "brick",
"text": "",
"points": [
[
789.0,
594.0
],
......
[
786.0,
597.0
],
]
"group_id": null,
"shape_type": "polygon",
"flags": {}
}
],
"imagePath": "1701656522935_5660202.png",
"imageData": null,
"imageHeight": 1240,
"imageWidth": 1624,
"text": ""
}
分析:
第一层是一个大括号{ }中的json数组,json数组中包含version,flags,shapes,imagePath,imageData,imageHeight,imageWidth,text.等属性。
第二层是shape的jsonArray属性,每个大括号代表一个对象,每个对象中有label,text,points,group_id,shape_type,flags等属性。
目标:修改label的值
代码:
import os
import json
def read_json(jsonPath):
with open(jsonPath,"r") as path_json:
jsonx=json.load(path_json)
for shape in jsonx["shapes"]:
obj_cls = str(shape["label"])
if(obj_cls != "brick"):
shape["label"] = "brick"
return jsonx
def write_json(jsonPath,params):
with open(jsonPath, "w",encoding='utf-8') as path_json:
json.dump(params,path_json, indent=4, ensure_ascii=False)
if __name__=="__main__":
json_path = "E:\\Tensor_YOLO\\yolov5_6.0\\yolov5-6.0\\data\\images\\json_file\\modify_label\\"#文件路径
list_json = os.listdir(json_path)
for cnt, json_name in enumerate(list_json):
file,fileext = os.path.splitext(json_name)
if(fileext == ".json"):
path_json = json_path + json_name
data = read_json(path_json)
write_json(path_json,data)
else:
pass