windows运行caffe-ssd目标检测

将在ubuntu下训练的caffe-ssd模型移植到windows下。

配置环境:windows7系统+vs2013(推荐)+cuda8.0

所需文件:

windows-caffe:https://github.com/conner99/caffe 选择ssd-Microsoft 分支

ubuntu-ssd地址:链接:http://pan.baidu.com/s/1mhYuf7y 密码:3jp2

libboost地址:链接:http://pan.baidu.com/s/1pLbBMpP 密码:41tq

cudnn地址:链接:http://pan.baidu.com/s/1o8vWBhw 密码:kdj4

opencv地址:链接:http://pan.baidu.com/s/1eSkHBj0 密码:nhch

ssd_detect.cpp地址:链接:http://pan.baidu.com/s/1nvwECNv 密码:e3yn

io.cpp地址:链接:http://pan.baidu.com/s/1i4CL7QP 密码:g623


cpu测试:

复制caffe-ssd-Microsoft/windows下commonsettings.props.example重命名为commonsettings.props,修改为<CpuOnlyBuild>true</CpuOnlyBuild>
        <UseCuDNN>false</UseCuDNN>
        <CudaVersion>8.0</CudaVersion>

vs2013打开caffe.sln,编译libcaffe(属性--配置属性--c/c++--常规--“将警告视为错误--否”)

复制ubuntu-ssd下所有文件(除build ,data,example,models以外)到caffe-ssd-Microsoft,选择替换,替换原文件夹文件。

可能出现的错误:

1. 缺少hungarian.h和Hungarian.cpp文件,分别在caffe-ssd-Microsoft/include/caffe/3rdparty下添加hungarian.h文件,在caffe-ssd-Microsoft/src/caffe/3rdparty下添加hungarian.cpp文件,在ubuntu-ssd链接下有以上两个文件;

2. hdf5.cpp文件报错“occurrences_32”的初始化操作由“case”标签跳过。在hdf5.cpp文件中将所有case语句下的内容都加上大括号{},例如:

3. db_lmdb.cpp文件报错"mkdir":找不到标识符。在db_lmdb.cpp文件的

CHECK_EQ(mkdir(source.c_str(), 0744), 0) << "mkdir " << source << " failed";

上下加上两句

4. signal_handler.cpp报错,替换成https://github.com/conner99/caffe文件夹下的该文件

5. common.cpp文件报错“无法解析的外部符号”google::InstallFailureSignalHandler(),将common.cpp中注释掉:

common.cpp报错“signup未声明的标识符”。在common.cpp文件添加

libcaffe编译成功后,编译caffe,同样设置   属性--配置属性--c/c++--常规--“将警告视为错误--否”

编译成功后,选择classification,用ssd_detect.cpp文件替换掉原有文件,去掉注释, 按照文件位置修改模型文件和待检测图片位置,如我的路径如下:

根据待检测的文件类型,修改file_type为image或video

编译classification,点击生成的caffe-ssd-microsoft/build/x64/release/classification.exe,成功后会跳出检测好后的图片

用python调用caffe进行图片检测

注意修改caffe_root,root,labelmap_file,model_weights,model_def,image路径


# coding: utf-8
# # Detection with SSD
 
import numpy as np
import matplotlib.pyplot as plt
import pylab
 
plt.rcParams['figure.figsize'] = (10, 10)
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
 
# Make sure that caffe is on the python path:
caffe_root = 'D:/caffe-ssd-microsoft/'  # this file is expected to be in {caffe_root}/examples
root = 'D:/mymodel/'
import os
os.chdir(caffe_root)
import sys
sys.path.insert(0, 'python')
 
import caffe
#caffe.set_device(0)
#caffe.set_mode_gpu()
caffe.set_mode_cpu()
 
# * Load LabelMap.
 
from google.protobuf import text_format
from caffe.proto import caffe_pb2
 
# load PASCAL VOC labels
labelmap_file = root+'labelmap_voc.prototxt'
file = open(labelmap_file, 'r')
labelmap = caffe_pb2.LabelMap()
text_format.Merge(str(file.read()), labelmap)
 
def get_labelname(labelmap, labels):
    num_labels = len(labelmap.item)
    labelnames = []
    if type(labels) is not list:
        labels = [labels]
    for label in labels:
        found = False
        for i in xrange(0, num_labels):
            if label == labelmap.item[i].label:
                found = True
                labelnames.append(labelmap.item[i].display_name)
                break
        assert found == True
    return labelnames
 
 
# * Load the net in the test phase for inference, and configure input preprocessing.
 
model_def = root+'deploy.prototxt'
model_weights = root+'VGG_FJXBS_SSD_512x512_iter_87647.caffemodel'
 
net = caffe.Net(model_def,      # defines the structure of the model
                model_weights,  # contains the trained weights
                caffe.TEST)     # use test mode (e.g., don't perform dropout)
 
# input preprocessing: 'data' is the name of the input blob == net.inputs[0]
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2, 0, 1))
transformer.set_mean('data', np.array([104,117,123])) # mean pixel
transformer.set_raw_scale('data', 255)  # the reference model operates on images in [0,255] range instead of [0,1]
transformer.set_channel_swap('data', (2,1,0))  # the reference model has channels in BGR order instead of RGB
 
 
# ### 2. SSD detection
 
