代码如下,可自行根据labelme的version更改代码中的verson版本号,以及label类别,和图像的宽度和高度。
注意:代码中这部分:
for i in range(5, 16, 3): # 每 3 个元素为一个关键点(x, y, confidence)# 这里的16指的是从0开始到最后一个数字(pose——txt标签)
是我根据yolov8-pose模型输出额txt格式预标注标签来写的,我的标签中是一个框加四个关键点,所以5代表的是第一个关键点的第一个坐标,16代表总共数字的个数,3代表从5开始每隔3个取一个关键点
import os
import json
import base64
def convert_txt_to_json(txt_folder, json_folder, image_folder, image_width, image_height):
# 确保 JSON 文件夹存在
os.makedirs(json_folder, exist_ok=True)
# 遍历 TXT 文件夹中的所有文件
for filename in os.listdir(txt_folder):
if filename.endswith('.txt'):
txt_file_path = os.path.join(txt_folder, filename)
# 读取 TXT 文件
with open(txt_file_path, 'r', encoding='utf-8') as f:
line = f.readline().strip()
# 处理每一行
parts = list(map(float, line.split()))
# 确保数据格式正确
if len(parts) >= 13:
class_id = int(parts[0])
x_center = parts[1] * image_width
y_center = parts[2] * image_height
width = parts[3] * image_width
height = parts[4] * image_height
# 计算矩形框的顶点
x1 = x_center - width / 2
y1 = y_center - height / 2
x2 = x_center + width / 2
y2 = y_center + height / 2
# 读取关键点和置信度
keypoints = []
for i in range(5, 16, 3): # 每 3 个元素为一个关键点(x, y, confidence)# 这里的16指的是从0开始到最后一个数字(pose——txt标签)
if i + 2 < len(parts): # 确保有足够的数据
keypoints.append({
'label': str(len(keypoints) + 5), # 关键点标签 5,6,7,8 # 若要1,2,3,4则将5改为1
'points': [[parts[i] * image_width, parts[i + 1] * image_height]],
'group_id': None,
'shape_type': 'point',
'flags':{}
})
# 获取对应的图像文件名
image_name = filename.replace('.txt', '.jpg') # 假设图像格式为 jpg
image_path = os.path.join(image_folder, image_name)
# 读取图像数据并进行编码
image_data = ""
if os.path.exists(image_path):
with open(image_path, "rb") as img_file:
image_data = base64.b64encode(img_file.read()).decode('utf-8')
# 创建 JSON 数据
json_data = {
"version": "5.1.1",
"flags": {},
"shapes": [
{
"label": "pylon", # 矩形框的标签
"points": [[x1, y1], [x2, y2]],
"group_id": None,
"shape_type": "rectangle",
"flags": {}
}
] + keypoints, # 添加关键点
"imagePath": image_name, # 图片名称
"imageData": image_data, # 图像的 base64 编码数据
"imageHeight": image_height,
"imageWidth": image_width
}
# 保存为 JSON 文件
json_file_path = os.path.join(json_folder, filename.replace('.txt', '.json'))
with open(json_file_path, 'w', encoding='utf-8') as f:
json.dump(json_data, f, ensure_ascii=False, indent=4)
print(f"Converted: {txt_file_path} to {json_file_path}")
image_width = 720 # 替换为实际图像宽度
image_height = 1280 # 替换为实际图像高度
# 使用示例
txt_folder = r'C:\Users\Administrator\Desktop\orb_images_hanger_pylon\orb_train_table\labels_pylon_yolo' # 替换为你的 TXT 文件夹路径
json_folder = r'C:\Users\Administrator\Desktop\orb_images_hanger_pylon\orb_train_table\labels_pylon_json' # 替换为你的 JSON 文件夹路径
image_folder = r'C:\Users\Administrator\Desktop\orb_images_hanger_pylon\orb_train_table\images' # 替换为你的图像文件夹路径
convert_txt_to_json(txt_folder, json_folder, image_folder, image_width, image_height)