import json
import os
def convert_labelme_to_yolo(json_path, txt_path, label_dict):
with open(json_path, 'r') as file:
data = json.load(file)
image_width = data['imageWidth']
image_height = data['imageHeight']
with open(txt_path, 'w') as file:
for shape in data['shapes']:
label = shape['label']
points = shape['points']
x_min, y_min = points[0]
x_max, y_max = points[1]
x_center = (x_min + x_max) / 2 / image_width
y_center = (y_min + y_max) / 2 / image_height
width = (x_max - x_min) / image_width
height = (y_max - y_min) / image_height
class_id = label_dict[label]
file.write(f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n")
def batch_convert(input_folder, output_folder, label_dict):
os.makedirs(output_folder, exist_ok=True)
for file_name in os.listdir(input_folder):
if file_name.endswith('.json'):
json_path = os.path.join(input_folder, file_name)
txt_path = os.path.join(output_folder, file_name.replace('.json', '.txt'))
convert_labelme_to_yolo(json_path, txt_path, label_dict)
def create_label_file(label_dict, output_path):
sorted_labels = [label for label, _ in sorted(label_dict.items(), key=lambda item: item[1])]
with open(output_path, 'w') as file:
for label in sorted_labels:
file.write(f"{label}\n")
if __name__ == '__main__':
# Example usage
label_dict = {"car": 0, "tree": 1}
input_folder = r'C:\Users\ailiu\Desktop\yolo\data'
output_folder = r'C:\Users\ailiu\Desktop\yolo\data'
batch_convert(input_folder, output_folder, label_dict)
# 生成lableme.txt文件,按照label_dict的值从小到大排列,一个类别1行
create_label_file(label_dict,r'C:\Users\ailiu\Desktop\yolo\data\yolo-label.txt')
lableme的 json (矩形框标注)转换为yolo 格式的txt --- (类别 x,y,w,h形式)
于 2024-04-16 20:16:04 首次发布