查看第0层权重:
weights = model.get_weights()[0]
将包含训练、测试、验证集的图像文件夹CamVid放在当前目录下,导入图像数据代码如下:
import util
import numpy as np
import os
DataPath='/CamVid/'
def load_data(mode):
data=[]
label=[]
with open(os.getcwd()+DataPath+mode+'.txt') as f:
txt=f.readlines()
txt=[line.split(' ') for line in txt]
for i in range(len(txt)):
img_data,img_h,img_w=util.get_preprocessed_image(os.getcwd()+txt[i][0])
data.append(img_data)
img_label,y_h,y_w=util.get_preprocessed_label(os.getcwd()+txt[i][1][:-1])
label.append(img_label)
return np.array(data),np.array(label)
其中训练样本保存在文件夹train中,其ground truth保存在trainannot文件夹中,ground truth是一通道图像,每个像素是类别索引(0~11)。保存训练图像和ground truth路径和名字的文本为train.txt,内容格式为:
/CamVid/train/0001TP_006690.png /CamVid/trainannot/0001TP_006690.png
如果导入的是训练集,则
train_data, train_label = load_data("train")
np.save("data/train_data.npy", train_data)
util如下:
import numpy as np
from PIL import Image
from keras.applications.vgg16 import preprocess_input
def one_hot_it(labels,h,w):
x=np.zeros([h,w,12])
for i in range(h):
for j in range(w):
x[i,j,int(labels[i][j])]=1
return x
def get_preprocessed_label(file_name): #from 1-channel index map to 1-channel binary index map
im=np.array(Image.open(file_name))
img_h,img_w=im.shape
im=one_hot_it(im,img_h,img_w)
if img_h>500 or img_w>500:
raise ValueError("Please resize your images to be not bigger than 500 x 500")
pad_h=500-img_h
pad_w=500-img_w
im=np.pad(im,pad_width=((0,pad_h),(0,pad_w),(0,0)),mode='constant',constant_values=0)
return im.reshape(500,500,12),img_h,img_w
def get_preprocessed_image(file_name):
#Note: channels last
im=np.array(Image.open(file_name)).a