目标检测:3 SSD的安装与测试

注意:最好使用python2来配置caffe接口,python3问题很多,但是也可以,这里只说python2,python3请绕道。最好不要使用anconda不然坑太多。

 

    主要步骤如下:

  1. 下载SSD代码(源码
  2. unzip caffe-ssd.zip
    cd caffe-ssd
    cp Makefile.config.example Makefile.config
    

     

  3. 打开Makefile.config文件

      Makefile.config中默认是opencv2版本系列,如果使用的是3以上。

# OPENCV_VERSION := 3
改成
OPENCV_VERSION := 3

 

文件中:
PYTHON_INCLUDE := /usr/include/python2.7 \
		 /usr/lib/python2.7/dist-packages/numpy/core/include

一般需要加local,可以查看自己的python2的路径,如何相同就不需要改。(这里给的是python2的默认路径)
改成:
PYTHON_INCLUDE := /usr/include/python2.7 \
		/usr/local/lib/python2.7/dist-packages/numpy/core/include

4、sudo make  -j10

j后边是需要用的线程数

如果出现错问题,如cuda之类的错误,自行百度吧。这里只说ssd的编译,这里一般不会出错。

Makefile:591: recipe for target '.build_release/src/caffe/layers/image_data_layer.o' failed

 这个错误是opencv的问题,可以直接把opencv屏蔽掉。

5、sudo make test 验证一下是否编译成功(可以不操作)

6、配置python接口:sudo make pycaffe

如果出现numpy之类的错误:查看上边的python地址后边的numpy是否正确,确任python地址是否正确

7、


返回到home下
cd

配置路径
sudo gedit ~/.bashrc

添加caffe下python路径
/home/boyun/下载/caffe-ssd/python
export PYTHONPATH=/path/caffe-ssd/python/:$PYTHONPATH

path为自己的根目录


使能
sudo ldconfig

8、关闭终端,重新打开一个终端

进入python环境

输入:

import caffe
caffe.__version__

如果打印caffe版本则配置成功。 

9、测试

修改这四处的地址:
model_def = '/models/models/VGGNet/VOC0712Plus/SSD_300x300/deploy.prototxt'

model_weights = '/models/models/VGGNet/VOC0712Plus/SSD_300x300/VGG_VOC0712Plus_SSD_300x300_iter_240000.caffemodel'

labelmap_file = '/data/VOC0712/labelmap_voc.prototxt'

image = caffe.io.load_image('/examples/images/cat.jpg')

# -*- coding: UTF-8 -*-


import numpy as np
import matplotlib.pyplot as plt

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 = '../'  # this file is expected to be in {caffe_root}/examples
import os
os.chdir(caffe_root)
import sys
sys.path.insert(0, 'python')

import caffe
caffe.set_device(0)
caffe.set_mode_gpu()


from google.protobuf import text_format
from caffe.proto import caffe_pb2

# load PASCAL VOC labels
labelmap_file = '/data/VOC0712/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

model_def = '/models/models/VGGNet/VOC0712Plus/SSD_300x300/deploy.prototxt'

model_weights = '/models/models/VGGNet/VOC0712Plus/SSD_300x300/VGG_VOC0712Plus_SSD_300x300_iter_240000.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
# set net to batch size of 1
image_resize = 300
net.blobs['data'].reshape(1,3,image_resize,image_resize)

image = caffe.io.load_image('/examples/images/cat.jpg')



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.6.
top_indices = [i for i, conf in enumerate(det_conf) if conf >= 0.6]

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]
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]))
    print(xmin,ymin,xmax,ymax )

    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})


plt.show()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值