一、Labelme安装
1.在anaconda中新建环境,命名为labelme。
conda create -n labelme python=3.6
2.进入labelme环境,安装labelme包。
conda activate labelme
conda install -c conda-forge pyside2
conda install pyqt
pip install labelme
二、绘制标签图
1.命令行输入labelme,等待软件启动,界面如下:
2.打开原图对应文件夹,开始标注。点击CreatePolygons,依次点击待分割物体边缘进行标注。弹出给定标签窗口,输入标签保存。之后点击save保存json文件。点击NextImage进行下一张图片的分割标注。
- 如果关闭软件之后下次标注想跳转到最近标注的文件,点选左上角File -> Open Recent选择最近标注的图片进行跳转。
- 如果标注物体很细小,可以按住ctrl滚动滚轮放大缩小图片。标注中退回到上一个点可以鼠标右键Undo last point。
- 点击EditPolygons可以对标注的点进行位置移动修改。
三、单张图片格式转换
1. cd到json文件存放的目录,输入命令 labelme_json_to_dataset <文件名>.json,在目录下就会生成一个新的文件。
得到结果:
四、批量图片格式转换
参考:深度学习数据预处理_python批量转换labelme标注的json格式标签为png格式 - 知乎
1.批量执行labelme_json_to_dataset步骤,生成多个包含PNG格式标记图的文件夹。
批量生成需要在python里调用cmd,使用os.system()调用。
这里的json_folder是放多个json文件的文件夹。在json文件同目录下生成dataset文件夹。
# -*- coding:utf8 -*-
import os
json_folder = r"C:\\Users\\Administrator\\Desktop\\example"
# 获取文件夹内的文件名
FileNameList = os.listdir(json_folder)
# 激活labelme环境
os.system("activate labelme")
for i in range(len(FileNameList)):
# 判断当前文件是否为json文件
if(os.path.splitext(FileNameList[i])[1] == ".json"):
json_file = json_folder + "\\" + FileNameList[i]
# 将该json文件转为png
os.system("labelme_json_to_dataset " + json_file)
2.批量从文件夹中得到PNG格式的标记图。这里的Paste_label_folder是放置PNG格式标记图的文件夹。
import os
import shutil
json_folder = r"C:\\Users\\Administrator\\Desktop\\example"
Paste_label_folder = r"C:\\Users\\Administrator\\Desktop\\label"
# 获取文件夹内的文件名
FileNameList = os.listdir(json_folder)
NewFileName = 1
for i in range(len(FileNameList)):
# 判断当前文件是否为json文件
if (os.path.splitext(FileNameList[i])[1] == ".json"):
# 复制label文件
jpg_file_name = FileNameList[i].split(".", 1)[0]
label_file = json_folder + "\\" + jpg_file_name + "_json\\label.png"
new_label_file = Paste_label_folder + "\\" + str(jpg_file_name) + ".png"
shutil.copyfile(label_file, new_label_file)
# 文件序列名+1
NewFileName = NewFileName + 1
3.如果看着黑底红路难受,想改成常见的黑底白路,可以采用如下代码。这里的pic_folder和root是放黑底红路标记图的文件夹,target是生成黑底白路标记图的文件夹。
#encoding:utf-8
import os
from PIL import Image
pic_folder = r"C:\\Users\\Administrator\\Desktop\\label"
# 获取文件夹内的文件名
FileNameList = os.listdir(pic_folder)
print(FileNameList)
for i in range(len(FileNameList)):
root = r"C:\\Users\\Administrator\\Desktop\\label\\"
target = r"C:\\Users\\Administrator\\Desktop\\label2\\"
img = Image.open(os.path.join(root + FileNameList[i]))
# 模式L”为灰色图像,它的每个像素用8个bit表示,0表示黑,255表示白,其他数字表示不同的灰度。
Img = img.convert('L')
# 自定义灰度界限
threshold = 0
table = []
for j in range(256):
if j <= threshold:
table.append(0)
else:
table.append(1)
photo = Img.point(table, '1')
photo.save(os.path.join(target + FileNameList[i]))
print("Finish!")
得到如下结果: