一緒に書く習慣を身につけましょう!「ナゲッツデイリーニュープラン・4月アップデートチャレンジ」に参加して7日目です。クリックしてイベントの詳細をご覧ください。
欢迎关注我的公众号 [极智视界],获取我的更多笔记分享
みなさん、こんにちは。私の名前はジジビジョンです。このペーパーでは、labelmeがセグメント化されたデータにラベルを付けて処理する方法を詳しく紹介します。
画像セグメンテーションは、インスタンスセグメンテーション、セマンティックセグメンテーション、パノラマセグメンテーションなどを含むコンピュータビジョンタスクの一般的なタスクです。セグメンテーションタスクに送信する前に、データにラベルを付ける必要があります。ご存知のとおり、深層学習におけるデータの品質は、最終的な検出効果に大きな影響を与えるため、データのラベル付けの重要性は自明です。
以下から始めてください。
1.labelmeをインストールします
WindowsでもLinuxでも、次のようにインストールできます。
# 首先安装anaconda,这个这里不多说
# 安装pyqt5
pip install -i https://pypi.douban.com/simple pyqt5
# 安装labelme
pip install -i https://pypi.douban.com/simple labelme
# 打开labelme
./labelme
复制代码
次に、画像に対応するjsonファイルが生成されます。このファイルには、ラベルとラベル付きセグメンテーションマスク情報が含まれています。これはほぼ次のようになります。
2.組み込みのjsonからdatset
2.1単一画像のjsonからデータセットへ
直接実行:
labelme_json_dataset xxx.json
复制代码
次に、以下を生成します。
-
img.png:元の画像;
-
label.png:マスク画像;
-
label_viz.png:画像を背景でマスクします。
-
info.yaml、label_names.txt:ラベル情報;
2.2jsonをデータセットにバッチ処理する
cli / json_to_dataset.pyディレクトリを見つけて、次のようにします。
cd cli
touch json_to_datasetP.py
vim json_to_datasetP.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 the\n"
"JSON file to a single image dataset, and not to handle\n"
"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()
复制代码
次に、バッチで変換を行います。
python path/cli/json_to_datasetP.py path/JPEGImages
复制代码
エラーが報告された場合:
lbl_viz = utils.draw_label(lbl, img, captions)
AttributeError: module 'labelme.utils' has no attribute 'draw_label'
复制代码
解決策:labelmeバージョンを変更する必要があり、labelmeバージョンを3.16.2に減らす必要があります。メソッドはlabelme環境に入り、と入力してこのバージョンを自動的にpip install labelme==3.16.2
ダウンロードでき、成功することができます。
3.別のスプリットラベル制作
このようなタグを生成する場合:
元の画像:
対応するラベル(背景は0、円は1):
このタグは8ビットのシングルチャンネル画像であり、このメソッドは最大256種類をサポートします。
データセットは、次のスクリプトで作成できます。
import cv2
import numpy as np
import json
import os
# 0 1 2 3
# backg Dog Cat Fish
category_types = ["Background", "Dog", "Cat", "Fish"]
# 获取原始图像尺寸
img = cv2.imread("image.bmp")
h, w = img.shape[:2]
for root,dirs,files in os.walk("data/Annotations"):
for file in files:
mask = np.zeros([h, w, 1], np.uint8) # 创建一个大小和原图相同的空白图像
print(file[:-5])
jsonPath = "data/Annotations/"
with open(jsonPath + file, "r") as f:
label = json.load(f)
shapes = label["shapes"]
for shape in shapes:
category = shape["label"]
points = shape["points"]
# 填充
points_array = np.array(points, dtype=np.int32)
mask = cv2.fillPoly(mask, [points_array], category_types.index(category))
imgPath = "data/masks/"
cv2.imwrite(imgPath + file[:-5] + ".png", mask)
复制代码
上記は4つのカテゴリーの場合です。
これで完了です。上記は、ラベルのラベル付けとセグメンテーションデータの処理の方法を共有しています。私の共有があなたの学習に役立つことを願っています。
【公開番号送信】