Json转txt
1.多边形
import json
import os#将坐标归一化到 [0, 1] 范围。
def normalize_points(points, image_width, image_height):"""Normalize polygon points to be in the range [0, 1]."""return [(x / image_width, y / image_height) for x, y in points]#将Labelme JSON标注转换为TXT格式
def labelme_json_to_txt(json_dir, txt_dir):if not os.path.exists(txt_dir):os.makedirs(txt_dir)for filename in os.listdir(json_dir):if filename.endswith('.json'):json_file_path = os.path.join(json_dir, filename)image_name = os.path.splitext(filename)[0]txt_file_path = os.path.join(txt_dir, f'{image_name}.txt')with open(json_file_path, 'r', encoding='utf-8') as json_file:data = json.load(json_file)shapes = data.get('shapes', [])image_height = data.get('imageHeight', 0)image_width = data.get('imageWidth', 0)with open(txt_file_path, 'w', encoding='utf-8') as out_f:for shape in shapes:shape_type = shape.get('shape_type', '')label = shape.get('label', '')points = shape.get('points', [])if shape['shape_type'] == "polygon":normalized_points = normalize_points(points, image_width, image_height)# Write the label (if present) followed by normalized pointsout_f.write(f"{label} ")out_f.write(" ".join(f"{x:.6f} {y:.6f}" for x, y in normalized_points))out_f.write("\n")else:print(f'Warning: Unknown shape type "{shape_type}" found in {json_file_path}')# 使用示例
json_directory = 'C:\\Users\Administrator\Desktop\自己制作的数据集\json'#你要修改的输入json地址
txt_output_directory = 'C:\\Users\Administrator\Desktop\自己制作的数据集\labels'#你要修改的txt保存的地址labelme_json_to_txt(json_directory, txt_output_directory)
2.矩形或者多边形
import os
import cv2
import glob
import json
import numpy as np
from tqdm import tqdm# 参考链接 https://zhuanlan.zhihu.com/p/622246547# 将labelme_json标注转yolo_txt
def convert(size, box):"""convert [xmin, xmax, ymin, ymax] to [x_centre, y_centre, w, h]"""dw = 1. / size[0]dh = 1. / size[1]x = (box[0] + box[1]) / 2.0y = (box[2] + box[3]) / 2.0w = box[1] - box[0]h = box[3] - box[2]x = x * dww = w * dwy = y * dhh = h * dhreturn [x, y, w, h]if __name__ == "__main__":class_names = []# json文件夹路径json_dir = r"O:\DeepLearningTool\01_handle_dataset\dataset\object\image"# 转化后txt的保存路径txt_dir = r"O:\DeepLearningTool\01_handle_dataset\dataset\object\label"if not os.path.exists(txt_dir):os.makedirs(txt_dir, exist_ok=True)json_pths = glob.glob(json_dir + "/*.json")for json_pth in tqdm(json_pths, desc='Processing'):f1 = open(json_pth, "r")json_data = json.load(f1)img_pth = os.path.join(json_dir, json_pth.replace("json", "jpg"))img = cv2.imread(img_pth)h, w = img.shape[:2]tag = os.path.basename(json_pth)out_file = open(os.path.join(txt_dir, tag.replace("json", "txt")), "w")label_infos = json_data["shapes"]for label_info in label_infos:label = label_info["label"]points = label_info["points"]if len(points) >= 3:points = np.array(points)xmin, xmax = max(0, min(np.unique(points[:, 0]))), min(w, max(np.unique(points[:, 0])))ymin, ymax = max(0, min(np.unique(points[:, 1]))), min(h, max(np.unique(points[:, 1])))elif len(points) == 2:x1, y1 = points[0]x2, y2 = points[1]xmin, xmax = min(x1, x2), max(x1, x2)ymin, ymax = min(y1, y2), max(y1, y2)else:continuebbox = [xmin, xmax, ymin, ymax]bbox_ = convert((w,h), bbox)if label not in class_names:class_names.append(label)cls_id = class_names.index(label)out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bbox_]) + '\n')with open(txt_dir + 'classes.txt', 'w') as f:for i in class_names:f.write(i + '\n')
3.圆形/矩形/多边形
import os
import json
import warnings
warnings.filterwarnings("ignore")json_dir = './labels_json/' # 输入 JSON
out_dir = './labels_txt/' # 输出 txtos.makedirs(out_dir, exist_ok=True)# 类别顺序,决定 cls_id
name = ['cola', 'pepsi', 'sprite', 'fanta', 'spring','ice', 'scream', 'milk', 'red', 'king']
name_class = {n: i for i, n in enumerate(name)}image_width = 5568
image_height = 3712def json2txt(json_file, filename):with open(json_file, 'r', encoding='utf-8') as f:data = json.load(f)txt_path = os.path.join(out_dir, filename + '.txt')# 先清空open(txt_path, 'w').close()for shape in data.get('shapes', []):label = shape['label']if label not in name_class:continuecls_id = name_class[label]pts = shape['points']shape_type = shape.get('shape_type', '')# ===== 1) 圆形 =====if shape_type == 'circle' and len(pts) == 2:cx, cy = pts[0]px, py = pts[1]r = ((px - cx) ** 2 + (py - cy) ** 2) ** 0.5xmin, xmax = cx - r, cx + rymin, ymax = cy - r, cy + r# ===== 2) 矩形 / 多边形 =====else:# 统一取外接矩形xs, ys = zip(*pts)xmin, xmax = min(xs), max(xs)ymin, ymax = min(ys), max(ys)# 限制在图像内xmin = max(0, xmin)ymin = max(0, ymin)xmax = min(image_width, xmax)ymax = min(image_height, ymax)# 中心点 + 宽高 归一化x = (xmin + xmax) / 2.0 / image_widthy = (ymin + ymax) / 2.0 / image_heightw = (xmax - xmin) / image_widthh = (ymax - ymin) / image_heightline = f"{cls_id} {x:.6f} {y:.6f} {w:.6f} {h:.6f}\n"with open(txt_path, 'a', encoding='utf-8') as f:f.write(line)def main():for file in os.listdir(json_dir):if file.endswith('.json'):json_path = os.path.join(json_dir, file)name_no_ext = os.path.splitext(file)[0]json2txt(json_path, name_no_ext)if __name__ == '__main__':main()