将Labelme标注的图片按种类进行切割成小图片

'''
切成单类别小图并放入TEA_CHECK\CLS_Folder文件夹中
'''
Org_Img_Path = 'C:\work\sun\datasets\RedTeaV\RedTeaV_L5_Product_III_train.txt'
Org_Json_Path = Org_Img_Path
Threshold_and = 25
Threshold_or = 10
DarwPoint = False
distination = "C:\work\sun\datasets\RedTeaV\RedTeaV_L5_Product"
###################################################################################
if __name__ == '__main__':
    if not os.path.exists(distination):
        os.makedirs(distination)
    if os.path.isfile(Org_Img_Path) and Org_Img_Path.endswith("txt"):
        with open(Org_Img_Path) as fx:
            line = fx.read().strip().splitlines()
            Img_Files = [item for item in line if item.split(".")[-1] in ["jpg","bmp","png"]]
    else:
        Img_Files = glob.glob(Org_Img_Path + "\*.jpg")+glob.glob(Org_Img_Path + "\*.bmp")+glob.glob(Org_Img_Path + "\*.png")

    for idx, Img_File in tqdm(enumerate(Img_Files),total=len(Img_Files)):
        imgItem = os.path.basename(Img_File)
        JsonItem = imgItem.replace(imgItem.split(".")[-1],"json")
        json_File = Img_File.replace(Img_File.split(".")[-1],"json")
        if not os.path.isfile(json_File):
            print("{} do not have same Name json !".format(json_File))
            continue
        im0s = cv2.imread(Img_File)
        data = json.load(open(json_File))
        box_list = []
        point_list = []
        for shape in data['shapes']:
            if shape['shape_type'] == 'rectangle':
                box_list.append(shape)
            elif shape['shape_type'] == 'point':
                point_list.append(shape)
        if len(box_list)==1:
            for id , (box_shape, point_shape) in enumerate(zip(box_list,point_list)):
                label_name = box_shape['label']
                folder_cls = os.path.join(distination, label_name)
                if not os.path.exists(folder_cls):
                    os.mkdir(folder_cls)
                label_point = box_shape['points']
                label_point = np.array(label_point).astype(np.int32)
                X1,Y1,X2,Y2 = label_point[0][0], label_point[0][1], label_point[1][0], label_point[1][1]
                Xmin, Ymin = min(X1, X2), min(Y1, Y2)
                Xmax, Ymax = max(X1, X2), max(Y1, Y2)
                Xmin,Ymin,Xmax,Ymax = max(int(Xmin),0),max(int(Ymin),0),min(max(int(Xmax),0),im0s.shape[1]) , min(max(int(Ymax),0),im0s.shape[0])
                KeyPoint = np.array(point_shape['points']).flatten().astype(np.int32)
                KeyPoint_X, KeyPoint_Y = KeyPoint[0], KeyPoint[1]
                KeyPoint_X, KeyPoint_Y = KeyPoint_X - Xmin, KeyPoint_Y - Ymin
                if (Ymax - Ymin) < Threshold_and and (Xmax - Xmin) < Threshold_and:
                    continue
                if (Ymax - Ymin) < Threshold_or or (Xmax - Xmin) < Threshold_or:
                    continue
                SMImg = im0s[Ymin:Ymax, Xmin:Xmax, :]
                KeyPoint_X, KeyPoint_Y = round(KeyPoint_X), round(KeyPoint_Y)
                if DarwPoint:
                    cv2.circle(SMImg, (KeyPoint_X, KeyPoint_Y), 5, (0, 0, 255), -1)
                keyPoint_str = str(KeyPoint_X) + "," + str(KeyPoint_Y)
                name = 'im_' + imgItem.split(".")[-2] + '_' + format(str(id), '0>3s') + "_X" + str(KeyPoint_X) + "_Y" + str(KeyPoint_Y) + '_.png'
                box_str = str(X1) + "," + str(Y1) + "," + str(X2) + "," + str(Y2)
                save_path = os.path.join(folder_cls, name)
                cv2.imwrite(save_path, SMImg)

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将labelme标注的数据转换成yolo可识别的数据标注集,需要进行以下步骤: 1. 解析labelme标注文件:labelme标注工具会生成一个或多个JSON文件,每个文件对应一张图片标注信息。首先需要读取这些JSON文件,并解析出图片路径、图片尺寸以及标注框的位置和类别信息。 2. 转换坐标格式:labelme标注框的位置信息通常是以像素坐标表示的,而yolo需要的是归一化后的坐标。因此,需要将像素坐标转换成相对于图片尺寸的归一化坐标。 3. 转换类别标签:labelme标注的类别信息可能是文字形式的,而yolo需要的是数字形式的类别标签。需要将文字形式的类别标签映射成数字形式的类别标签。 4. 生成yolo标注文件:根据yolo标注文件格式,将转换后的图片路径、图片尺寸、归一化坐标和类别标签信息写入到一个文本文件中,作为yolo可识别的数据标注集。 下面是一个示例代码,用于将labelme标注的数据转换成yolo可识别的数据标注集: ```python import json def convert_labelme_to_yolo(labelme_file, yolo_file): with open(labelme_file, 'r') as f: data = json.load(f) image_path = data['imagePath'] image_width = data['imageWidth'] image_height = data['imageHeight'] with open(yolo_file, 'w') as f: for shape in data['shapes']: label = shape['label'] points = shape['points'] x_min = min(points, key=lambda x: x[0])[0] y_min = min(points, key=lambda x: x[1])[1] x_max = max(points, key=lambda x: x[0])[0] y_max = max(points, key=lambda x: x[1])[1] x_center = (x_min + x_max) / 2 / image_width y_center = (y_min + y_max) / 2 / image_height width = (x_max - x_min) / image_width height = (y_max - y_min) / image_height class_id = 0 # 根据需要自行映射类别标签 line = f"{class_id} {x_center} {y_center} {width} {height}\n" f.write(line) convert_labelme_to_yolo('labelme.json', 'yolo.txt') ``` 请将上述代码保存为一个Python脚本,并将`labelme.json`替换为你的labelme标注文件的路径,将`yolo.txt`替换为你想要生成的yolo标注文件的路径。运行脚本后,即可生成yolo可识别的数据标注集。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值