# -*- coding: utf-8 -*-
"""
Created on Fri Apr 6 09:33:13 2018
@author: Daniel
"""
import caffe
import numpy as np
import PIL
from PIL import Image
import matplotlib.pyplot as plt
import os
import sys
#定义相关文件路径
caffe_root = 'F:/GitHub/caffe_sub/caffe/'
deploy_file = caffe_root + 'models/bvlc_googlenet/deploy.prototxt'
model_file = caffe_root + 'models/bvlc_googlenet/bvlc_googlenet.caffemodel'
#设置训练模式
caffe.set_mode_cpu()
#定义网络模型
net = caffe.Classifier(deploy_file,
model_file,
mean=np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1),
channel_swap=(2,1,0),
raw_scale=255,#python中的像素取值范围是0-1,而caffe中图片是0-255,故需要一个转换
image_dims=(224,224))
#分类标签文件
imagenet_labels_filename = caffe_root + 'models/bvlc_googlenet/synset_words.txt'
labels = np.loadtxt(imagenet_labels_filename, str, delimiter = '\t')#载入标签,类型为string,分隔符为制表符
##对目标中的图像进行遍历并分类
for root, dir, files in os.walk(caffe_root + 'models/bvlc_googlenet/image/'):
for file in files:
#加载要分类的图片
image_file = os.path.join(root,file)#组合root和file,使之成为root/file
input_image = caffe.io.load_image(image_file)#加载图片
#打印图片路径及名称
image_path = os.path.join(root, file)
print(image_path)
#显示图片
img = Image.open(image_path)#将图片转换为PIL图像
plt.imshow(img)#将PIL图像传入,返回AxesImage(坐标图像)
plt.axis('off')#关闭坐标
plt.show()#显示图像
#预测分类
prediction = net.predict([input_image])
#输出概率前五的预测结果
top_five = prediction[0].argsort()[-5:][::-1]#[::-1]是对当前序列取到数操作
for i in top_five:
#获取分类名称
class_string = labels[i]
#获取置信度
score = prediction[0][i]
print('%s (score = %.5s)' % (class_string, score))
caffe中使用训练好的模型进行图像识别
最新推荐文章于 2019-04-25 16:11:32 发布