yolo目标检测数据采用矩形框进行标注,其标注格式为[cls_id xp yp wp hp],cls_id表示目标所属的类别序号。xp、yp表示目标中心点相对坐标,其中xp等于目标的绝对横坐标除以图像宽度,yp等于目标的绝对纵坐标除以图像高度。wp和hp表示目标的相对宽度和高度,其中wp等于目标的绝对宽度除以图像宽度,hp等于目标的绝对高度除以图像高度。每张图片的标注结果以txt文本文件存储,每一行[cls_id xp yp wp hp]表示一个目标。
cv_img=cv2.imdecode(np.fromfile(imagePath,dtype=np.uint8),flags=cv2.IMREAD_COLOR)
labelme矩形目标的标注格式为[x1 y1 x2 y2],表示目标的左上和右下的绝对坐标。
yolo转labelme标注程序如下所示:
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 29 17:42:11 2022
@author: https://blog.csdn.net/suiyingy?type=blog
"""
import cv2
import os
import json
import shutil
import numpy as np
from pathlib import Path
id2cls = {0:'pig'}
def xyxy2labelme(labels, w, h, image_path, save_dir='res/'):
save_dir = str(Path(save_dir)) + '/'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
label_dict = {}
label_dict['version'] = '5.0.1'
label_dict['flags'] = {}
label_dict['imageData'] = None
label_dict['imagePath'] = image_path
label_dict['imageHeight'] = h
label_dict['imageWidth'] = w
label_dict['shapes'] = []
for l in labels:
tmp = {}
tmp['label'] = id2cls[int(l[0])]
tmp['points'] =[[l[1], l[2]], [l[3], l[4]]]
tmp['group_id']= None
tmp['shape_type'] = 'rectangle'
tmp['flags'] = {}
label_dict['shapes'].append(tmp)
fn = save_dir+image_path.rsplit('.', 1)[0]+'.json'
with open(fn, 'w') as f:
json.dump(label_dict, f)
def yolo2labelme(yolo_image_dir, yolo_label_dir, save_dir='res/'):
yolo_image_dir = str(Path(yolo_image_dir)) + '/'
yolo_label_dir = str(Path(yolo_label_dir)) + '/'
save_dir = str(Path(save_dir)) + '/'
image_files = os.listdir(yolo_image_dir)
for iimgf, imgf in enumerate(image_files):
print(iimgf+1, '/', len(image_files), imgf)
fn = imgf.rsplit('.', 1)[0]
shutil.copy(yolo_image_dir + imgf, save_dir + imgf)
image = cv2.imread(yolo_image_dir + imgf)
h,w = image.shape[:2]
if not os.path.exists(yolo_label_dir + fn + '.txt'):
continue
labels = np.loadtxt(yolo_label_dir + fn + '.txt').reshape(-1, 5)
if len(labels) < 1:
continue
labels[:,1::2] = w * labels[:, 1::2]
labels[:,2::2] = h * labels[:, 2::2]
labels_xyxy = np.zeros(labels.shape)
labels_xyxy[:, 1] = np.clip(labels[:, 1] - labels[:, 3]/2, 0, w)
labels_xyxy[:, 2] = np.clip(labels[:, 2] - labels[:, 4]/2, 0, h)
labels_xyxy[:, 3] = np.clip(labels[:, 1] + labels[:, 3]/2, 0, w)
labels_xyxy[:, 4] = np.clip(labels[:, 2] + labels[:, 4]/2, 0, h)
xyxy2labelme(labels_xyxy, w, h, imgf, save_dir)
print('Completed!')
if __name__ == '__main__':
yolo_image_dir = r'H:\Data\pigs\images\train'
yolo_label_dir = r'H:\Data\pigs\labels\train'
save_dir = r'res/'
yolo2labelme(yolo_image_dir, yolo_label_dir, save_dir)
labelme转yolo标注程序如下所示:
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 29 17:42:11 2022
@author: https://blog.csdn.net/suiyingy?type=blog
"""
import cv2
import os
import json
import shutil
import numpy as np
from pathlib import Path
from glob import glob
id2cls = {0: 'pig'}
cls2id = {'pig': 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(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(anno['imagePath'])
labels = []
for s in shapes:
pts = s['points']
x1, y1 = pts[0]
x2, y2 = pts[1]
x = (x1 + x2) / 2 / w0
y = (y1 + y2) / 2 / h0
w = abs(x2 - x1) / w0
h = abs(y2 - y1) / h0
cid = cls2id[s['label']]
labels.append([cid, x, y, w, h])
return np.array(labels), image_path
def labelme2yolo(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 + 'labels/'
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')
for ijf, jf in enumerate(json_files):
print(ijf+1, '/', len(json_files), jf)
filename = os.path.basename(jf).rsplit('.', 1)[0]
labels, image_path = labelme2yolo_single(jf)
if len(labels) > 0:
np.savetxt(yolo_label_dir + filename + '.txt', labels)
shutil.copy(labelme_label_dir + image_path, yolo_image_dir + image_path)
print('Completed!')
if __name__ == '__main__':
root_dir = r'D:\tmp\images'
save_dir = r'res'
labelme2yolo(root_dir, save_dir)
labelme标注结果可视化程序如下所示:
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 29 17:42:11 2022
@author: https://blog.csdn.net/suiyingy?type=blog
"""
import cv2
import os
import json
import shutil
import numpy as np
from pathlib import Path
from glob import glob
id2cls = {0: 'pig'}
cls2id = {'pig': 0}
id2color = {0: (0, 255, 0)}
#支持中文路径
def cv_imread(filePath):
cv_img=cv2.imdecode(np.fromfile(filePath,dtype=np.uint8),flags=cv2.IMREAD_COLOR)
return cv_img
def get_labelme_info(label_file):
anno= json.load(open(label_file, "r", encoding="utf-8"))
shapes = anno['shapes']
image_path = os.path.basename(anno['imagePath'])
labels = []
for s in shapes:
pts = s['points']
x1, y1 = pts[0]
x2, y2 = pts[1]
color = id2color[cls2id[s['label']]]
labels.append([color, x1, y1, x2, y2])
return labels, image_path
def vis_labelme(labelme_label_dir, save_dir='res/'):
labelme_label_dir = str(Path(labelme_label_dir)) + '/'
save_dir = str(Path(save_dir)) + '/'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
json_files = glob(labelme_label_dir + '*.json')
for ijf, jf in enumerate(json_files):
print(ijf+1, '/', len(json_files), jf)
filename = os.path.basename(jf).rsplit('.', 1)[0]
labels, image_path = get_labelme_info(jf)
image = cv_imread(labelme_label_dir + image_path)
for label in labels:
color = label[0]
x1, y1, x2, y2 = label[1:]
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
cv2.rectangle(image, (x1, y1), (x2, y2), color, 3)
#显示图片
# cv2.imshow(filename, image)
# cv2.waitKey(0)
#支持中文路径,保存图片
cv2.imencode(os.path.splitext(image_path)[-1], image)[1].tofile(save_dir + image_path)
print('Completed!')
if __name__ == '__main__':
root_dir = r'D:\tmp\images'
save_dir = r'res'
vis_labelme(root_dir, save_dir)
yolo格式数据可视化程序如下所示:
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 29 17:42:11 2022
@author: https://blog.csdn.net/suiyingy?type=blog
"""
import cv2
import os
import numpy as np
from pathlib import Path
id2cls = {0: 'pig'}
cls2id = {'pig': 0}
id2color = {0: (0, 255, 0)}
#支持中文路径
def cv_imread(filePath):
cv_img=cv2.imdecode(np.fromfile(filePath,dtype=np.uint8),flags=cv2.IMREAD_COLOR)
return cv_img
def vis_yolo(yolo_image_dir, yolo_label_dir, save_dir='res/'):
yolo_image_dir = str(Path(yolo_image_dir)) + '/'
yolo_label_dir = str(Path(yolo_label_dir)) + '/'
save_dir = str(Path(save_dir)) + '/'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
image_files = os.listdir(yolo_image_dir)
for iimgf, imgf in enumerate(image_files):
print(iimgf+1, '/', len(image_files), imgf)
fn = imgf.rsplit('.', 1)[0]
image = cv_imread(yolo_image_dir + imgf)
h,w = image.shape[:2]
if not os.path.exists(yolo_label_dir + fn + '.txt'):
continue
labels = np.loadtxt(yolo_label_dir + fn + '.txt').reshape(-1, 5)
if len(labels) > 0:
labels[:,1::2] = w * labels[:, 1::2]
labels[:,2::2] = h * labels[:, 2::2]
labels_xyxy = np.zeros(labels.shape)
labels_xyxy[:, 1] = np.clip(labels[:, 1] - labels[:, 3]/2, 0, w)
labels_xyxy[:, 2] = np.clip(labels[:, 2] - labels[:, 4]/2, 0, h)
labels_xyxy[:, 3] = np.clip(labels[:, 1] + labels[:, 3]/2, 0, w)
labels_xyxy[:, 4] = np.clip(labels[:, 2] + labels[:, 4]/2, 0, h)
for label in labels_xyxy:
color = id2color[int(label[0])]
x1, y1, x2, y2 = label[1:]
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
cv2.rectangle(image, (x1, y1), (x2, y2), color, 3)
cv2.imencode(os.path.splitext(imgf)[-1], image)[1].tofile(save_dir + imgf)
print('Completed!')
if __name__ == '__main__':
yolo_image_dir = r'H:\Data\pigs\images\train'
yolo_label_dir = r'H:\Data\pigs\labels\train'
save_dir = r'res1/'
vis_yolo(yolo_image_dir, yolo_label_dir, save_dir)