caffe pichulitupian

本文介绍如何使用Caffe框架进行深度学习模型的部署过程,包括环境配置、模型加载及图片预处理步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#coding=utf-8
import numpy as np
import sys,os
caffe_root='/home/ls/caffe-master/'   #根目录
sys.path.insert(0, caffe_root + 'python')
import caffe
os.chdir(caffe_root)
caffe.set_device(0)
caffe.set_mode_gpu()

root='/home/ls/caffe-master/'
deploy= root+'myself/deploy.prototxt'    #deploy文件
caffe_model=root+'myself/caffenet_train_iter_15000.caffemodel'   #训练好的 caffemodel
mean_file=root+'myself/imagenet_mean.npy'
img_txt=root+'myself/test/test.txt'    #随机找的一张待测图片
#labels_filename =root+'synset_words.txt'  #类别名称文件,将数字标签转换回类别名称

caffe.set_device(0)
caffe.set_mode_gpu()

net = caffe.Net(deploy,caffe_model,caffe.TEST)   #加载model和network

#图片预处理设置
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})  #设定图片的shape格式(1,3,28,28)
transformer.set_transpose('data', (2,0,1))    #改变维度的顺序,由原始图片(28,28,3)变为(3,28,28)
transformer.set_mean('data', np.load(mean_file).mean(1).mean(1))    #减去均值,前面训练模型时没有减均值,这儿就不用
transformer.set_raw_scale('data', 255)    # 缩放到【0,255】之间
transformer.set_channel_swap('data', (2,1,0))   #交换通道,将图片由RGB变为BGR
transformer.set_image_dim=(160,160)

fp=open(img_txt,'a+')
lines=fp.readlines()
for line in lines:
    im=caffe.io.load_image(line.strip('\n'))    #加载图片         
    net.blobs['data'].data[...] = transformer.preprocess('data',im)      #执行上面设置的图片预处理操作,并将图片载入到blob中
    #执行测试
    out = net.forward()
   # labels = np.loadtxt(labels_filename, str, delimiter='\t')   #读取类别名称文件
#prob= net.blobs['Softmax1'].data[0].flatten() #取出最后一层(Softmax)属于某个类别的概率值,并打印
#print prob
#order=prob.argsort()[0]  #将概率值排序,取出最大值所在的序号
#print 'the class is:',labels[order]   #将该序号转换成对应的类别名称,并打印
  #  top_k = net.blobs['prob'].data[0].flatten().argsort()[-1:-2:-1]
 #   for i in np.arange(top_k.size):
#        print top_k[i], labels[top_k[i]]
   #     fp.write(line.strip('\n')+'     '+labels[top_k[i]]+'\n')
    output_prob = output['prob'][0]  # the output probability vector for the first image in the batch

    print 'predicted class is:', output_prob.argmax()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值