labelme . --labels ./labels.txt --autosave -o ./annotated --imagelabel ./images --output ./json
yolo格式的标注文件转成labelme可以查询的json格式
代码如下
import os
import json
from PIL import Image
# 读取图片尺寸
def get_image_size(image_path):
# 这里可以使用相应的方法获取图片尺寸,例如 PIL 库
# image_width, image_height = 320, 240 # 假设图片尺寸为 320x240
# return image_width, image_height
img = Image.open(image_path)
# 获取图像尺寸
image_width, image_height = img.size
# 返回图像尺寸
return image_width, image_height
# 转换 YOLO 格式标注为 JSON 格式
def convert_to_json(image_path, annotation_path):
# 读取图片尺寸
image_width, image_height = get_image_size(image_path)
# 读取文本标注文件
with open(annotation_path, 'r') as f:
yolo_data = f.readlines()
# 初始化 JSON 数据结构
json_data = {
"version": "5.3.1",
"flags": {},
"shapes": [],
"imagePath": image_path,
"imageData": None,
"imageHeight": image_height,
"imageWidth": image_width
}
# 转换为 JSON 格式
for line in yolo_data:
data = line.split()
label = data[0]
x_center = float(data[1]) * json_data["imageWidth"]
y_center = float(data[2]) * json_data["imageHeight"]
width = float(data[3]) * json_data["imageWidth"]
height = float(data[4]) * json_data["imageHeight"]
x1 = x_center - width / 2
y1 = y_center - height / 2
x2 = x_center + width / 2
y2 = y_center + height / 2
shape = {
"label": label,
"points": [[x1, y1], [x2, y2]],
"group_id": None,
"description": "",
"shape_type": "rectangle",
"flags": {}
}
json_data["shapes"].append(shape)
return json_data
# 创建新的文件夹
def create_directory(directory):
if not os.path.exists(directory):
os.makedirs(directory)
# 遍历图片文件夹和标注文件夹
image_folder = r"D:\HisCameraImage\datasetv2_240326\downloadIncorrect\images"
annotation_folder = r"D:\HisCameraImage\datasetv2_240326\downloadIncorrect\labels"
output_folder = r"D:\HisCameraImage\datasetv2_240326\downloadIncorrect\json"
create_directory(output_folder)
for root, dirs, files in os.walk(image_folder):
for file in files:
if file.endswith(".jpg"):
image_path = os.path.join(root, file)
annotation_path = os.path.join(annotation_folder, file[:-4] + ".txt")
if os.path.exists(annotation_path):
json_data = convert_to_json(image_path, annotation_path)
output_path = os.path.join(output_folder, file[:-4] + ".json")
with open(output_path, 'w') as f:
json.dump(json_data, f, indent=4)