-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert_xml_to_json.py
More file actions
45 lines (37 loc) · 1.78 KB
/
convert_xml_to_json.py
File metadata and controls
45 lines (37 loc) · 1.78 KB
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
import json
from wsi_annotations_kit import wsi_annotations_kit as wak
from typing import Dict
def xml_to_json(xml_file_path: str, json_file_path: str, annotation_map: Dict[str, int] = None) -> None:
"""
Convert an XML annotation file to a JSON format and update its annotations.
Parameters:
- xml_file_path (str): Path to the input XML annotation file.
- json_file_path (str): Path to save the output JSON file.
- annotation_map (Dict[str, int], optional): A dictionary to map annotation types to IDs.
Default is {'Nuclei': 1}.
"""
if annotation_map is None:
annotation_map = {'Nuclei': 1}
try:
# Step 1: Convert XML to JSON and save to specified path
print(f"Converting XML ({xml_file_path}) to JSON ({json_file_path})...")
converter = wak.Converter(xml_file_path, annotation_map)
converter.json_save(json_file_path)
print(f"Initial JSON saved to {json_file_path}.")
# Step 2: Load the JSON file
with open(json_file_path, 'r') as file:
annotations = json.load(file)
# Step 3: Update the JSON annotations
print("Updating JSON annotations with line color...")
for annotation_dict in annotations:
annotation = annotation_dict.get("annotation")
if annotation and "elements" in annotation:
for element in annotation["elements"]:
element["lineColor"] = "rgba(255, 0, 0, 255)"
# Step 4: Save the updated JSON back to the file
with open(json_file_path, 'w') as file:
json.dump(annotations, file, indent=4)
print(f"Updated JSON successfully saved to {json_file_path}.")
except Exception as e:
print(f"An error occurred during XML to JSON conversion: {e}")
raise