#cnn 识别狗狗类别
#用类构造代码
#dog图片的训练、保存
#预测以及结果输出
import os
import numpy as np
from PIL import Image
from keras.models import Sequential
from keras.layers import Convolution2D,Flatten,MaxPooling2D,Dense,Activation
from keras.optimizers import Adam
from keras.utils import np_utils
class PreFile(object):#对数据进行预处理
def __init__(self,DogType):
self.FilePath = FilePath
Self.DogType = DogType
def FileReName(self):
count=0
for type in self.DogType:
subfolder = os.listdir(self.FilePath+type)
for subclass in subfolder:
print('count_class:->>',count)
print(subclass)
print(self.FilePath+type+'/'+subclass) #打印图片路径以及名字
os.rename(self.FilePath+type+'/'+subclass,self.FilePath+type+'/'+str(type_counter)+'_'+str(file_counter)+'.jpg')
count+=1
def FileResize(self,Width,Height,Output_folder):
for type in self.DogType:
print(type)
files = os.listdir(self.FilePath+type)
for i in files:
img_open = Image.open(self.Path+type+'/'+i)
conv_RGB = img_open.convert('RGB')#统一将所有图片转换成RGB格式
new_img = conv_RGB.resize((Width,Height),Image.BILINEAR)
new_img.save(os.path.join(Output_folder,os.path.basename(i)))
class Training(object):
def __init__(self,batch_size,number_batch,categories,train_folder):
self.batch_size = batch_size
self.number_batch = number_batch
self.categoried = categories
self.train_folder = train_folder
def read_train_image(self,filename):
img = Image.open(self.train_folder+filename)
return np.array(img)
def train(self):
train_img_list = [] #X_train
train_label_list = [] #Y_train
for file in os.listdir(self.train_folder):
file_img_in_array = self.read_train_image(filename=file)
train_img_list.append(file_img_in_array)
train_label_list.append(int(file.split('_')[0]))
print(file.split('_')[0])
#网络吃的是numpy数组,所以必须转化
train_img_list = np.array(train_img_list)
train_label_list = np.array(train_label_list)
train_label_list = np_utils.to_categorical(train_label_list,self.categoried)
train_img_list = train_img_list.astype('float32')
train_img_list/=255.0
model = Sequential()
#输入是(100,100,3)
#CNN layer 1st
model.add(Convolution2D(
input_shape=(100,100,3),
filters = 32, #所以输出应该是(100,100,32)
kernel_size = (5,5),
padding = 'same',
))
model.add(Activation('relu'))
model.add(MaxPooling2D(
pool_size = (2,2),
strides = (2,2),#所以输出变成(50,50,32)
padding = 'same'
))
#CNN layer 2nd
model.add(Convolution2D(
filters = 64, #所以输出应该是(50,50,64)
kernel_size = (2,2),
padding = 'same',
))
model.add(Activation('relu'))
model.add(MaxPooling2D(
pool_size = (2,2),
strides = (2,2),#所以输出变成(25,25,64)
padding = 'same'
))
model.add(Flatten()) #降维打击
model.add(Dense(1024))
model.add(Activation('relu'))
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dense(self.categoried))
model.add(Activation('softmax'))
#添加优化器
adam = Adam(lr=0.0001)
#编译
model.compile(
optimizer = adam,
loss='categorical_crossentropy',
metrics=['accuracy']
)
model.fit(
x=train_img_list,
y=train_label_list,
epochs = self.number_batch,
batch_size=self.batch_size,
verbose = 1,
#validation_data #如果有test数据
)
model.save('/content/drive/My Drive/app/dogfinder.h5')
def MAIN():
DogType=['erha','demu','labuladuo','samoye']
Train = Training(batch_size=128,number_batch=30,categories=4,train_folder='/content/drive/My Drive/app/my_image/DogRawTrain/')
Train.train()
if __name__=="__main__":
MAIN()
模型训练结果:
预测
from keras.models import load_model #加载模型
import matplotlib.image as processimage #处理照片
import matplotlib.pyplot as plt #打印照片
import numpy as np
from PIL import Image
class Prediction(object):
#初始化函数
def __init__(self,ModelFile,PredictFile,DogType,Width=100,Height=100):
self.modelfile = ModelFile
self.predict_file = PredictFile
self.Width = Width
self.Height = Height
self.DogType = DogType
def Predict(self):
model = load_model(self.modelfile)
#print('load model')
image_open = Image.open(self.predict_file)
#print('open image')
conv_RGB = image_open.convert('RGB')
new_img = conv_RGB.resize((self.Width,self.Height),Image.BILINEAR)
new_img.save(self.predict_file)#覆盖掉了原来的文件
print('Image Resized')
image= processimage.imread(self.predict_file)
image_to_array = np.array(image)/255.0
image_to_array = image_to_array.reshape(-1,100,100,3)
print('Image2Array')
prediction = model.predict(image_to_array)
Final_Pred = [result.argmax() for result in prediction]
print(prediction)
print(Final_Pred)
count = 0
for i in prediction[0]:
percent = '%.2f%%'%(i*100)
print(self.DogType[count],'概率',percent)
count+=1
DogType=['erha','demu','labuladuo','samoye']
Pred = Prediction(DogType=DogType,PredictFile='/content/drive/My Drive/app/my_image/DogRawTest/erha2.jpg',ModelFile='/content/drive/My Drive/app/dogfinder.h5')
Pred.Predict()
模型预测结果: