labelme标注出来的标注文件格式是json文件,在利用yolo进行训练时,要使用YOLO格式的数据。
import cv2
import os
import json
import shutil
import numpy as np
from pathlib import Path
from glob import glob
from tqdm import tqdm
id2cls = {0: 'pen'}
cls2id = {'pen': 0}
#支持中文路径
def cv_imread(filePath):
cv_img=cv2.imdecode(np.fromfile(filePath,dtype=np.uint8),flags=cv2.IMREAD_COLOR)
return cv_img
def labelme2yolo_single(img_path,label_file):
anno= json.load(open(label_file, "r", encoding="utf-8"))
shapes = anno['shapes']
w0, h0 = anno['imageWidth'], anno['imageHeight']
image_path = os.path.basename(img_path + anno['imagePath'])
labels = []
for s in shapes:
pts = s['points']
x1, y1 = pts[0]
x2, y2 = pts[1]
x = round((x1 + x2) / 2 / w0, 8)
y = round((y1 + y2) / 2 / h0, 8)
w = round(abs(x2 - x1) / w0, 8)
h = round(abs(y2 - y1) / h0, 8)
cid = cls2id[s['label']]
labels.append([cid, x, y, w, h])
return np.array(labels, dtype=float), image_path
#这里的定位信息,xywh我选择了精确到小数点后第八位,可以根据需要随意修改。
# 确保所有数据都是数值类型
def labelme2yolo(img_path,labelme_label_dir, save_dir='res/'):
labelme_label_dir = str(Path(labelme_label_dir)) + '/'
save_dir = str(Path(save_dir))
yolo_label_dir = save_dir + '/'
""" yolo_image_dir = save_dir + 'images/'
if not os.path.exists(yolo_image_dir):
os.makedirs(yolo_image_dir) """
if not os.path.exists(yolo_label_dir):
os.makedirs(yolo_label_dir)
json_files = glob(labelme_label_dir + '*.json')
img_files = glob(img_path + '/*.jpg') + glob(img_path + '/*.png') # 假设图像文件是jpg或png格式
for jf in tqdm(json_files, desc="Processing JSON files"):
filename = os.path.basename(jf).rsplit('.', 1)[0]
labels, image_path = labelme2yolo_single(img_path,jf)
if len(labels) > 0:
np.savetxt(yolo_label_dir + filename + '.txt', labels, fmt='%d %.8f %.8f %.8f %.8f')
# 处理没有对应json文件的图像文件
for img_file in tqdm(img_files, desc="Processing image files"):
filename = os.path.basename(img_file).rsplit('.', 1)[0]
txt_file = yolo_label_dir + filename + '.txt'
if not os.path.exists(txt_file):
open(txt_file, 'w').close() # 创建一个空白的txt文件
# shutil.copy(labelme_label_dir + image_path, yolo_image_dir + image_path)
print('Completed!')images
if __name__ == '__main__':
img_path = 'F:/***/***/images/' # 数据集图片的路径
json_dir = 'F:/***/***/json' # json标签的路径
save_dir = 'F:/***/***/txt/' # 保存的txt标签的路径
labelme2yolo(img_path,json_dir, save_dir)