运行环境:windows10 + Tensorflow 1.6.0 + Python 3.6.4(笔记本无GPU)
参考文章:https://blog.csdn.net/qq_32799915/article/details/80070711(图像语义分割 DeepLab v3+ 训练自己的数据集)
运行DeeplabV3+,数据集为VOC2012,整个过程参考上文,在运行eval.py时报错,报错的页面如下:Predictions out of bound,刚开始以为是dataset.ignore_label = 255,导致Predictions里出现255,而VOC总共类别数为21(包括背景),从而报错,然而修改ignore_label的值也仍然报错。
曾一度以为可能是版本问题,但仔细查看报错信息,否决了自己的这个想法。
最终不断尝试后发现:是Label数据存在问题。
DeeplabV3+的数据集应包括2个部分,images和labels,image为[n*m*3],jpg格式,label为[n*m*1],png格式。而VOC2012 SegmentationClass中的label数据格式为[n*m*3],只需将label数据从RGB的3通道转为’L'的单通道即可,代码如下:
import numpy as np
from PIL import Image
from keras.preprocessing.image import load_img, img_to_array
import os
classes = ['background', 'aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'dining table',
'dog', 'horse', 'motorbike', 'person', 'potted plant',
'sheep', 'sofa', 'train', 'tv/monitor']
colormap = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128],
[128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0],
[64, 128, 0], [192, 128, 0], [64, 0, 128], [192, 0, 128],
[64, 128, 128], [192, 128, 128], [0, 64, 0], [128, 64, 0],
[0, 192, 0], [128, 192, 0], [0, 64, 128]]
# 利用下面的代码,将标注的图片转换为单通道的label图像
cm2lbl = np.zeros(256**3)
for i, cm in enumerate(colormap):
cm2lbl[(cm[0]*256+cm[1])*256+cm[2]] = i
def image2label(im):
# 输入为标记图像的矩阵,输出为单通道映射的label图像
data = im.astype('int32')
idx = (data[:, :, 0]*256+data[:, :, 1])*256+data[:, :, 2]
return np.array(cm2lbl[idx])
def change_label(label_url, label_name):
label_img = load_img(label_url)
label_img = img_to_array(label_img)
label_img = image2label(label_img) # 将图片映射为单通道数据
print(np.max(label_img))
label_single = Image.fromarray(label_img)
label_single = label_single.convert('L')
save_path = './datasets/VOC2012/Label'
save_path = os.path.join(save_path, label_name) # 确定保存路径及名称
label_single.save(save_path)
val_file_path = './datasets/VOC2012/ImageSets/trainval.txt' # 文件名存放路径
label_file_path = './datasets/VOC2012/SegmentationClass' # 原label存放路径
with open(val_file_path, 'r') as f:
file_names = f.readlines()
count = 0
for name in file_names:
count += 1
name = name.strip('\n') # 去掉换行符
label_name = name + '.png' # label文件名
label_url = os.path.join(label_file_path, label_name)
print('这是第 %s 张' % count)
print(label_url)
change_label(label_url, label_name)
Label转换前后的效果如下:
转换后程序运行无异常,部分提示信息如下:
程序运行成功,输出为MIOU值,由于使用单个样本仅训练了30步,所以结果较差。