origin:
后来增加了draw.py 在同一个文件夹中 参考3.9博客
import glob
import json
import os
import os.path as osp
import numpy as np
import PIL.Image
import labelme
import sys
input_dir = './cat_test/' # 里面是含有json文件所处的文件夹
output_dir = 'data_dataset_voc' #output_dir 不能是一个已经存在的文件夹,要起一个新名字,让系统自己创建
labels = './cat_test/label.txt'
if osp.exists(output_dir):
print('Output directory already exists:',output_dir)
sys.exit(1)
os.makedirs(output_dir) # 生成output_dir = 'data_dataset_voc' 文件,且与
# Python 文件处于同一文件夹下即 f:/dataset3/labelme_practice_cat_test/
print(osp.join(output_dir,'JPEGImages'))
输出
data_dataset_voc\JPEGImages # 这里的斜杠与我前面./不同也,
不知道后面可不可以生成文件夹
origin
os.makedirs(osp.join(output_dir, 'JPEGImages'))
os.makedirs(osp.join(output_dir,'SegmentationClass'))
os.makedirs(osp.join(output_dir,'SegmentationClassPNG'))
os.makedirs(osp.join(output_dir,'SegmentationClassVisualization'))
os.makedirs(osp.join(output_dir,'SegmentationObject'))
os.makedirs(osp.join(output_dir,'SegmentationObjectPNG'))
os.makedirs(osp.join(output_dir,'SegmentationObjectVisualization'))
then 输出
class_names = [] # 用来储藏类别
class_name_to_id = {} # 利用字典来储藏id 以及相对应的 class_name
for i , line in enumerate(open(labels).readlines()):
class_id = i - 1 # 我希望 __ignore__对应的是-1,开始,因为我希望类别从0---background 开始数起
class_name = line.strip() # 获取类别名称
class_name_to_id[class_name] = class_id
if class_id == -1: # 下面的代码是用来检错的 看-1是否与__ignore__对应, 0是否与__background__对应
assert class_name == '__ignore__'
continue # 用来阻止 __ignore__ 写入class_names 列表中
elif class_id == 0:
assert class_name == '__background__'
class_names.append(class_name)
输出
class_names = tuple(class_names)
class_names
输出
('__background__', 'cat')
out_class_names_file = osp.join(output_dir, 'class_names.txt') # 创建一个文件用来保存类名
##out_class_names_file 为'data_dataset_voc\\class_names.txt'
with open(out_class_names_file,'w') as f:
f.writelines('\n'.join(class_names))
输出
import draw
colormap = draw.label_colormap()
==About json.load()==
Help on function load in module json:
load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``object_pairs_hook`` is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs. The
return value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders. If ``object_hook``
is also defined, the ``object_pairs_hook`` takes priority.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg; otherwise ``JSONDecoder`` is used.
PIL.Image.fromarray(obj, mode=None)
Creates an image memory from an object exporting the array interface
(using the buffer protocol).
If **obj** is not contiguous, then the tobytes method is called
and :py:func:`~PIL.Image.frombuffer` is used.
------------------------------------------
| If you have an image in NumPy::
from PIL import Image
import numpy as np
im = Image.open('hopper.jpg')
a = np.asarray(im)
Then this can be used to convert it to a Pillow image::
im = Image.fromarray(a)
------------------------------------------------------
:param obj: Object with array interface
:param mode: Mode to use (will be determined from type if None)
See: :ref:`concept-modes`.
:returns: An image object.
| ImageObject.save(self, fp, format=None, **params)
| Saves this image under the given filename. If no format is
| specified, the format to use is determined from the filename
| extension, if possible.
|
| Keyword options can be used to provide additional instructions
| to the writer. If a writer doesn't recognise an option, it is
| silently ignored. The available options are described in the
| :doc:`image format documentation
| <../handbook/image-file-formats>` for each writer.
|
| You can use a file object instead of a filename. In this case,
| you must always specify the format. The file object must
| implement the ``seek``, ``tell``, and ``write``
| methods, and be opened in binary mode.
|
| :param fp: A filename (string), pathlib.Path object or file object.
| :param format: Optional format override. If omitted, the
| format to use is determined from the filename extension.
| If a file object was used instead of a filename, this
| parameter should always be used.
| :param params: Extra parameters to the image writer.
| :returns: None
| :exception ValueError: If the output format could not be determined
| from the file name. Use the format option to solve this.
| :exception IOError: If the file could not be written.
----------- The file
| --------- may have been created, and may contain partial data
for label_file in glob.glob(osp.join(input_dir,'10.json')): # 原本join 的时候:./cat_test/10.json
label_file = label_file.replace('\\','/')
print('Generating dataset from:',label_file) # ./cat_test/10.json
with open(label_file) as f:
base = osp.splitext(osp.basename(label_file))[0]# 这里就只有文件名,连文件格式都没有了:10
#创建文件每个图片的名称
out_img_file = osp.join(output_dir,'JPEGImages', base+'.jpg') # data_dataset_voc\JPEGImages\10.jpg
out_cls_file = osp.join(output_dir,'SegmentationClass', base+'.npy')
out_clsp_file = osp.join(output_dir,'SegmentationClassPNG', base+'.png')
out_clsv_file = osp.join(output_dir,'SegmentationClassVisualization', base+'.jpg',)
out_ins_file = osp.join(output_dir,'SegmentationObject', base+'.npy')
out_insp_file = osp.join(output_dir,'SegmentationObjectPNG', base+'.png')
out_insv_file = osp.join(output_dir,'SegmentationObjectVisualization', base+'.jpg',)
# 载入数据Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
#a JSON document) to a Python object.
data = json.load(f) # data 是一个字典型数据,里面的内容与json里面的内容一致
img_file = osp.join(osp.dirname(label_file),data['imagePath']) #生成一个路径
#label_file = './cat_test/10.json' --dirname--- './cat_test'----join ---'./cat_test\10.jpg'
img = np.asarray(PIL.Image.open(img_file)) #Convert the input to an array.
PIL.Image.fromarray(img).save(out_img_file)# 在out_img_file 生成10.jpg
# [np.ndarray]---fromarray----[PIL.Image object] ----save----[return none]Saves this image under the given filename
#生成标签
cls, ins = labelme.utils.shapes_to_label(
img_shape = img.shape,
shapes = data['shapes'],
label_name_to_value = class_name_to_id,
type = 'instance',) # 通过np.unique(cls)--0,1 np.unique(ins) --0,1
ins[cls == -1] =0 # 是之前ignore 在ins内也为 background 的0
# class label
labelme.utils.lblsave(out_clsp_file,cls)#lblsave(filename, lbl) # 这一个在out_clsp_file文件夹中生成10.png
np.save(out_cls_file,cls) # 在out_cls_file 文件夹中,生成10.npy
# clsv = labelme.utils.draw_label(
# label =cls,img =img, label_names=class_names,colormap = colormap)
# label矩阵,img矩阵,class_names = ('__background__', 'cat') ,colormap = imgviz.label_colormap()
clsv = draw.draw_label(label =cls, img=img, label_names=class_names, colormap = colormap)
PIL.Image.fromarray(clsv).save(out_clsv_file) # 在out_clsv_file 中生成10.jpg (带colormap)有 图注1
# instance label
labelme.utils.lblsave(out_insp_file,ins)
np.save(out_ins_file,ins)
instance_ids = np.unique(ins)
instance_names = [str(i) for i in range(max(instance_ids)+1)]
insv = draw.draw_label(label=ins, img=img, label_names = instance_names)
PIL.Image.fromarray(insv).save(out_insv_file) # 也是有图注的 0 1
输出