Caffe 抽取CNN网络特征 Python

Caffe Python特征抽取

转载请注明出处,楼燚(yì)航的blog, http://www.cnblogs.com/louyihang-loves-baiyan/

Caffe大家一般用到的深度学习平台都是这个,关于Caffe的训练通常一般都可以通过一些命令来执行,但是在deploy阶段,如果是做实际的工程,那么C++接口用得会相对比较多。但是Caffe是支持Python和Matlab接口的,所以用Python来做一些相关的特征的处理以及额外的任务比较方便

这里我主要是结合了Caffe官网的例程,当然它给的例程是参照的Ipython,然后以命令的形式,我主要做了一些相关的整合。当时也不知道怎么提取一些相关特征,上网一搜也基本上没有干净、好的代码。因此我在这里介绍如何使用Python做特征的抽取。

Python 接口

首先你要确保你已经在安装Caffe时,编译了Python接口,我记得对应着的命令是make pycaffe ,相关的接口是在在 Caffe_Root\python 目录下,这个目录里面还是有一个caffe模块,提供了一些使用python的基本类

抽取的代码

这里我把其例程中,以及一部分我添加的代码都合到了一起,并且加了注释,希望能对大家有帮助,这里主要是三个函数

  • initialize () 初始化网络的相关
  • readlist() 读取抽取图像列表
  • extractFeatre() 抽取图像的特征,保存为指定的格式

其中在transformer那里需要根据自己的需求设定

import numpy as np
import matplotlib.pyplot as plt
import os
import caffe
import sys
import pickle
import struct
import sys,cv2
caffe_root = '../'  
# 运行模型的prototxt
deployPrototxt =  '/home/chenjie/baiyan/caffe/models/compcar_model_C_all/deploy_louyihang.prototxt'
# 相应载入的modelfile
modelFile = '/home/chenjie/baiyan/caffe/models/compcar_model_C_all/caffenet_carmodel_baiyan_iter_50000.caffemodel'
# meanfile 也可以用自己生成的
meanFile = 'python/caffe/imagenet/ilsvrc_2012_mean.npy'
# 需要提取的图像列表
imageListFile = '/home/chenjie/DataSet/500CarCNNRetrieve/500CarFaceOrig/images_total.txt'
imageBasePath = '/home/chenjie/DataSet/500CarCNNRetrieve/500CarFaceOrig'
gpuID = 4
postfix = '.classify_allCar1716_fc6'

# 初始化函数的相关操作
def initilize():
    print 'initilize ... '

    sys.path.insert(0, caffe_root + 'python')
    caffe.set_mode_gpu()
    caffe.set_device(gpuID)
    net = caffe.Net(deployPrototxt, modelFile,caffe.TEST)
    return net  
# 提取特征并保存为相应地文件
def extractFeature(imageList, net):
    # 对输入数据做相应地调整如通道、尺寸等等
    transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
    transformer.set_transpose('data', (2,0,1))
    transformer.set_mean('data', np.load(caffe_root + meanFile).mean(1).mean(1)) # mean pixel
    transformer.set_raw_scale('data', 255)  
    transformer.set_channel_swap('data', (2,1,0))  
    # set net to batch size of 1 如果图片较多就设置合适的batchsize 
    net.blobs['data'].reshape(1,3,227,227)      #这里根据需要设定,如果网络中不一致,需要调整
    num=0
    for imagefile in imageList:
        imagefile_abs = os.path.join(imageBasePath, imagefile)
        print imagefile_abs
        net.blobs['data'].data[...] = transformer.preprocess('data', caffe.io.load_image(imagefile_abs))
        out = net.forward()
        fea_file = imagefile_abs.replace('.jpg',postfix)
        num +=1
        print 'Num ',num,' extract feature ',fea_file
        with  open(fea_file,'wb') as f:
            for x in xrange(0, net.blobs['fc6'].data.shape[0]):
                for y in xrange(0, net.blobs['fc6'].data.shape[1]):
                    f.write(struct.pack('f', net.blobs['fc6'].data[x,y]))

