当前位置:   article > 正文

【深度学习图像识别课程】毕业项目:狗狗种类识别(4)代码实现_宠物种类识别代码

宠物种类识别代码
本博文涉及以下:六
  1. 目录:
  2. Zero:导入数据集
  3. 一、检测人脸
  4. 二、检测狗狗
  5. 三、从头实现CNN实现狗狗分类
  6. 四、迁移VGG16实现狗狗分类
  7. 五、迁移ResNet_50实现狗狗分类
  8. 六、自己实现狗狗分类

 

六、自己实现狗狗分类整体流程

实现一个算法,它的输入为图像的路径,它能够区分图像是否包含一个人、狗或两者都不包含,然后:

  • 如果从图像中检测到一只,返回被预测的品种。
  • 如果从图像中检测到,返回最相像的狗品种。
  • 如果两者都不能在图像中检测到,输出错误提示。

可以自己编写检测图像中人类与狗的函数,可以随意使用已经完成的 face_detector 和 dog_detector 函数。使用在步骤5的CNN来预测狗品种。

下面提供了算法的示例输出,也可以自由地设计模型!

Sample Human Output

1、加载数据集

  1. from sklearn.datasets import load_files
  2. from keras.utils import np_utils
  3. import numpy as np
  4. from glob import glob
  5. # 定义函数来加载train,test和validation数据集
  6. def load_dataset(path):
  7. data = load_files(path)
  8. dog_files = np.array(data['filenames'])
  9. dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
  10. return dog_files, dog_targets
  11. # 加载train,test和validation数据集
  12. train_files, train_targets = load_dataset('dogImages/train')
  13. valid_files, valid_targets = load_dataset('dogImages/valid')
  14. test_files, test_targets = load_dataset('dogImages/test')
  15. # 加载狗品种列表
  16. dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]
  17. # 打印数据统计描述
  18. print('There are %d total dog categories.' % len(dog_names))
  19. print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
  20. print('There are %d training dog images.' % len(train_files))
  21. print('There are %d validation dog images.' % len(valid_files))
  22. print('There are %d test dog images.'% len(test_files))

 

2、检测是否有狗狗

  1. from keras.applications.resnet50 import ResNet50
  2. # 定义ResNet50模型
  3. ResNet50_model = ResNet50(weights='imagenet')
  4. from keras.preprocessing import image
  5. from tqdm import tqdm
  6. def path_to_tensor(img_path):
  7. # 用PIL加载RGB图像为PIL.Image.Image类型
  8. img = image.load_img(img_path, target_size=(224, 224))
  9. # 将PIL.Image.Image类型转化为格式为(224, 224, 3)的3维张量
  10. x = image.img_to_array(img)
  11. # 将3维张量转化为格式为(1, 224, 224, 3)的4维张量并返回
  12. return np.expand_dims(x, axis=0)
  13. def paths_to_tensor(img_paths):
  14. list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
  15. return np.vstack(list_of_tensors)
  16. from keras.applications.resnet50 import preprocess_input, decode_predictions
  17. def ResNet50_predict_labels(img_path):
  18. # 返回img_path路径的图像的预测向量
  19. img = preprocess_input(path_to_tensor(img_path))
  20. return np.argmax(ResNet50_model.predict(img))
  21. def dog_detector(img_path):
  22. prediction = ResNet50_predict_labels(img_path)
  23. return ((prediction <= 268) & (prediction >= 151))

 

3、检测是否有人

  1. import cv2
  2. import matplotlib.pyplot as plt
  3. %matplotlib inline
  4. # 提取预训练的人脸检测模型
  5. face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
  6. # 如果img_path路径表示的图像检测到了脸,返回"True"
  7. def face_detector(img_path):
  8. img = cv2.imread(img_path)
  9. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  10. faces = face_cascade.detectMultiScale(gray)
  11. return len(faces) > 0

 

4、得到bottleneck特征:ResNet50

  1. bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')
  2. train_Resnet50 = bottleneck_features['train']
  3. valid_Resnet50 = bottleneck_features['valid']
  4. test_Resnet50 = bottleneck_features['test']

 

5、模型建立、编译、训练和测试

  1. ### TODO: 定义你的框架
  2. from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
  3. from keras.layers import Dropout, Flatten, Dense
  4. from keras.models import Sequential
  5. Resnet50_model = Sequential()
  6. Resnet50_model.add(GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]))
  7. Resnet50_model.add(Dense(133, activation='softmax'))
  8. Resnet50_model.summary()

  1. ### TODO: 编译模型
  2. Resnet50_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
  1. ### TODO: 训练模型
  2. from keras.callbacks import ModelCheckpoint
  3. checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5',
  4. verbose=1, save_best_only=True)
  5. Resnet50_model.fit(train_Resnet50, train_targets,
  6. validation_data=(valid_Resnet50, valid_targets),
  7. epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
  1. ### TODO: 加载具有最佳验证loss的模型权重
  2. Resnet50_model.load_weights('saved_models/weights.best.Resnet50.hdf5')
  1. ### TODO: 在测试集上计算分类准确率
  2. Resnet50_predictions = [np.argmax(Resnet50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Resnet50]
  3. # 报告测试准确率
  4. test_accuracy = 100*np.sum(np.array(Resnet50_predictions)==np.argmax(test_targets, axis=1))/len(Resnet50_predictions)
  5. print('Test accuracy: %.4f%%' % test_accuracy)

 

 6、测试新图片

  1. ### TODO: 写一个函数,该函数将图像的路径作为输入
  2. ### 然后返回此模型所预测的狗的品种
  3. from extract_bottleneck_features import *
  4. def Resnet50_predict_breed(img_path):
  5. # 提取bottleneck特征
  6. bottleneck_feature = extract_Resnet50(path_to_tensor(img_path))
  7. # 获取预测向量
  8. predicted_vector = Resnet50_model.predict(bottleneck_feature)
  9. # 返回此模型预测的狗的品种
  10. return dog_names[np.argmax(predicted_vector)]
  1. def LastPredict(img_path):
  2. img = cv2.imread(img_path)
  3. # 将BGR图像转变为RGB图像以打印
  4. cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  5. plt.imshow(cv_rgb)
  6. plt.show()
  7. if face_detector(img_path) > 0:
  8. print("Hello, Human")
  9. print("You look like a ... in dog world")
  10. print(Resnet50_predict_breed(img_path))
  11. elif dog_detector(img_path) == True:
  12. print("Hello, Dog")
  13. print("You are a ... ")
  14. print(Resnet50_predict_breed(img_path))
  15. else:
  16. print("Error Input")

(1)6张狗狗:只有第一张被误判为人类,但是检测的相似狗狗对了。另外5张没有错误。

 

(2)5张人的图片:5张没有误判的。另外,我像Poodle。

 

(3)3张猫咪:第二张错误,被误判为人类。其他2张正确。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/744533
推荐阅读
  

闽ICP备14008679号