1. 程式人生 > >caffe-SSD 安裝、訓練、SSD測試(ubuntu18.04+cuda9.0+openvc3.4)

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