# 读取文件列表
def readImageList(imageListFile):
    imageList = []
    with open(imageListFile,'r') as fi:
        while(True):
            line = fi.readline().strip().split()# every line is a image file name
            if not line:
                break
            imageList.append(line[0]) 
    print 'read imageList done image num ', len(imageList)
    return imageList

if __name__ == "__main__":
    net = initilize()
    imageList = readImageList(imageListFile) 
    extractFeature(imageList, net)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
RCNNPython源代码主要是基于Caffe框架实现的,以下是RCNNPython源代码示例: 1. 数据预处理部分: ```python import numpy as np import os import cv2 # 读取图像并进行预处理 def load_image(filename): img = cv2.imread(filename) img = img.astype(np.float32, copy=False) # 图像缩放 img = cv2.resize(img, (224, 224)) # 图像减均值 img -= [104, 117, 123] # 图像通道转换 img = img.transpose((2, 0, 1)) return img ``` 2. 候选区域提取部分: ```python import selectivesearch # 使用选择性搜索算法提取候选区域 def selective_search(image, mode='fast'): # 选择性搜索参数配置 ss = selectivesearch.selective_search(image, mode=mode) # 提取候选区域 candidates = [] for e, (x, y, w, h) in enumerate(ss): if w < 10 or h < 10: continue candidates.append((x, y, w, h)) return candidates ``` 3. 特征提取部分: ```python import caffe # 加载模型和权重 def load_net(model_file, pretrained_file): net = caffe.Net(model_file, pretrained_file, caffe.TEST) return net # 提取候选区域的特征 def extract_features(net, image, candidates): features = [] for x, y, w, h in candidates: # 裁剪候选区域并进行预处理 roi = image[:, y:y+h, x:x+w] roi = cv2.resize(roi, (227, 227)) roi = roi - np.array([104, 117, 123]) # 将候选区域送入网络中进行前向传播 net.blobs['data'].reshape(1, 3, 227, 227) net.blobs['data'].data[...] = roi net.forward() # 提取网络特征表示 feat = net.blobs['fc7'].data[0].copy() features.append(feat) return features ``` 4. 目标分类和定位部分: ```python # 加载SVM模型 def load_svm_model(model_file): svm_model = cv2.ml.SVM_load(model_file) return svm_model # 对候选区域进行分类和定位 def classify_and_locate(svm_model, features, candidates): labels = [] bboxes = [] for i, feat in enumerate(features): # 对特征进行分类 label = svm_model.predict(feat.reshape(1, -1))[1][0][0] if label == 1: # 如果分类为正样本,则进行定位 bbox = candidates[i] bboxes.append(bbox) labels.append(label) return labels, bboxes ``` 5. 非极大值抑制部分: ```python # 非极大值抑制 def non_max_suppression(bboxes, overlap_threshold=0.3): # 计算候选区域的面积 areas = [(x[2] - x[0] + 1) * (x[3] - x[1] + 1) for x in bboxes] # 根据y坐标排序 idxs = np.argsort([x[1] for x in bboxes]) picked_idxs = [] # 对每个候选区域进行遍历 while len(idxs) > 0: # 取出第一个候选区域 i = idxs[0] picked_idxs.append(i) # 计算与其重叠度最大的候选区域 overlaps = [] for j in idxs[1:]: intersection = max(0, min(bboxes[i][2], bboxes[j][2]) - max(bboxes[i][0], bboxes[j][0])) \ * max(0, min(bboxes[i][3], bboxes[j][3]) - max(bboxes[i][1], bboxes[j][1])) union = areas[i] + areas[j] - intersection overlap = intersection / union overlaps.append(overlap) # 删除与其重叠度大于阈值的候选区域 idxs = np.delete(idxs, np.concatenate(([0], np.where(np.array(overlaps) > overlap_threshold)[0] + 1))) # 返回最终的候选区域 bboxes = [bboxes[i] for i in picked_idxs] return bboxes ``` 以上就是RCNNPython源代码示例,其中主要使用了OpenCV和Caffe两个库。这里的代码仅供参考,具体实现还需要根据具体的任务和数据进行相应的调整和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值