caffe中使用训练好的模型进行图像识别

5 篇文章 0 订阅
3 篇文章 0 订阅
# -*- 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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值