猫狗大战V1

%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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值