labelme2yolo

import numpy as np
import os
from pathlib import Path
from tqdm import tqdm
import cv2
from tqdm.contrib import tzip
import json

# python train.py --data kll/lp.yaml --epochs 10 --weights ./yolov5s.pt  --batch-size 20 --device 0 --workers 1

class_names = ['lp', 'face']
                
def crpd2yolo(images_path: str, labels_path: str, save_labels_top: str):
    
    if not os.path.exists(save_labels_top):
        os.makedirs(save_labels_top)
    
    for f1, f2 in tzip(os.listdir(images_path), os.listdir(labels_path)):
        path_image = f'{images_path}/{f1}'
        path_label = f'{labels_path}/{f2}'
        
        im = cv2.imread(path_image)
        w , h = im.shape[1], im.shape[0]
        
        if(Path(path_image).stem == Path(path_label).stem):
            with open(path_label, 'r', encoding='utf-8') as f:
                coorList = f.read().split(" ")
                type = 0
                xyxy = [int(coorList[0]), int(coorList[1]), int(coorList[4]), int(coorList[5])]
            x,y,w,h = xyxy2xywh(xyxy, w, h)
            with open(f'{save_labels_top}/{Path(path_label).name}', 'w', encoding='utf-8') as f:
                s = f'{type} {x} {y} {w} {h}'
                f.write(s)
                    
        
        
def xyxy2xywh(xyxy: list, im0_w, im0_h):
    """
    xyxy
    """
    x = (xyxy[0] + xyxy[2]) / 2
    y = (xyxy[1] + xyxy[3]) / 2
    w = xyxy[2] - xyxy[0]
    h = xyxy[3] - xyxy[1]   

    # norm
    x = x / im0_w
    y = y / im0_h
    w = w / im0_w
    h = h / im0_h
    
    return x,y,w,h


def check_labels(path):
    """
    检测 lables 文件是否有负值
    """
    for f in tqdm(os.listdir(path)):
        file = f'{path}/{f}'
        with open(file, 'r') as f:
            line = f.read().split(" ")
            for coord in line[1:]:
                assert float(coord) > 0, f'Coord should less than 0, file is {file}'
                
                
def labelme2yolo(json_path: str, save_path: str):
    
    files = os.listdir(json_path)
    for fn in files:
        if not fn.endswith('json'): continue
        
        with open(os.path.join(json_path, fn), 'r') as f, open(os.path.join(save_path, Path(fn).stem + '.txt'), 'w') as f2:
            json_data = json.load(f)
            fn = json_data['imagePath']
            h, w = json_data['imageHeight'], json_data['imageWidth']
            
            for shape in json_data['shapes']:
                lable = shape['label']
                points = shape['points']
                
                points = np.array(points)
                # yolov5 格式 cx cy w h
                xmin, xmax = max(0, min(points[:, 0])), min(w, max(points[:, 0]))
                ymin, ymax = max(0, min(points[:, 1])), min(h, max(points[:, 1]))
            
                bbox = [xmin, ymin, xmax, ymax]
                lines = xyxy2xywh(bbox, w, h)
                
                f2.write(f'{str(class_names.index(lable))} {" ".join(str(l) for l in lines)} \n')
                
                
    
    pass
               
       
if __name__ == '__main__':
    # crpd2yolo(r"H:\dataset\CRPD_single\train\images", r"H:\dataset\CRPD_single\train\labels", r"H:\dataset\zp_crpd\train20k\labels")
    labelme2yolo(r'H:\dataset\tt', r'H:\dataset\t2')
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值