caffe-SSD 安装、训练、SSD测试(ubuntu18.04+cuda9.0+openvc3.4)

安装及MNIST模型测试、matlab caffe接口测试

https://blog.csdn.net/qq_35608277/article/details/84938244

自己看代码提供者的最直接,大家都是根据他的copy的:
https://github.com/weiliu89/caffe/tree/ssd

1 数据准备

1.1 voc0712数据集下载

# Download the data.
cd $HOME/data
wget http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar
wget http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtrainval_06-Nov-2007.tar
wget http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtest_06-Nov-2007.tar
# Extract the data.
tar -xvf VOCtrainval_11-May-2012.tar
tar -xvf VOCtrainval_06-Nov-2007.tar
tar -xvf VOCtest_06-Nov-2007.tar

放在/home/data下

然后回到caffe-ssd文件夹下生成LMDB 文件.

cd caffe-ssd
./data/VOC0712/create_list.sh
# It will create lmdb files for trainval and test with encoded original image:
#   - $HOME/data/VOCdevkit/VOC0712/lmdb/VOC0712_trainval_lmdb
#   - $HOME/data/VOCdevkit/VOC0712/lmdb/VOC0712_test_lmdb
./data/VOC0712/create_data.sh

1.2 下载预训练模型

便于自己训练
预训练模型(VGG):VGG_ILSVRC_16_layers_fc_reduced.caffemodel
(下载地址:密码: t9ub
下载完毕后将VGG模型放到caffe主目录下 models\VGGNet 下面(如果没有的话,models 下面没有的话mkdir VGGNet)

1.3 下载训练好的权重

git model
百度云
链接:http://pan.baidu.com/s/1kVoJ6GR 密码:leo6
解压替换掉models里的文件。
VGG_VOC0712_SSD_300x300_iter_240000.caffemodel,
.prototxt files, python scripts.

2 测试模型

在caffe-ssd中新建文件夹my_detection.定义detect.py,这里没有用ipynb

https://github.com/weiliu89/caffe/blob/ssd/examples/ssd_detect.ipynb

# coding: utf-8
# Note: this file is expected to be in {caffe_root}/examples
# ### 1. Setup
from __future__ import print_function
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'
 
 
caffe_root = '../'
import os
os.chdir(caffe_root)
import sys
#sys.path.insert(0, '/home/lilai/LL/caffe/python')
import caffe
from google.protobuf import text_format
from caffe.proto import caffe_pb2
 
 
caffe.set_device(0)
caffe.set_mode_gpu()
labelmap_file = '/home/dong/Downloads/caffe-ssd/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 = '/home/dong/Downloads/caffe-ssd/my_detection/deploy.prototxt'


model_weights = '/home/dong/Downloads/caffe-ssd/models/VGGNet/VOC0712/SSD_300x300/VGG_VOC0712_SSD_300x300_iter_240000.caffemodel'
 
net = caffe.Net(model_def, model_weights, caffe.TEST)
# 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.
 
image_resize = 300
net.blobs['data'].reshape(1, 3, image_resize, image_resize)
 
image = caffe.io.load_image('/home/dong/Downloads/caffe-ssd/examples/images/fish-bike.jpg')
plt.imshow(image)
 
# 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.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]
 
# Plot the boxes
 
colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist()
 
currentAxis = plt.gca()
 
for i in xrange(top_conf.shape[0]):
    # bbox value
    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
    score = top_conf[i]
    # label
    label = int(top_label_indices[i])
    label_name = top_labels[i]
    # display info: label score xmin ymin xmax ymax
    display_txt = '%s: %.2f %d %d %d %d' % (label_name, score,xmin, ymin, xmax, ymax)
    # display_bbox_value = '%d %d %d %d' % (xmin, ymin, xmax, ymax)
    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})
    # currentAxis.text((xmin+xmax)/2, (ymin+ymax)/2, display_bbox_value, bbox={'facecolor': color, 'alpha': 0.5})
plt.imshow(image)
pylab.show()

选择模型文件,从models/VGGNet中复制一份到自己文件夹。并且修改上述路径
deploy.prototxt
最后几行,修改label和name_size 的路径

  detection_output_param {
    num_classes: 21
    share_location: true
    background_label_id: 0
    nms_param {
      nms_threshold: 0.449999988079
      top_k: 400
    }
    save_output_param {
      output_directory: "/home/dong/Downloads/caffe-ssd/my_detection/myout"
      output_name_prefix: "comp4_det_test_"
      output_format: "VOC"
      label_map_file: "/home/dong/Downloads/caffe-ssd/my_detection/labelmap_voc.prototxt"
      name_size_file: "/home/dong/Downloads/caffe-ssd/my_detection/test_name_size.txt"
      num_test_image: 4952
    }
    code_type: CENTER_SIZE
    keep_top_k: 200
    confidence_threshold: 0.00999999977648
  }
}

test_name_size.txt,labelmap_voc.prototxt复制到自己文件路径里。

命令行运行,

python my_detection/detect.py

在这里插入图片描述

ref

https://www.jianshu.com/p/109e30491ec4

https://blog.csdn.net/u013738531/article/details/56678247

https://blog.csdn.net/lilai619/article/details/53791420

猜你喜欢

转载自blog.csdn.net/qq_35608277/article/details/84981191
今日推荐