import tensorflow as tf
from PIL import Image
import os
import numpy as np
from sklearn.model_selection import train_test_split
# os.environ['CUDA_VISIBLE_DEVICES'] = '1'
# 读取所有图片 统一尺寸 转为像素矩阵
VGG_MEAN = [103.939, 116.778, 123.68]
# 分类图片的路径
dir_path = 'newfile'
# vgg16模型的路径 这个模型保存着训练好的模型的所有参数 需要另外下载
path_Vgg16 = r'C:\Users\machenike\Desktop\vgg16.npy'
# 所有样本
data_all = []
# 所有标签
labels_all = []
for sub_dir in os.listdir(dir_path):
# print(sub_dir)
i = 0
for img_path in os.listdir(os.path.join(dir_path,sub_dir)):
# 图片全路径
imgs = Image.open(os.path.join(dir_path,sub_dir,img_path))
# 转换通道
imgs = imgs.convert('RGB')
# 重置尺寸
imgs = imgs.resize((224,224))
img_array = np.array(imgs)
data_all.append(img_array)
# print(img_array.shape)
# 制作标签
label = str.split(img_path,'.')[0]
labels_all.append(label)
# 转为数组
data_all = np.array(data_all)
labels_all = np.asarray(labels_all)
labels_all = labels_all.astype(np.int)
print(data_all.shape)
print(labels_all.shape)
# 数据集切分和打乱
x_train,x_test,y_train,y_test = train_test_split(data_all,labels_all,test_size=0.1,shuffle=20)
# 载入模型
data_dict = np.load(path_Vgg16,allow_pickle=True,encoding='latin1').item()
class VGGNet:
def __init__(self, data_dict):
self.data_dict = data_dict
# 获取卷积层卷积核
def get_conv_filter(self, name):
return tf.constant(self.data_dict[name][0], name=
利用VGG16模型做迁移学习
最新推荐文章于 2024-04-06 21:55:43 发布