第一章 导包
import os
import json
第二章 两条路径
json_dir = '' # json文件路径
out_dir = '' # 输出的 txt 文件路径
第三章 读取json文件
def get_json(json_file, filename):
# 读取 json 文件数据
with open(json_file, 'r') as load_f:
content = json.load(load_f)
第四章 创建txt文件并写入
tmp = filename
filename_txt = out_dir + tmp + '.txt'
# 创建txt文件
fp = open(filename_txt, mode="w", encoding="utf-8")
# 将数据写入文件
# 计算 yolo 数据格式所需要的中心点的 相对 x, y 坐标, w,h 的值
x = (content["shapes"][0])["points"][0][0]
y = (content["shapes"][0])["points"][0][1]
w = (content["shapes"][0])["points"][1][0] - (content["shapes"][0])["points"][0][0]
h = (content["shapes"][0])["points"][1][1] - (content["shapes"][0])["points"][0][1]
fp = open(filename_txt, mode="r+", encoding="utf-8")
file_str = str(filename) + ' ' + str(round(x, 6)) + ' ' + str(round(y, 6)) + ' ' + str(round(w, 6)) + \
' ' + str(round(h, 6))
line_data = fp.readlines()
if len(line_data) != 0:
fp.write('\n' + file_str)
else:
fp.write(file_str)
fp.close()
第六章 遍历文件夹
def main():
files = os.listdir(json_dir) # 得到文件夹下的所有文件名称
s = []
for file in files: # 遍历文件夹
filename = file.split('.')[0]
# print(tmp)
get_json(json_dir + file, filename)
第七章 创建主函数并调用
if __name__ == '__main__':
main()
全部代码如下:
import os
import json
json_dir = '' # json文件路径
out_dir = '' # 输出的 txt 文件路径
def get_json(json_file, filename):
# 读取 json 文件数据
with open(json_file, 'r') as load_f:
content = json.load(load_f)
# # 循环处理
tmp = filename
filename_txt = out_dir + tmp + '.txt'
# 创建txt文件
fp = open(filename_txt, mode="w", encoding="utf-8")
# 将数据写入文件
# 计算 yolo 数据格式所需要的中心点的 相对 x, y 坐标, w,h 的值
x = (content["shapes"][0])["points"][0][0]
y = (content["shapes"][0])["points"][0][1]
w = (content["shapes"][0])["points"][1][0] - (content["shapes"][0])["points"][0][0]
h = (content["shapes"][0])["points"][1][1] - (content["shapes"][0])["points"][0][1]
fp = open(filename_txt, mode="r+", encoding="utf-8")
file_str = str(filename) + ' ' + str(round(x, 6)) + ' ' + str(round(y, 6)) + ' ' + str(round(w, 6)) + \
' ' + str(round(h, 6))
line_data = fp.readlines()
if len(line_data) != 0:
fp.write('\n' + file_str)
else:
fp.write(file_str)
fp.close()
def main():
files = os.listdir(json_dir) # 得到文件夹下的所有文件名称
s = []
for file in files: # 遍历文件夹
filename = file.split('.')[0]
# print(tmp)
get_json(json_dir + file, filename)
if __name__ == '__main__':
main()
最近写的一个新版本
import json
import os
from tqdm import tqdm # 可选进度条库
def labelme_json_to_yolo(txt_save_path, json_path, class_map):
"""
将LabelMe格式JSON转换为YOLO TXT标注文件
:param txt_save_path: TXT保存路径
:param json_path: LabelMe JSON文件路径
:param class_map: 类别名映射字典(如{"person": 0})
"""
with open(json_path, 'r', encoding='utf-8') as f:
data = json.load(f)
img_height = data["imageHeight"]
img_width = data["imageWidth"]
img_name = os.path.basename(data["imagePath"]) # 提取图片文件名
txt_name = os.path.splitext(img_name)[0] + ".txt"
txt_path = os.path.join(txt_save_path, txt_name)
lines = []
for shape in data["shapes"]:
label = shape["label"]
if label not in class_map:
continue # 跳过未定义类别
cls_id = class_map[label]
# 解析多边形/矩形标注为边界框(xmin, ymin, xmax, ymax)
points = shape["points"]
x_coords = [p[0] for p in points]
y_coords = [p[1] for p in points]
xmin = min(x_coords)
ymin = min(y_coords)
xmax = max(x_coords)
ymax = max(y_coords)
# 计算YOLO格式坐标(归一化中心坐标+宽高)
x_center = (xmin + xmax) / (2 * img_width)
y_center = (ymin + ymax) / (2 * img_height)
w = (xmax - xmin) / img_width
h = (ymax - ymin) / img_height
# 过滤无效坐标(避免越界)
if 0 <= x_center <= 1 and 0 <= y_center <= 1 and w > 0 and h > 0:
lines.append(f"{cls_id} {x_center:.6f} {y_center:.6f} {w:.6f} {h:.6f}")
# 保存TXT文件
with open(txt_path, 'w') as f:
f.write('\n'.join(lines))
def batch_convert_labelme_to_yolo(json_folder, txt_folder, class_map):
"""
批量转换LabelMe格式JSON文件夹到YOLO TXT
:param json_folder: JSON文件夹路径
:param txt_folder: TXT保存路径
:param class_map: 类别名映射字典(如{"person": 0})
"""
os.makedirs(txt_folder, exist_ok=True)
json_files = [f for f in os.listdir(json_folder) if f.lower().endswith('.json')]
for json_file in tqdm(json_files, desc="转换中"):
json_path = os.path.join(json_folder, json_file)
labelme_json_to_yolo(txt_folder, json_path, class_map)
print(f"批量转换完成!共处理{len(json_files)}个JSON文件,保存到:{txt_folder}")
# 示例调用(需根据实际修改)
if __name__ == "__main__":
JSON_FOLDER = "F:/pytharm/gan/data_dm/lables_json" # LabelMe JSON文件夹路径
TXT_FOLDER = "F:/pytharm/gan/data_dm/lables" # YOLO TXT保存路径
CLASS_MAP = {"person": 0} # 类别名映射(需与实际标注一致)
batch_convert_labelme_to_yolo(JSON_FOLDER, TXT_FOLDER, CLASS_MAP)
json的格式有很多种,要根据自己的json内容格式去写专门的属于自己的转换代码,这两个仅供参考,后续有新格式后也会更新,如有疑问可以留言交流。
本文介绍了一个Python程序,它读取指定目录下的JSON文件,解析其中的数据,特别是Yolo所需的中心点坐标,然后将这些信息写入对应的txt文件。程序通过遍历文件夹来处理多个文件。
2万+

被折叠的 条评论
为什么被折叠?



