貓狗大戰V1
阿新 • • 發佈:2018-12-19
%matplotlib inline
import numpy as np
import os
import matplotlib.pyplot as plt
fnames = np.array([f'train/{f}' for f in sorted(os.listdir('train/'))])
labels = np.array([(0 if 'cat' in fname else 1) for fname in fnames])
img = plt.imread(fnames[0])
#plt.imshow(img)
print(fnames)
from keras.applications.resnet50 import ResNet50 ResNet50_model = ResNet50(weights='imagenet')
from sklearn.model_selection import train_test_split
X_train,X_valid, y_train, y_valid =train_test_split(fnames,labels,test_size=0.2, random_state=1)
from keras.preprocessing import image from tqdm import tqdm def path_to_tensor(img_path): # 用PIL載入RGB影象為PIL.Image.Image型別 img = image.load_img(img_path, target_size=(224, 224)) # 將PIL.Image.Image型別轉化為格式為(224, 224, 3)的3維張量 x = image.img_to_array(img) # 將3維張量轉化為格式為(1, 224, 224, 3)的4維張量並返回 return np.expand_dims(x, axis=0) def paths_to_tensor(img_paths): list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)] return np.vstack(list_of_tensors)
from keras.applications.resnet50 import preprocess_input, decode_predictions
def ResNet50_predict_labels(img_path):
# 返回img_path路徑的影象的預測向量
img = preprocess_input(path_to_tensor(img_path))
return np.argmax(ResNet50_model.predict(img))
def detector(img_path): prediction = ResNet50_predict_labels(img_path) if (prediction <= 268) & (prediction >= 151): index=1 elif (prediction <= 285) & (prediction >= 281): index=0 else: index=prediction return index
for i in range(100):
img = plt.imread(X_train[i])
plt.imshow(img);
plt.show()
index_num=detector(X_train[i])
if index_num ==0:
call='cat'
elif index_num ==1:
call='dog'
else:
call=index_num
print(f'the picture is {call}\n')
print(index_num)