labelme标准数据并抠图

2022/8/8 6:22:51

本文主要是介绍labelme标准数据并抠图,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

import json
import numpy as np
from labelme import utils
import cv2
import os
 
def create_file(file):
 
    if not os.path.exists(file):
        os.mkdir(file)
 
def cv_show(name,img):
 
    cv2.imshow(name,img)
    cv2.waitKey()
    cv2.destroyAllWindows()
 
def from_mask_extract_ROI(img,mask):
 
    y = np.where(mask==1)[0]
    x = np.where(mask==1)[1]
    lu_y = min(y)
    ld_y = max(y)
    ru_x = min(x)
    rd_x = max(x)
    mask_ROI = mask[lu_y:ld_y+1,ru_x:rd_x+1]
    ROI = img[lu_y:ld_y+1,ru_x:rd_x+1]
    mask = np.ones_like(ROI)
    for i in range(mask.shape[2]):
        mask[:,:,i] = mask_ROI
    masked_ROI = mask*ROI
    channel_reverse = np.ones_like(masked_ROI)
    for i in range(channel_reverse.shape[2]):
        channel_reverse[:,:,-1-i] = masked_ROI[:,:,i]
    return channel_reverse
 
def from_json_extract_ROI_based_label(file):
    file_list = os.listdir(file)
 
    json_file = []
    for idx, value in enumerate(file_list):
        if value.split('.')[-1] == 'json':
            json_name = os.path.join(file, value)
            json_file.append(json_name)
    for idx, value in enumerate(json_file):
        json_name = value
        data = json.load(open(json_name))
        img = utils.img_b64_to_arr(data['imageData'])
        lbl, lbl_name = utils.labelme_shapes_to_label(img.shape, data['shapes'])
 
        mask = []
        for i in range(1, len(lbl_name)):
            mask.append((lbl == i).astype(np.uint8))
        mask = np.transpose(np.asarray(mask, np.uint8), [1, 2, 0])
 
        keys = []
        values = []
        for value, key in enumerate(lbl_name):
            key = key.split('.')[0]
            keys.append(key)
            values.append(value)
        labels = []
        for i in range(1, len(values)):
            labels.append(keys[i])
 
        for i in range(mask.shape[2]):
            a = mask[:, :, i]
            masked_ROI_ChannelRevrse = from_mask_extract_ROI(img=img,mask=a)
            save_file = str(labels[i])
            create_file(save_file)
            save_ROI = './' + save_file + '/' + json_name.split('/')[-1].split('.json')[0] + '.' + str(i) + '.jpg'
            cv2.imwrite(save_ROI, masked_ROI_ChannelRevrse)
 
from_json_extract_ROI_based_label(file='./test/')



这篇关于labelme标准数据并抠图的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程