-
Notifications
You must be signed in to change notification settings - Fork 2
/
non_standardization.py
80 lines (73 loc) · 2.63 KB
/
non_standardization.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
import base64
import json
import os
import xml.etree.ElementTree as ET
from mltools.src.log.logger import logger
import traceback
from mltools.src.utils.mlfiles_standardization import Annotation
def labelImg_to_ml_file(xmlPath: str, imgPath: str):
imgName = os.path.split(imgPath)[-1]
fileName = (os.sep).join(imgPath.split(".")[:-1]) + ".ml"
with open(imgPath, "rb") as img:
b64 = base64.b64encode(img.read())
d = dict()
d["imageName"] = imgName
d["imageData"] = b64.decode()
d["scale"] = 1.0
tree = ET.parse(xmlPath)
root = tree.getroot()
entities = []
savedClassNames = []
try:
for o in root.iter("object"):
label = o.find("name").text
bndbox = o.find("bndbox")
xmin = bndbox.find("xmin").text
xmax = bndbox.find("xmax").text
ymin = bndbox.find("ymin").text
ymax = bndbox.find("ymax").text
if label not in savedClassNames:
savedClassNames.append(label)
entities.append(
Annotation(
"rect",
label,
{
"xmin": int(xmin),
"xmax": int(xmax),
"ymin": int(ymin),
"ymax": int(ymax),
},
None,
).to_json(),
)
d["annotations"] = entities
d["savedClassNames"] = savedClassNames
with open(fileName, "w", encoding="utf-8") as f:
json.dump(d, f, indent=3, ensure_ascii=False, sort_keys=True)
except:
logger.error("===== Exception =====")
traceback.print_exc()
def labelme_to_ml_file(jsonPath: str):
jsonData = json.load(open(jsonPath, "r"))
fileName = (os.sep).join(jsonPath.split(".")[:-1]) + ".ml"
d = dict()
d["imagePath"] = jsonData["imagePath"]
d["imageData"] = jsonData["imageData"]
savedClassNames = []
entities = []
for s in jsonData["shapes"]:
if s["label"] not in savedClassNames:
savedClassNames.append(s["label"])
entities.append(
Annotation(
"polygon",
s["label"],
None,
s["points"],
).to_json(),
)
d["annotations"] = entities
d["savedClassNames"] = savedClassNames
with open(fileName, "w", encoding="utf-8") as f:
json.dump(d, f, indent=3, ensure_ascii=False, sort_keys=True)