需要将json文件中的imagePath中的信息修改为图片文件名:
xx//xx.jpg -> xx.jpg
imgData中包含了加密后的图像信息 不可随意更改
jsonRenameImagePath.py
参考
import json
import os, sys
json_path = 'data/labels' # // 修改1 json文件存放路径 data放到项目根目录下
def get_json_data(json_path):
with open(json_path, 'rb')as f:
params = json.load(f)
# 加载json文件中的内容给params
a = filename[:-5]
params['imagePath'] = a + ".jpg" # 这两行控制修改的内容 时间有限写的很草率
dict = params
# 将修改后的内容保存在dict中
f.close()
# 关闭json读模式
return dict
# 返回dict字典内容
def write_json_data(dict):
# 写入json文件
with open(json_path1, 'w')as r:
# 定义为写模式,名称定义为r
json.dump(dict, r, indent=2) # indent控制间隔
# 将dict写入名称为r的文件中
r.close()
# 关闭json写模式
# 获取文件夹中的文件名称列表
filenames = os.listdir(json_path)
# 遍历文件名
for filename in filenames:
filepath = json_path + '/' + filename
print(filepath)
dict = {}
the_revised_dict = get_json_data(filepath)
json_path1 = 'data/labels/' + filename # // 修改2 修改后的json文件保存路径 # 修改json文件后保存的路径
write_json_data(the_revised_dict)
json2mask.py
参考 https://blog.csdn.net/szumaine/article/details/104408382
import argparse
import base64
import json
import os
import os.path as osp
import imgviz
import PIL.Image
import yaml
from labelme.logger import logger
from labelme import utils
import cv2
from math import *
import numpy as np
import random
def main():
list_path = os.listdir('data/json/')
for i in range(0, len(list_path)):
logger.warning('This script is aimed to demonstrate how to convert the'
'JSON file to a single image dataset, and not to handle'
'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 = 'data/json/' + list_path[i]
print(list_path[i])
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) # 用于以数字权限模式创建目录
data = json.load(open(json_file))
imageData = data.get('imageData')
if not imageData:
imagePath = os.path.join(os.path.dirname(json_file), data['imagePath']) # os.path.dirname返回文件路径
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 sorted(data['shapes'], key=lambda x: x['label']):
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
lbl, _ = utils.shapes_to_label(
img.shape, data['shapes'], label_name_to_value
)
label_names = [None] * (max(label_name_to_value.values()) + 1)
for name, value in label_name_to_value.items():
label_names[value] = name
lbl_viz = imgviz.label2rgb(
label=lbl, image=imgviz.asgray(img), label_names=label_names, loc='rb'
)
PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.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')
logger.info('Saved to: {}'.format(out_dir))
x = out_dir+'\\label.png'
#######
# 增加了yaml生成部分
logger.warning('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)
logger.info('Saved to: {}'.format(out_dir))
if __name__ == '__main__':
main()
if __name__ == '__main__':
main()
img.png: 原图
label.png:mask
label_names.txt: 类别名称
info.yaml yolo所需的配置文件
参考:maskrcnn数据集制作
# 把label.png改名为原图名.png
import os
for root, dirs, names in os.walk("data/jsonDir"): # 改成你自己的json文件夹所在的目录
for dr in dirs:
file_dir = os.path.join(root, dr)
print(dr)
file = os.path.join(file_dir, 'label.png')
print(file)
new_name = dr.split('_')[0] + '.png'
new_file_name = os.path.join(file_dir, new_name)
os.rename(file, new_file_name)
import os
from shutil import copyfile
for root, dirs, names in os.walk("data/jsonDir"): # 改成你自己的json文件夹所在的目录
for dr in dirs:
file_dir = os.path.join(root, dr)
print(dr)
file = os.path.join(file_dir, dr + '.png')
print(file)
new_name = dr.split('_')[0] + '.png'
new_file_name = os.path.join(file_dir, new_name)
print(new_file_name)
tar_root = 'data/cv2_mask' # 目标路径
tar_file = os.path.join(tar_root, new_name)
copyfile(new_file_name, tar_file)
参考 好像是b站up主bubbliiing的项目里的文件
import collections
import datetime
import glob
import json
import os
import os.path as osp
import labelme
import numpy as np
import PIL.Image
import pycocotools.mask
from utils.utils import get_classes
'''
标注自己的数据集需要注意以下几点:
1、我使用的labelme版本是3.16.7,建议使用该版本的labelme,
2、标注的数据集存放在datasets/before里面。
jpg结尾的为图片文件
json结尾的为标签文件
图片文件和标签文件相对应
3、在标注目标时需要注意,同一种类的不同目标需要使用 _ 来隔开。
比如想要训练网络检测三角形和正方形,当一幅图片存在两个三角形时,一个标记为:
triangle_1
另一个为:
triangle_2
代码同时兼容了MASK RCNN视频中提到的数据标注方式(不能让各位白标注了对吧)
标记为triangle1、triangle2也可以正常训练
'''
if __name__ == '__main__':
#------------------------------------#
# 训练自己的数据集必须要修改
# 所需要区分的类别对应的txt文件
#------------------------------------#
classes_path = "class_names.txt"
#------------------------------------#
# labelme标注数据保存的位置
#------------------------------------#
input_dir = "data/jpgForJson/"
#------------------------------------#
# 输出的图片文件保存的位置
#------------------------------------#
Img_output_dir = "data/jsonDivide/"
#------------------------------------#
# 输出的json文件保存的位置
#------------------------------------#
Json_output_dir = "data/jsonDivide/"
#--------------------------------------------------------------------------------------------------------------------------------#
# trainval_percent用于指定(训练集+验证集)与测试集的比例,默认情况下 (训练集+验证集):测试集 = 9:1
# train_percent用于指定(训练集+验证集)中训练集与验证集的比例,默认情况下 训练集:验证集 = 9:1
#--------------------------------------------------------------------------------------------------------------------------------#
trainval_percent = 0.9
train_percent = 0.9
#------------------------------------#
# 创建文件夹
#------------------------------------#
if not osp.exists(Img_output_dir):
os.makedirs(Img_output_dir)
if not osp.exists(Json_output_dir):
os.makedirs(Json_output_dir)
#------------------------------------#
# 获取当前时间
#------------------------------------#
now = datetime.datetime.now()
#------------------------------------#
# 找到所有标注好的json文件
#------------------------------------#
label_files = glob.glob(osp.join(input_dir, '*.json'))
#------------------------------------#
# 对数据集进行打乱,并进行训练集、
# 验证集和测试集的划分。
#------------------------------------#
np.random.seed(10101)
np.random.shuffle(label_files)
np.random.seed(None)
num_train_val = int(trainval_percent * len(label_files))
num_train = int(train_percent * num_train_val)
train_label_files = label_files[: num_train]
val_label_files = label_files[num_train : num_train_val]
test_label_files = label_files[num_train_val :]
#------------------------------------#
# 设定输出json文件的名称
#------------------------------------#
train_out_ann_file = osp.join(Json_output_dir, 'train_annotations.json')
val_out_ann_file = osp.join(Json_output_dir, 'val_annotations.json')
test_out_ann_file = osp.join(Json_output_dir, 'test_annotations.json')
#------------------------------------#
# 获得列表
#------------------------------------#
label_files_list = [train_label_files, val_label_files, test_label_files]
out_ann_files_list = [train_out_ann_file, val_out_ann_file, test_out_ann_file]
data_list = [
dict(
#------------------------------------#
# 基础信息
#------------------------------------#
info = dict(
description = None,
url = None,
version = None,
year = now.year,
contributor = None,
date_created = now.strftime('%Y-%m-%d %H:%M:%S.%f'),
),
#------------------------------------#
# 许可证信息
#------------------------------------#
licenses=[
dict(
url = None,
id = 0,
name = None,
)
],
#------------------------------------#
# images是图片信息
#------------------------------------#
images=[
# license, url, file_name, height, width, date_captured, id
],
#------------------------------------#
# instances是实例
#------------------------------------#
type='instances',
#------------------------------------#
# 标签信息
#------------------------------------#
annotations=[
# segmentation, area, iscrowd, image_id, bbox, category_id, id
],
#------------------------------------#
# 放的是需要区分的种类
#------------------------------------#
categories=[
# supercategory, id, name
],
) for _ in range(3)
]
#------------------------------------#
# 该部分增加categories信息
#------------------------------------#
class_names, _ = get_classes(classes_path)
class_names = ["__ignore__", "_background_"] + class_names
class_name_to_id = {}
for i, line in enumerate(class_names):
class_id = i - 1
class_name = line.strip()
if class_id == -1:
assert class_name == '__ignore__'
continue
class_name_to_id[class_name] = class_id
for data in data_list:
data['categories'].append(
dict(
supercategory = None,
id = class_id,
name = class_name,
)
)
for label_files_index, label_files in enumerate(label_files_list):
#------------------------------------#
# 读取before文件夹里面的json文件
#------------------------------------#
for image_id, label_file in enumerate(label_files):
print('Generating dataset from:', label_file)
with open(label_file) as f:
label_data = json.load(f)
#------------------------------------#
# 该部分增加images信息
# 首先获取其对应的JPG图片
# 然后保存到指定文件夹
# 之后写入json数据
#------------------------------------#
base = osp.splitext(osp.basename(label_file))[0]
out_img_file = osp.join(Img_output_dir, base + '.jpg')
img_file = osp.join(osp.dirname(label_file), base + '.jpg')
img = PIL.Image.open(img_file)
img.save(out_img_file)
img = np.asarray(img)
data_list[label_files_index]['images'].append(
dict(
license = 0,
url = None,
file_name = base + '.jpg',
height = img.shape[0],
width = img.shape[1],
date_captured = None,
id = image_id,
)
)
masks = {}
segmentations = collections.defaultdict(list)
for shape in label_data['shapes']:
points = shape['points']
label = shape['label']
shape_type = shape.get('shape_type', None)
mask = labelme.utils.shape_to_mask(img.shape[:2], points, shape_type)
if label in masks:
masks[label] = masks[label] | mask
else:
masks[label] = mask
points = np.asarray(points).flatten().tolist()
segmentations[label].append(points)
for label, mask in masks.items():
if '_' in label:
#------------------------------------#
# 利用-进行分割
#------------------------------------#
cls_name = label.split('_')[0]
if cls_name not in class_name_to_id:
continue
else:
import re
cls_name = re.split('\d+$', label)[0]
if cls_name not in class_name_to_id:
continue
cls_id = class_name_to_id[cls_name]
#------------------------------------#
# 获得mask,area和bbox坐标
#------------------------------------#
mask = np.asfortranarray(mask.astype(np.uint8))
mask = pycocotools.mask.encode(mask)
area = float(pycocotools.mask.area(mask))
bbox = pycocotools.mask.toBbox(mask).flatten().tolist()
#------------------------------------#
# 该部分增加annotations信息
#------------------------------------#
data_list[label_files_index]['annotations'].append(dict(
id = len(data_list[label_files_index]['annotations']),
image_id = image_id,
category_id = cls_id,
segmentation = segmentations[label],
area = area,
bbox = bbox,
iscrowd = 0,
))
with open(out_ann_files_list[label_files_index], 'w') as f:
json.dump(
data_list[label_files_index],
f,
indent = 4,
ensure_ascii = False
)
补充:utils.util.py
import numpy as np
from PIL import Image
#---------------------------------------------------------#
# 将图像转换成RGB图像,防止灰度图在预测时报错。
# 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB
#---------------------------------------------------------#
def cvtColor(image):
if len(np.shape(image)) == 3 and np.shape(image)[2] == 3:
return image
else:
image = image.convert('RGB')
return image
#---------------------------------------------------#
# 对输入图像进行resize
#---------------------------------------------------#
def resize_image(image, size, letterbox_image):
iw, ih = image.size
w, h = size
if letterbox_image:
scale = min(w/iw, h/ih)
nw = int(iw*scale)
nh = int(ih*scale)
image = image.resize((nw,nh), Image.BICUBIC)
new_image = Image.new('RGB', size, (128,128,128))
new_image.paste(image, ((w-nw)//2, (h-nh)//2))
else:
new_image = image.resize((w, h), Image.BICUBIC)
return new_image
#---------------------------------------------------#
# 获得类
#---------------------------------------------------#
def get_classes(classes_path):
with open(classes_path, encoding='utf-8') as f:
class_names = f.readlines()
class_names = [c.strip() for c in class_names]
return class_names, len(class_names)
def preprocess_input(image):
image /= 255.0
image -= np.array([0.485, 0.456, 0.406])
image /= np.array([0.229, 0.224, 0.225])
return image
#---------------------------------------------------#
# 获得学习率
#---------------------------------------------------#
def get_lr(optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
import json
import os
import shutil
# 将json文件中的jpg划分到相应的文件夹中
jpg_ppath = "data/jsonDivide/jpg/"
new_path = 'data/jsonDivide/test/'
jpg_path = os.listdir(jpg_ppath) # 要划分的jpg文件夹
# print(type(jpg_path)) # 文件夹中的文件 类型 为 list
with open('./data/jsonDivide/test_annotations.json', 'r', encoding='utf-8') as fp: # 要处理的json文件
json_data = json.load(fp) # 读取json文件
# print(type(json_data)) # json文件中的数据类型为 dict
A = json_data.keys() # 查看
# print(A) # dict_keys(['info', 'licenses', 'images', 'type', 'annotations', 'categories'])
# print(type(A)) #
images = json_data.get('images') # images这个元素的形式是list
# print(type(images)) #
# print(images)
json_file_name_list = [] # 初始化存储 json中 文件名的列表
for i in range(len(images)):
image = images[i].get("file_name")
# file_names = images[0].get('file_name')
# print(file_names)
json_file_name_list.append(image) # 将每一个jpg的名字添加到file_name_list列表中
# print(image)# 得到了该json文件中的每一个file_name
print(json_file_name_list) #json文件中的jpg
file_list = jpg_path # 文件夹中的jpg文件
# print(file_list)
for file_name in file_list:
for json_file_name in json_file_name_list:
if file_name == json_file_name:
file_name = jpg_ppath + file_name
print(file_name)
shutil.move(file_name, new_path)
# # print("json_file_name" + json_file_name)
# # print("file_name" + file_name)
# if json_file_name == name:
# name = jpg_path + name
# print(name)
# # shutil.move(name, new_path)