Coding-python-标签-labelme_json2txt

代码

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
import os
import json

def convert_labelme_to_yolo(json_file, output_folder, class_dict):
# Read the JSON file
with open(json_file, 'r') as f:
data = json.load(f)

# Get image dimensions
img_width = data['imageWidth']
img_height = data['imageHeight']

# Get the image name without extension
img_name = os.path.splitext(os.path.basename(json_file))[0]

# Create YOLO format label file
txt_filename = os.path.join(output_folder, img_name + '.txt')
with open(txt_filename, 'w') as f:
for shape in data['shapes']:
if shape['shape_type'] != 'rectangle':
continue

# Get category
label = shape['label']
class_id = class_dict[label]

# Get bounding box coordinates
points = shape['points']
xmin, ymin = points[0]
xmax, ymax = points[1]

# Convert to YOLO format required coordinates
x_center = (xmin + xmax) / 2.0 / img_width
y_center = (ymin + ymax) / 2.0 / img_height
width = (xmax - xmin) / img_width
height = (ymax - ymin) / img_height

# Write to label file
line = f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n"
f.write(line)


def main():
# Define your class dictionary, where keys are class names and values are class IDs
# class_dict = {'Brassiere': 14, 'panties': 15}

class_dict = {
'Short sleeve top': 1,
'Long sleeve top': 2,
'Short sleeve outwear': 3,
'Long sleeve outwear': 4,
'Vest': 5,
'Sling': 6,
'Shorts': 7,
'Trousers': 8,
'Skirt': 9,
'Short sleeve dress': 10,
'Long sleeve dress': 11,
'Vest dress': 12,
'Sling dress': 13,
}


# Specify the folder containing JSON files and the output folder for YOLO labels
input_folder = 'train\\annos'
output_folder = 'train\\lables'

# Iterate over all JSON files in the input folder
for filename in os.listdir(input_folder):
if filename.endswith('.json'):
json_file = os.path.join(input_folder, filename)
convert_labelme_to_yolo(json_file, output_folder, class_dict)

if __name__ == "__main__":
main()