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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| import os import glob import numpy as np import cv2 import json
def convert_txt_to_labelme_json(txt_path, image_path, output_dir, class_name, image_fmt='.png' ): """ 将文本文件转换为LabelMe格式的JSON文件。 此函数处理文本文件中的数据,将其转换成LabelMe标注工具使用的JSON格式。包括读��图像, 解析文本文件中的标注信息,并生成相应的JSON文件。 :param txt_path: 文本文件所在的路径 :param image_path: 图像文件所在的路径 :param output_dir: 输出JSON文件的目录 :param class_name: 类别名称列表,索引对应类别ID :param image_fmt: 图像文件格式,默认为'.png' :return: """ txts = glob.glob(os.path.join(txt_path, "*.txt")) for txt in txts: labelme_json = { 'version': '3.16.2', 'flags': {}, 'shapes': [], 'lineColor': [0, 255, 0, 128], 'fillColor': [255, 0, 0, 128], 'imagePath': None, 'imageData': None, 'imageHeight': None, 'imageWidth': None, } txt_name = os.path.basename(txt) image_name = txt_name.split(".")[0] + image_fmt labelme_json['imagePath'] = image_name image_name = os.path.join(image_path, image_name) if not os.path.exists(image_name): raise Exception('txt 文件={},找不到对应的图像={}'.format(txt, image_name)) image = cv2.imdecode(np.fromfile(image_name, dtype=np.uint8), cv2.IMREAD_COLOR) h, w = image.shape[:2] labelme_json['imageHeight'] = h labelme_json['imageWidth'] = w os.makedirs(output_dir, exist_ok=True) with open(txt, 'r') as t: lines = t.readlines() for line in lines: point_list = [] content = line.strip().split(' ') if len(content) < 5: continue label = class_name[int(content[0])] cx = float(content[1]) cy = float(content[2]) wi = float(content[3]) hi = float(content[4]) x1 = (2 * cx * w - w * wi) / 2 x2 = (w * wi + 2 * cx * w) / 2 y1 = (2 * cy * h - h * hi) / 2 y2 = (h * hi + 2 * cy * h) / 2 point_list.append(x1) point_list.append(y1) point_list.append(x2) point_list.append(y2) point_list = [point_list[i:i+2] for i in range(0, len(point_list), 2)] shape = { 'label': label, 'line_color': None, 'fill_color': None, 'points': point_list, 'shape_type': 'rectangle', 'flags': {} } labelme_json['shapes'].append(shape) json_name = txt_name.split('.')[0] + '.json' json_name_path = os.path.join(output_dir, json_name) with open(json_name_path, 'w', encoding='utf-8') as fd: json.dump(labelme_json, fd, indent=2, ensure_ascii=False) print("save json={}".format(json_name_path)) if __name__ == '__main__': txt_path = 'yolo格式标签文件夹路径' image_path ='图像文件夹路径(用于读取图像名和图像大小)' output_dir = 'labelme标签输出文件夹路径' class_name = ['orange','apple'] convert_txt_to_labelme_json(txt_path, image_path, output_dir, class_name)
|