yolo检测生成的txt转换为labelme可以编辑的json
yolo检测生成的txt转换为labelme可以编辑的json以及json转txttxt转json代码如下import cv2 import os import json 该脚本实现将yolo格式标签转为json格式标签 需要的数据原始图像 原始yolo格式标签txt文件 imgs_path D:/.../images/ # 图像路径 txt_dir D:/.../labels/ # txt标签目录路径 out_json_dir D:/.../json/ # 保存的json文件路径 # 确保输出目录存在 os.makedirs(out_json_dir, exist_okTrue) # 定义YOLO标签类别映射 name_label [A, B, C] # 需要与训练时的类别顺序一致 def convert_yolo_bbox(box, img_shape): 将YOLO格式的归一化坐标转换为像素坐标 x_center, y_center, w, h box img_h, img_w img_shape[:2] x1 int((x_center - w / 2) * img_w) y1 int((y_center - h / 2) * img_h) x2 int((x_center w / 2) * img_w) y2 int((y_center h / 2) * img_h) return [x1, y1, x2, y2] def parse_yolo_txt(img_path, txt_path): 解析YOLO标签文件 img cv2.imread(img_path) if img is None: raise FileNotFoundError(f无法读取图像: {img_path}) bboxes [] if not os.path.exists(txt_path): return img, bboxes # 返回空列表表示没有目标 with open(txt_path, r) as f: for line in f.readlines(): parts line.strip().split() if len(parts) ! 5: continue # 解析YOLO格式 label_idx int(parts[0]) label name_label[label_idx] x_center float(parts[1]) y_center float(parts[2]) width float(parts[3]) height float(parts[4]) # 转换坐标 bbox convert_yolo_bbox([x_center, y_center, width, height], img.shape) bbox.append(label) bboxes.append(bbox) return img, bboxes def create_labelme_json(img_name, img_dir, txt_dir, output_dir): 创建Labelme格式的JSON标注文件 # 构建完整路径 img_path os.path.join(img_dir, img_name) txt_path os.path.join(txt_dir, img_name.replace(.jpg, .txt)) # 解析数据 try: img, gt_boxes parse_yolo_txt(img_path, txt_path) except Exception as e: print(f处理 {img_name} 时出错: {str(e)}) return # 构建基础字典 label_dict { version: 5.5.0, flags: {}, shapes: [], imagePath: img_path, imageData: None, imageHeight: img.shape[0], imageWidth: img.shape[1] } # 添加标注形状 for box in gt_boxes: shape { label: box[-1], points: [[box[0], box[1]], [box[2], box[3]]], group_id: None, description: , shape_type: rectangle, flags: {}, mask: None } label_dict[shapes].append(shape) # 写入JSON文件 output_path os.path.join(output_dir, img_name.replace(.jpg, .json)) with open(output_path, w) as f: json.dump(label_dict, f, indent2) print(f已生成: {output_path}) # 主处理循环 img_files [f for f in os.listdir(imgs_path) if f.lower().endswith(.jpg)] for idx, img_name in enumerate(img_files): if idx % 100 0: print(f处理进度: {idx}/{len(img_files)}) create_labelme_json(img_name, imgs_path, txt_dir, out_json_dir) print(转换完成)JSON转txt代码如下import json import os input_folder D:/.../json output_folder D:/.../txt os.makedirs(output_folder, exist_okTrue) # 标注类别名 label_to_id_mapping { A: 0, B: 1, C: 2, D: 3 # Add more mappings as needed } def convert_annotation(json_file, txt_file, label_to_id_mapping): # Read the JSON file with open(json_file, r, encodingutf-8) as f: data json.load(f) # Extract image dimensions, assuming imageWidth and imageHeight fields are present image_width data.get(imageWidth) image_height data.get(imageHeight) # Check if image dimensions are present if image_width is None or image_height is None: raise ValueError(fMissing image dimensions in {json_file}) # Iterate over all shapes (annotations) with open(txt_file, w, encodingutf-8) as out_file: for shape in data.get(shapes, []): # Extract point coordinates, assuming each shape has a points field points shape.get(points, []) # Check if points are present if not points: raise ValueError(fMissing points in a shape in {json_file}) x_values [point[0] for point in points] y_values [point[1] for point in points] x_min min(x_values) y_min min(y_values) x_max max(x_values) y_max max(y_values) # Calculate bounding box center, width, and height bbox_center_x (x_min x_max) / 2 bbox_center_y (y_min y_max) / 2 bbox_width x_max - x_min bbox_height y_max - y_min # Convert bounding box coordinates to ratios relative to image dimensions bbox_center_x_ratio bbox_center_x / image_width bbox_center_y_ratio bbox_center_y / image_height bbox_width_ratio bbox_width / image_width bbox_height_ratio bbox_height / image_height # Get the category ID, assuming each shape has a label field category_id shape.get(label, unknown) if isinstance(category_id, str): # If the label is a string, map it to a numeric ID using the provided mapping category_id label_to_id_mapping.get(category_id, -1) # Default to -1 if label is unknown # Write the result to the TXT file in YOLO format out_file.write( f{int(category_id)} {bbox_center_x_ratio} {bbox_center_y_ratio} {bbox_width_ratio} {bbox_height_ratio}\n) # Input and output folder paths # 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) txt_file os.path.join(output_folder, filename.replace(.json, .txt)) try: convert_annotation(json_file, txt_file, label_to_id_mapping) print(f{txt_file},Conversion successful!) except Exception as e: print(fAn error occurred while processing {json_file}: {e})
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2595650.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!