Labelme标注流程

Labelme标注流程,第1张

Labelme标注流程 使用前注意:如果标注前需要对图片尺寸进行修改,务必先修改图片尺寸,再标注
"""
修改图片尺寸的代码
"""
from PIL import Image
import os

Files_path = r"C:UsersddDesktop标注远距离图片"  # C:UsersddDesktop标注远距离图片data  注意图片是放在data文件夹下的!!!
labels_num = len(os.listdir(Files_path))
print(labels_num)

for i in range(labels_num):
    image_dir = os.path.join(Files_path, str(os.listdir(Files_path)[i]))
    print(image_dir)
    image_list = os.listdir(image_dir)

    for image_name in image_list:
        image_path = os.path.join(image_dir, image_name)
        img = Image.open(image_path)
        print(img)

        x_s = 512
        y_s = 512

        Resize_image = img.resize((x_s, y_s), Image.ANTIALIAS)

        Resize_out_path = r"C:UsersddDesktop标注远距离图片"

        Resize_image.save(Resize_out_path + '/' + str(os.listdir(Files_path)[i]) + '/' + str(image_name))
1.按照下图中流程标注:

(下面的图片顶端的路径调整一下,C:UsersddDesktop标注远距离图片left_0.jpg 变为 C:UsersddDesktop标注远距离图片dataleft_0.jpg)




2.处理标注后的json文件 2.1 修改json_to_dataset.py文件的内容:(如果已经替换过则忽略)

参考链接
在D:AnacondaenvslabelmeLibsite-packageslabelmecli 可以看到json_to_dataset.py文件
修改为:

import argparse
import json
import os
import os.path as osp
import warnings
 
import PIL.Image
import yaml
 
from labelme import utils
import base64
 
def main():
    warnings.warn("This script is aimed to demonstrate how to convert then"
                  "JSON file to a single image dataset, and not to handlen"
                  "multiple JSON files to generate a real-use dataset.")
    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    parser.add_argument('-o', '--out', default=None)
    args = parser.parse_args()
 
    json_file = args.json_file
    if args.out is None:
        out_dir = osp.basename(json_file).replace('.', '_')
        out_dir = osp.join(osp.dirname(json_file), out_dir)
    else:
        out_dir = args.out
    if not osp.exists(out_dir):
        os.mkdir(out_dir)
 
    count = os.listdir(json_file) 
    for i in range(0, len(count)):
        path = os.path.join(json_file, count[i])
        if os.path.isfile(path):
            data = json.load(open(path))
            
            if data['imageData']:
                imageData = data['imageData']
            else:
                imagePath = os.path.join(os.path.dirname(path), data['imagePath'])
                with open(imagePath, 'rb') as f:
                    imageData = f.read()
                    imageData = base64.b64encode(imageData).decode('utf-8')
            img = utils.img_b64_to_arr(imageData)
            label_name_to_value = {'_background_': 0}
            for shape in data['shapes']:
                label_name = shape['label']
                if label_name in label_name_to_value:
                    label_value = label_name_to_value[label_name]
                else:
                    label_value = len(label_name_to_value)
                    label_name_to_value[label_name] = label_value
            
            # label_values must be dense
            label_values, label_names = [], []
            for ln, lv in sorted(label_name_to_value.items(), key=lambda x: x[1]):
                label_values.append(lv)
                label_names.append(ln)
            assert label_values == list(range(len(label_values)))
            
            lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)
            
            captions = ['{}: {}'.format(lv, ln)
                for ln, lv in label_name_to_value.items()]
            lbl_viz = utils.draw_label(lbl, img, captions)
            
            out_dir = osp.basename(count[i]).replace('.', '_')
            out_dir = osp.join(osp.dirname(count[i]), out_dir)
            if not osp.exists(out_dir):
                os.mkdir(out_dir)
 
            PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
            #PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
            utils.lblsave(osp.join(out_dir, 'label.png'), lbl)
            PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))
 
            with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
                for lbl_name in label_names:
                    f.write(lbl_name + 'n')
 
            warnings.warn('info.yaml is being replaced by label_names.txt')
            info = dict(label_names=label_names)
            with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
                yaml.safe_dump(info, f, default_flow_style=False)
 
            print('Saved to: %s' % out_dir)
if __name__ == '__main__':
    main()
2.2 处理json文件

命令行输入:

F:>cd F:Anacondascripts
F:Anacondascripts>labelme_json_to_dataset.exe C:UsersddDesktop标注远距离图片标注后文件


3.使用Python批量提取不同json文件夹中的img.png 和 label.png图片:

3.1 如果json文件夹的命名各不相同,为了提取方便,先使用Python批量修改一个文件夹下所有文件夹的名字,这里统一改成了rgb_i_json,其中i从1到n,代码如下:
import os
dirs = os.listdir(r'C:UsersddDesktop标注远距离图片json_to_data')
i = 1
for dir in dirs:
    # 获取每个文件夹
    print(dir)
    # 获取文件夹的名字
    oldName = os.path.join(r'C:UsersddDesktop标注远距离图片json_to_data', dir)
    newName = os.path.join(r'C:UsersddDesktop标注远距离图片json_to_data', 'rgb_'+str(i)+'_json')
    # 执行修改名称的方法.参数1告诉他以前的名字叫啥;参数2告诉他新名字叫啥
    os.rename(oldName, newName)
    i += 1

3.2 然后,分别提取rgb_i_json文件夹中的各个img.png和label.png到两个新的文件夹中,代码如下:
import os
import shutil

path = input('_json文件夹所在的路径:')
new_path = input('需保存的路径:')
count = os.listdir(path)
for j in range(1, len(count) + 1):
    for root, dirs, files in os.walk(path):
        if len(dirs) == 0:
            for i in range(len(files)):
                print("i=", i)
                # 样例:
                # if files[i].find('label.png') != -1:
                #     shutil.copy(os.path.join(path + '/rgb_' + str(j).zfill(4) + '_json/', files[i]),
                #                 os.path.join(new_path, 'rgb_' + str(j).zfill(4) + '.png'))

                # 将label.png提取出来并且按照顺序命名1.png....
                if files[i].find('label.png') != -1:
                    shutil.copy(os.path.join(path + '/rgb_' + str(j).zfill(1) + '_json/', files[i]),
                                os.path.join(new_path, str(j).zfill(1) + '.png'))

                # 将img.png提取出来并且按照顺序命名1.png.....
                # if files[i].find('img.png') != -1:
                #     shutil.copy(os.path.join(path + '/rgb_' + str(j).zfill(1) + '_json/', files[i]),
                #                 os.path.join(new_path, str(j).zfill(1) + '.png'))

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5689960.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存