-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxml2json.py
220 lines (184 loc) · 6.35 KB
/
xml2json.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import base64
import io
import json
import os
import traceback
import xml.etree.ElementTree as ET
import numpy as np
import PIL
from mltools.src.log.logger import logger
try:
from labelme import __version__ as labelmeVersion
except:
labelmeVersion = "4.2.9"
def img_encode(img_or_path):
if isinstance(img_or_path, np.ndarray):
"""
copy from labelme image.py
"""
img_pil = PIL.Image.fromarray(img_or_path)
f = io.BytesIO()
img_pil.save(f, format="PNG")
img_bin = f.getvalue()
if hasattr(base64, "encodebytes"):
img_b64 = base64.encodebytes(img_bin)
else:
img_b64 = base64.encodestring(img_bin)
# _, enc = cv2.imencode('.jpg', img_or_path)
# base64_data = base64.urlsafe_b64encode(enc.tobytes())
return img_b64
else:
if isinstance(img_or_path, str):
i = open(img_or_path, "rb")
elif isinstance(img_or_path, io.BufferedReader):
i = img_or_path
else:
raise TypeError("Input type error!")
base64_data = base64.b64encode(i.read())
return base64_data.decode()
def x2j_convert(xmlpath, originImgPath, saveFile=True):
"""this function is used to convert xml files (labelimg) to jsons (labelme)"""
if not os.path.exists(xmlpath) or not os.path.exists(originImgPath):
logger.error("file not exist")
return
base64Code = img_encode(originImgPath)
shapes = getPolygon(xmlpath)
(fatherPath, filename_ext) = os.path.split(originImgPath)
(filename, _) = os.path.splitext(filename_ext)
ob = dict()
ob["imageData"] = base64Code
ob["flags"] = {}
ob["version"] = labelmeVersion
ob["imagePath"] = filename_ext
img = io.imread(originImgPath)
imgShape = img.shape
del img
ob["imageHeight"] = imgShape[0]
ob["imageWidth"] = imgShape[1]
ob["shapes"] = shapes
if saveFile:
with open(fatherPath + os.sep + filename + ".json", "w", encoding="utf-8") as f:
j = json.dumps(ob, sort_keys=True, indent=4)
f.write(j)
logger.info("save to path {}".format(fatherPath + os.sep + filename + ".json"))
return fatherPath + os.sep + filename + ".json"
else:
return json.dumps(ob, sort_keys=True, indent=4)
def x2j_convert_pascal(xmlpath, originImgPath, saveFile=True):
# pass
if not os.path.exists(xmlpath) or not os.path.exists(originImgPath):
logger.error("file not exist")
return
base64Code = img_encode(originImgPath)
shapes = getPolygonPascal(xmlpath)
(fatherPath, filename_ext) = os.path.split(originImgPath)
(filename, _) = os.path.splitext(filename_ext)
ob = dict()
ob["imageData"] = base64Code
ob["flags"] = {}
ob["version"] = labelmeVersion
ob["imagePath"] = filename_ext
img = io.imread(originImgPath)
imgShape = img.shape
del img
ob["imageHeight"] = imgShape[0]
ob["imageWidth"] = imgShape[1]
ob["shapes"] = shapes
if saveFile:
with open(
fatherPath + os.sep + filename + "_p.json", "w", encoding="utf-8"
) as f:
j = json.dumps(ob, sort_keys=True, indent=4)
f.write(j)
logger.info(
"save to path {}".format(fatherPath + os.sep + filename + "_p.json")
)
return fatherPath + os.sep + filename + "_p.json"
else:
return json.dumps(ob, sort_keys=True, indent=4)
def getImgShape(xmlPath):
in_file = open(xmlPath)
tree = ET.parse(in_file)
root = tree.getroot()
imgSize = root.find("size")
imgwidth = imgSize.find("width").text
imgheight = imgSize.find("height").text
return imgwidth, imgheight
def getPolygon(xmlPath):
in_file = open(xmlPath)
tree = ET.parse(in_file)
root = tree.getroot()
shapes = []
try:
for obj in root.iter("object"):
flags = {}
group_id = "null"
shape_type = "polygon"
# pass
dic = dict()
label = obj.find("name").text
polygon = obj.find("polygon")
# print(len(polygon))
if len(polygon) > 2:
points = []
for i in range(0, len(polygon)):
# print(polygon.find('point{}'.format(i)).text)
tmp = polygon.find("point{}".format(i)).text.split(",")
point = [int(tmp[0]), int(tmp[1])]
# print(point)
points.append(point)
del tmp, point
dic["flags"] = flags
dic["group_id"] = group_id
dic["shape_type"] = shape_type
dic["points"] = points
dic["label"] = label
shapes.append(dic)
# print(shapes)
return shapes
except Exception:
logger.error(traceback.print_exc())
def getPolygonPascal(xmlPath):
in_file = open(xmlPath)
tree = ET.parse(in_file)
root = tree.getroot()
shapes = []
try:
for obj in root.iter("object"):
flags = {}
group_id = "null"
shape_type = "polygon"
# pass
dic = dict()
label = obj.find("name").text
polygon = obj.find("bndbox")
# print(len(polygon))
# if len(polygon)>2:
# points = []
# for i in range(0,len(polygon)):
xmin = int(polygon.find("xmin").text)
ymin = int(polygon.find("ymin").text)
xmax = int(polygon.find("xmax").text)
ymax = int(polygon.find("ymax").text)
# print(polygon.find('point{}'.format(i)).text)
# tmp = polygon.find('point{}'.format(i)).text.split(',')
# point = [int(tmp[0]),int(tmp[1])]
# print(point)
p1 = [xmin, ymin]
p2 = [xmax, ymax]
p3 = [xmin, ymax]
p4 = [xmax, ymin]
# points.append(point)
points = [p1, p2, p3, p4]
# del tmp,point
dic["flags"] = flags
dic["group_id"] = group_id
dic["shape_type"] = shape_type
dic["points"] = points
dic["label"] = label
shapes.append(dic)
# print(shapes)
return shapes
except Exception:
logger.error("===== Exception =====")
traceback.print_exc()