caffe的python接口提取resnet101某层特征

 论文的caffemodel转化为tensorflow模型过程中越坑无数,最后索性直接用caffe提特征。

caffe提取倒数第二层,pool5的输出,fc1000层的输入,2048维的特征

 1 #coding=utf-8
 2 
 3 import caffe
 4 import os
 5 import numpy as np
 6 
 7 OUTPUT='E:/caffemodel/'#输出txt文件夹
 8 root='E:/caffemodel/'   #根目录
 9 deploy=root + 'ResNet-101-deploy.prototxt'    #deploy文件
10 caffe_model=root + 'ResNet-101-model.caffemodel'   #训练好的 caffemodel
11 imgroot = 'E:/bjfu-cv-project/CUB_200_2011/CUB_200_2011/images/'   #随机找的一张待测图片路径
12 #labels_filename = 'E:/bjfu-cv-project/CUB_200_2011/CUB_200_2011/classes.txt'  #类别名称文件,将数字标签转换回类别名称
13 net = caffe.Net(deploy,caffe_model,caffe.TEST)   #加载model和network
14 mean_file='mean.npy'
15 for line in open("feature2048test5.txt"):
16     line=line[:-1]
17     img = imgroot +line
18     print(img)
19 
20     #图片预处理设置
21     transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})  #设定图片的shape格式(1,3,224,224)
22     transformer.set_transpose('data', (2,0,1))    #改变维度的顺序,由原始图片(224,224,3)变为(3,224,224)
23     transformer.set_mean('data', np.load(mean_file).mean(1).mean(1))    #减去均值
24     transformer.set_raw_scale('data', 255)    # 缩放到【0,255】之间
25     transformer.set_channel_swap('data', (2,1,0))   #交换通道,将图片由RGB变为BGR
26     im=caffe.io.load_image(img)                   #加载图片
27     net.blobs['data'].data[...] = transformer.preprocess('data',im)      #执行上面设置的图片预处理操作,并将图片载入到blob中
28 
29     #执行测试
30     out = net.forward()
31     fea = net.blobs['pool5'].data  # 提取某层数据(特征)
32     output_dir=str(line)+".txt"
33     isExists = os.path.exists(output_dir)
34     if not isExists:
35         os.makedirs(output_dir)
36     out_name1 = img.split('/')[-1]
37     out_name2 = out_name1.split('.')[0]
38     print(out_name2)
39     np.savetxt(str(out_name2) + ".txt", fea, delimiter='\n',fmt="%.4f")

均值文件ResNet_mean.binaryproto转化mean.npy

 1 #coding=utf-8
 2 import caffe
 3 import numpy as np
 4 
 5 MEAN_PROTO_PATH = 'ResNet_mean.binaryproto'               # 待转换的pb格式图像均值文件路径
 6 
 7 MEAN_NPY_PATH = 'mean.npy'                         # 转换后的numpy格式图像均值文件路径
 8 
 9 blob = caffe.proto.caffe_pb2.BlobProto()           # 创建protobuf blob
10 data = open(MEAN_PROTO_PATH, 'rb' ).read()         # 读入mean.binaryproto文件内容
11 blob.ParseFromString(data)                         # 解析文件内容到blob
12 
13 array = np.array(caffe.io.blobproto_to_array(blob))# 将blob中的均值转换成numpy格式,array的shape (mean_number,channel, hight, width)
14 mean_npy = array[0]                                # 一个array中可以有多组均值存在,故需要通过下标选择其中一组均值
15 np.save(MEAN_NPY_PATH ,mean_npy)

猜你喜欢

转载自www.cnblogs.com/wind-chaser/p/10854716.html