# * Load an image.
 
# set net to batch size of 1
image_resize = 512
net.blobs['data'].reshape(1,3,image_resize,image_resize)
 
image = caffe.io.load_image('G:/fjx/test_bs/1312.jpg')
#plt.imshow(image)
#pylab.show()
 
# * Run the net and examine the top_k results
 
transformed_image = transformer.preprocess('data', image)
net.blobs['data'].data[...] = transformed_image
 
# Forward pass.
detections = net.forward()['detection_out']
 
# Parse the outputs.
det_label = detections[0,0,:,1]
det_conf = detections[0,0,:,2]
det_xmin = detections[0,0,:,3]
det_ymin = detections[0,0,:,4]
det_xmax = detections[0,0,:,5]
det_ymax = detections[0,0,:,6]
 
# Get detections with confidence higher than 0.3.
top_indices = [i for i, conf in enumerate(det_conf) if conf >= 0.3]
 
top_conf = det_conf[top_indices]
top_label_indices = det_label[top_indices].tolist()
top_labels = get_labelname(labelmap, top_label_indices)
top_xmin = det_xmin[top_indices]
top_ymin = det_ymin[top_indices]
top_xmax = det_xmax[top_indices]
top_ymax = det_ymax[top_indices]
 
 
# * Plot the boxes
 
colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist()
 
plt.imshow(image)
currentAxis = plt.gca()
 
for i in xrange(top_conf.shape[0]):
    xmin = int(round(top_xmin[i] * image.shape[1]))
    ymin = int(round(top_ymin[i] * image.shape[0]))
    xmax = int(round(top_xmax[i] * image.shape[1]))
    ymax = int(round(top_ymax[i] * image.shape[0]))
    score = top_conf[i]
    label = int(top_label_indices[i])
    label_name = top_labels[i]
    display_txt = '%s: %.2f'%(label_name, score)
    coords = (xmin, ymin), xmax-xmin+1, ymax-ymin+1
    color = colors[label]
    currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor=color, linewidth=2))
    currentAxis.text(xmin, ymin, display_txt, bbox={'facecolor':color, 'alpha':0.5})
 
pylab.show()

gpu测试: 

打开commonsettings.props,修改为<CpuOnlyBuild>false</CpuOnlyBuild>,<UseCuDNN>true</UseCuDNN>

更改cudnn路径

 <CuDnnPath>D:\software\cudnn-8.0-windows7-x64-v5.1</CuDnnPath>

更改cuda计算能力

 <CudaArchitecture>compute_30,sm_30;compute_50,sm_50</CudaArchitecture>

如果使用python和matlab,还要更改它们的位置路径

编译libcaffe和caffe

可能出现的错误:

1. error MSB3721:C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin\nvcc.exe

我的解决办法是打开conv_layer.cu文件,修改一句话

 this->forward_gpu_gemm(bottom_data + n * this->bottom_dim_, weight,
          top_data + n * this->top_dim_,false);

即添加一个参数false

2. cuda库找不到的问题,打开项目属性,将cuda路径添加到VC++,目录中去:

包含目录添加:C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\include

库目录添加:C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\lib\x64

3. 有关thrust的错误,打开bbox_util.cu文件,注释掉所有包含thrust的语句

//#include "thrust/functional.h"
//#include "thrust/sort.h"

//thrust::sort_by_key(&confidences[0], &confidences[0] + num_remain, &idx[0],
//thrust::greater<Dtype>());

4.运行classification.exe报错停止,failed to parse netparameter file xxxxxxxxx\deploy.prototxt check failure stack trace:***

打开deploy.prototxt ,将所有prior_box_param包含的step、offset删除 

在此运行,可以得到检测结果。

  至此,caffe-ssd移植到了windows系统下

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,针对你的问题,这里简单介绍一下如何使用caffe-ssd预训练模型进行目标检测caffe-ssd是基于caffe框架实现的单阶段目标检测算法,使用预训练模型可以加快模型训练的速度,同时也可以提高模型的检测精度。下面是使用预训练模型做目标检测的步骤: 1. 下载预训练模型 caffe-ssd官方提供了一些预训练模型,可以在这里下载:https://github.com/weiliu89/caffe/tree/ssd#models。选择适合自己数据集的模型进行下载。 2. 准备数据集 准备自己的数据集,包括训练集、验证集和测试集。数据集需要满足SSD数据格式要求,即每个样本需要有对应的标注文件,标注文件格式为:类别id、xmin、ymin、xmax、ymax(例如:0 0.1 0.2 0.3 0.4,表示类别为0,左上角坐标为(0.1, 0.2),右下角坐标为(0.3, 0.4))。 3. 修改配置文件 修改caffe-ssd的配置文件,将模型路径、数据路径、类别数等参数配置正确。其中,模型路径需要指定为下载的预训练模型路径。 4. 训练模型 使用修改后的配置文件训练模型。训练过程中可以调整学习率、迭代次数等参数,以达到更好的效果。 5. 测试模型 使用测试集对训练好的模型进行测试,并计算模型在测试集上的精度和召回率等指标。 以上就是使用caffe-ssd预训练模型做目标检测的基本步骤。需要注意的是,使用预训练模型虽然可以加速模型训练过程,但是如果数据集和预训练模型的差异较大,仍然需要进行微调。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值