目录
labelimg标注的xml是这样
<annotation>
<folder>22</folder>
<filename>1.jpg</filename>
<path>.\1.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>815</width>
<height>692</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>normal</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>205</xmin>
<ymin>98</ymin>
<xmax>805</xmax>
<ymax>624</ymax>
</bndbox>
</object>
</annotation>
labelme标注的格式是这样
{
"version": "5.0.0",
"flags": {},
"shapes": [
{
"label": "normal",
"points": [
[
206.1290322580645,
61.16129032258067
],
[
799.6774193548387,
645.0322580645161
]
],
"group_id": null,
"shape_type": "rectangle",
"flags": {}
}
],
"imagePath": "..\\22\\1.jpg",
"imageData": "/9j/4AAQSkZJRgABAQAAAQABAAD",
"imageHeight": 692,
"imageWidth": 815
}
labelimg的xml转labelme的json
import xml.etree.ElementTree as ET
import os
import json
import cv2
from io import BytesIO
import base64
from PIL import Image
def makefile(path,content):
with open(path, 'w') as f: # 创建一个params.json文件
f.write(content) # 将json_str写到文件中
# if os.path.exists(path):
# if os.path.isdir(path):
# #**
# else:
# print('please input the dir name')
# else:
# print('the path is not exists')
def toJson(imagePath, imageHeight, imageWidth, shape_type, label, points, xml_path):
print(imagePath)
coco = dict()
coco['version'] = "5.0.0"
coco['flags'] = dict()
coco['shapes'] = [1]
coco['shapes'][0]=dict()
coco['shapes'][0]['label'] = label
coco['shapes'][0]['points'] = points
coco['shapes'][0]['group_id'] = None
coco['shapes'][0]['shape_type'] = "rectangle"
coco['shapes'][0]['flags'] = dict()
coco['imagePath'] = imagePath
img = cv2.imread(imagePath)
pil_img = Image.fromarray(img)
buff = BytesIO()
pil_img.save(buff, format="JPEG")
new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")
coco['imageData'] = new_image_string
coco['imageHeight'] = imageHeight
coco['imageWidth'] = imageWidth
makefile(imagePath[:-4]+"_1.json",json.dumps(coco, indent=4))
def parseXmlFiles(xml_path):
for f in os.listdir(xml_path):
if not f.endswith('.xml'):
continue
size = dict()
size['width'] = None
size['height'] = None
size['depth'] = None
xml_file = os.path.join(xml_path, f)
print(xml_file)
tree = ET.parse(xml_file)
root = tree.getroot()
if root.tag != 'annotation':
raise Exception('pascal voc xml root element should be annotation, rather than {}'.format(root.tag))
imagePath = ""
imageHeight = 0
imageWidth = 0
shape_type = "rectangle"
label = "normal"
points = [[0,0],[0,0]]
for elem in root:
if elem.tag == 'folder' or elem.tag == 'filename' or elem.tag == 'source' or elem.tag == 'segmented':
continue
elif elem.tag == 'path':
imagePath = elem.text
elif elem.tag == 'size':
for subelem in elem:
if subelem.tag == 'width':
imageWidth = subelem.text
elif subelem.tag == 'height':
imageHeight = subelem.text
elif elem.tag == 'object':
for subelem in elem:
if subelem.tag == 'bndbox':
for item in subelem:
if item.tag == 'xmin':
points[0][0] = int(item.text)
if item.tag == 'ymin':
points[0][1] = int(item.text)
if item.tag == 'xmax':
points[1][0] = int(item.text)
if item.tag == 'ymax':
points[1][1] = int(item.text)
toJson(imagePath, imageHeight, imageWidth, shape_type, label, points, xml_path)
if __name__ == '__main__':
xml_path = './' # 这是xml文件所在的地址
parseXmlFiles(xml_path)
附上一个json文件创建编辑的脚本例子
import json
class Params():
"""Class that loads hyperparameters from a json file.
Example:
```
params = Params(json_path)
print(params.learning_rate)
params.learning_rate = 0.5 # change the value of learning_rate in params
```
"""
def __init__(self, json_path):
with open(json_path) as f:
params = json.load(f) # 将json格式数据转换为字典
self.__dict__.update(params)
def save(self, json_path):
with open(json_path, 'w') as f:
json.dump(self.__dict__, f, indent=4) # indent缩进级别进行漂亮打印
def update(self, json_path):
"""Loads parameters from json file"""
with open(json_path) as f:
params = json.load(f)
self.__dict__.update(params)
@property # Python内置的@property装饰器就是负责把一个方法变成属性调用的
def dict(self):
"""Gives dict-like access to Params instance by `params.dict['learning_rate']"""
return self.__dict__
if __name__ == '__main__':
parameters = {"SEED": 1,
"dataset": "Omniglot",
"meta_lr": 1e-3,
"num_episodes": 5000,
"num_classes": 5,
"num_samples": 1,
"num_query": 10,
"num_steps": 100,
"num_inner_tasks": 8,
"num_train_updates": 1,
"num_eval_updates": 1,
"save_summary_steps": 100,
"num_workers": 1
}
json_str = json.dumps(parameters, indent=4)
with open('params.json', 'w') as f: # 创建一个params.json文件
f.write(json_str) # 将json_str写到文件中
params = Params('params.json')
params.SEED2 = 2 # 修改json中的数据
params.save('params.json') # 将修改后的数据保存