caffe学习笔记12 -- R-CNN detection

[Caffe]:关于caffe新手入门 Caffe的几个重要文件用了这么久Caffe都没好好写过一篇新手入门的博客,最近应实验室小师妹要求,打算写一篇简单、快熟入门的科普文。 利用Caffe进行深度神经网络训练第一步需要搞懂几个重要文件: solver.prototxt train_val.prototxt train.sh 接下来我们按顺序一个个说明。solver.prototxtsolver这个文件主要存放模型训练所用到的一些超参数 阅读详情

这是caffe文档中Notebook Examples的倒数第二个例子,链接地址http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/detection.ipynb

这个例子用R-CNN做目标检测。


R-CNN是一个先进的目标检测模型,它通过微调caffe模型提供分类区域。对于R-CNN系统和模型的详细介绍,参考

Rich feature hierarchies for accurate object detection and semantic segmentation. Ross Girshick, Jeff Donahue, Trevor Darrell, Jitendra Malik. CVPR 2014.Arxiv 2013.

在本例中,预训练模型基于ImageNet数据集,在并在ILSVRC13上进行微调,输出200个检测分类的得分。需要注意的是:本例中一个原始数据对应所有SVM分类的得分,没有概率校准和类间比较。本例中使用现成的模型只是为了简便,并非完整的R-CNN模型


现在,来检测图caffe-master/examples/images/fish-bike.jpg

首先,需要做一些准备工作:

i. 安装matlab, 具体安装过程参考:http://blog.youkuaiyun.com/thystar/article/details/50720691

ii. 添加matlab安装路径,sudo gedit ~/.bashrc, 在文本最后添加:export PATH="/home/sindyz/software/matlab2014/bin":$PATH (我的安装路径)保存后需要重启电脑,要说明的是,这一步是必要的,否则运行时会出现:OSError: [Errno 2] No such file or directory错误。

iii. 下载Selective Search文件,下载地址:https://github.com/sergeyk/selective_search_ijcv_with_python,用于检测候选框,关于Selective Search的算法介绍,参考:http://koen.me/research/selectivesearch/,下载完成后,解压,在matlab下运行demo.m, 无报错信息关闭即可,需要注意的是,如果这个文件不在$CAFFE-ROOT/python目录下,需要将其添加到PYTHONPATH路径中,我的是:export PYTHONPATH=/home/sindyz/code/matlabCode/selective_search_ijcv_with_python/:$PYTHONPATH。(按自己的情况添加)

完成上述步骤后,还有几处需要注意和修改的地方:

  • 在Selective Search文件目录下运行python selective_search.py,看看是否由报错信息,一般来说,如果你添加好了matlab路径,这里不会出什么问题。
  • 修改$CAFFE-ROOT/python/caffe/detector.py中第86行左右:

    predictions = out[self.outputs[0]].squeeze(axis=(2, 3)) 改为 

    predictions = out[self.outputs[0]].squeeze(),否则会报出ValueError: 'axis' entry 2 is out of bounds (-2, 2)错误

  • 修改$CAFFE-ROOT/python/caffe/detector.py中114行左右

    import selective_search_ijcv_with_python as selective_search

    改为

    import selective_search,因为在Selective Search文件目录下,只有selective_search.py模块,否则会出现模块找不到的错误

OK,现在可以开心的运行R-CNN这个例子了。

1. 更改目录,导入相应的包

import os
caffe_root = '/home/sindyz/caffe-master/'
os.chdir(caffe_root)
import sys
sys.path.insert(0,'./python')
2. 创建临时目录,导入检测样本

! mkdir -p _temp
! echo examples/images/fish-bike.jpg > _temp/det_input.txt

3. 运行selective_search提取候选框,调用Caffe进行分类预测。运行GPU模式

! python/detect.py --crop_mode=selective_search --pretrained_model=models/bvlc_reference_rcnn_ilsvrc13/bvlc_reference_rcnn_ilsvrc13.caffemodel --model_def=models/bvlc_reference_rcnn_ilsvrc13/deploy.prototxt --gpu --raw_scale=255 _temp/det_input.txt _temp/det_output.h5

输出如下内容:

GPU mode
WARNING: Logging before InitGoogleLogging() is written to STDERR
I0608 10:32:38.067106  6131 net.cpp:42] Initializing net from parameters: 
name: "R-CNN-ilsvrc13"
input: "data"
input_dim: 10
input_dim: 3
input_dim: 227
input_dim: 227
state {
  phase: TEST
}
layer {
  name: "conv1"
  type: "Convolution"
  bottom: "data"
  top: "conv1"
  convolution_param {
    num_output: 96
    kernel_size: 11
    stride: 4
  }
}
layer {
  name: "relu1"
  type: "ReLU"
  bottom: "conv1"
  top: "conv1"
}
layer {
  name: "pool1"
  type: "Pooling"
  bottom: "conv1"
  top: "pool1"
  pooling_param {
    pool: MAX
    kernel_size: 3
    stride: 2
  }
}
layer {
  name: "norm1"
  type: "LRN"
  bottom: "pool1"
  top: "norm1"
  lrn_param {
    local_size: 5
    alpha: 0.0001
    beta: 0.75
  }
}
layer {
  name: "conv2"
  type: "Convolution"
  bottom: "norm1"
  top: "conv2"
  convolution_param {
    num_output: 256
    pad: 2
    kernel_size: 5
    group: 2
  }
}
layer {
  name: "relu2"
  type: "ReLU"
  bottom: "conv2"
  top: "conv2"
}
layer {
  name: "pool2"
  type: "Pooling"
  bottom: "conv2"
  top: "pool2"
  pooling_param {
    pool: MAX
    kernel_size: 3
    stride: 2
  }
}
layer {
  name: "norm2"
  type: "LRN"
  bottom: "pool2"
  top: "norm2"
  lrn_param {
    local_size: 5
    alpha: 0.0001
    beta: 0.75
  }
}
layer {
  name: "conv3"
  type: "Convolution"
  bottom: "norm2"
  top: "conv3"
  convolution_param {
    num_output: 384
    pad: 1
    kernel_size: 3
  }
}
layer {
  name: "relu3"
  type: "ReLU"
  bottom: "conv3"
  top: "conv3"
}
layer {
  name: "conv4"
  type: "Convolution"
  bottom: "conv3"
  top: "conv4"
  convolution_param {
    num_output: 384
    pad: 1
    kernel_size: 3
    group: 2
  }
}
layer {
  name: "relu4"
  type: "ReLU"
  bottom: "conv4"
  top: "conv4"
}
layer {
  name: "conv5"
  type: "Convolution"
  bottom: "conv4"
  top: "conv5"
  convolution_param {
    num_output: 256
    pad: 1
    kernel_size: 3
    group: 2
  }
}
layer {
  name: "relu5"
  type: "ReLU"
  bottom: "conv5"
  top: "conv5"
}
layer {
  name: "pool5"
  type: "Pooling"
  bottom: "conv5"
  top: "pool5"
  pooling_param {
    pool: MAX
    kernel_size: 3
    stride: 2
  }
}
layer {
  name: "fc6"
  type: "InnerProduct"
  bottom: "pool5"
  top: "fc6"
  inner_product_param {
    num_output: 4096
  }
}
layer {
  name: "relu6"
  type: "ReLU"
  bottom: "fc6"
  top: "fc6"
}
layer {
  name: "drop6"
  type: "Dropout"
  bottom: "fc6"
  top: "fc6"
  dropout_param {
    dropout_ratio: 0.5
  }
}
layer {
  name: "fc7"
  type: "InnerProduct"
  bottom: "fc6"
  top: "fc7"
  inner_product_param {
    num_output: 4096
  }
}
layer {
  name: "relu7"
  type: "ReLU"
  bottom: "fc7"
  top: "fc7"
}
layer {
  name: "drop7"
  type: "Dropout"
  bottom: "fc7"
  top: "fc7"
  dropout_param {
    dropout_ratio: 0.5
  }
}
layer {
  name: "fc-rcnn"
  type: "InnerProduct"
  bottom: "fc7"
  top: "fc-rcnn"
  inner_product_param {
    num_output: 200
  }
}
I0608 10:32:38.067556  6131 net.cpp:370] Input 0 -> data
I0608 10:32:38.067576  6131 layer_factory.hpp:74] Creating layer conv1
I0608 10:32:38.067585  6131 net.cpp:90] Creating Layer conv1
I0608 10:32:38.067589  6131 net.cpp:410] conv1 <- data
I0608 10:32:38.067595  6131 net.cpp:368] conv1 -> conv1
I0608 10:32:38.067603  6131 net.cpp:120] Setting up conv1
I0608 10:32:38.108999  6131 net.cpp:127] Top shape: 10 96 55 55 (2904000)
I0608 10:32:38.109035  6131 layer_factory.hpp:74] Creating layer relu1
I0608 10:32:38.109048  6131 net.cpp:90] Creating Layer relu1
I0608 10:32:38.109055  6131 net.cpp:410] relu1 <- conv1
I0608 10:32:38.109063  6131 net.cpp:357] relu1 -> conv1 (in-place)
I0608 10:32:38.109076  6131 net.cpp:120] Setting up relu1
I0608 10:32:38.109233  6131 net.cpp:127] Top shape: 10 96 55 55 (2904000)
I0608 10:32:38.109244  6131 layer_factory.hpp:74] Creating layer pool1
I0608 10:32:38.109257  6131 net.cpp:90] Creating Layer pool1
I0608 10:32:38.109263  6131 net.cpp:410] pool1 <- conv1
I0608 10:32:38.109269  6131 net.cpp:368] pool1 -> pool1
I0608 10:32:38.109277  6131 net.cpp:120] Setting up pool1
I0608 10:32:38.109311  6131 net.cpp:127] Top shape: 10 96 27 27 (699840)
I0608 10:32:38.109318  6131 layer_factory.hpp:74] Creating layer norm1
I0608 10:32:38.109325  6131 net.cpp:90] Creating Layer norm1
I0608 10:32:38.109329  6131 net.cpp:410] norm1 <- pool1
I0608 10:32:38.109335  6131 net.cpp:368] norm1 -> norm1
I0608 10:32:38.109341  6131 net.cpp:120] Setting up norm1
I0608 10:32:38.109349  6131 net.cpp:127] Top shape: 10 96 27 27 (699840)
I0608 10:32:38.109352  6131 layer_factory.hpp:74] Creating layer conv2
I0608 10:32:38.109360  6131 net.cpp:90] Creating Layer conv2
I0608 10:32:38.109364  6131 net.cpp:410] conv2 <- norm1
I0608 10:32:38.109370  6131 net.cpp:368] conv2 -> conv2
I0608 10:32:38.109376  6131 net.cpp:120] Setting up conv2
I0608 10:32:38.109931  6131 net.cpp:127] Top shape: 10 256 27 27 (1866240)
I0608 10:32:38.109947  6131 layer_factory.hpp:74] Creating layer relu2
I0608 10:32:38.109954  6131 net.cpp:90] Creating Layer relu2
I0608 10:32:38.109959  6131 net.cpp:410] relu2 <- conv2
I0608 10:32:38.109966  6131 net.cpp:357] relu2 -> conv2 (in-place)
I0608 10:32:38.109972  6131 net.cpp:120] Setting up relu2
I0608 10:32:38.110002  6131 net.cpp:127] Top shape: 10 256 27 27 (1866240)
I0608 10:32:38.110008  6131 layer_factory.hpp:74] Creating layer pool2
I0608 10:32:38.110014  6131 net.cpp:90] Creating Layer pool2
I0608 10:32:38.110018  6131 net.cpp:410] pool2 <- conv2
I0608 10:32:38.110024  6131 net.cpp:368] pool2 -> pool2
I0608 10:32:38.110030  6131 net.cpp:120] Setting up pool2
I0608 10:32:38.110136  6131 net.cpp:127] Top shape: 10 256 13 13 (432640)
I0608 10:32:38.110144  6131 layer_factory.hpp:74] Creating layer norm2
I0608 10:32:38.110152  6131 net.cpp:90] Creating Layer norm2
I0608 10:32:38.110157  6131 net.cpp:410] norm2 <- pool2
I0608 10:32:38.110162  6131 net.cpp:368] norm2 -> norm2
I0608 10:32:38.110168  6131 net.cpp:120] Setting up norm2
I0608 10:32:38.110175  6131 net.cpp:127] Top shape: 10 256 13 13 (432640)
I0608 10:32:38.110179  6131 layer_factory.hpp:74] Creating layer conv3
I0608 10:32:38.110187  6131 net.cpp:90] Creating Layer conv3
I0608 10:32:38.110191  6131 net.cpp:410] conv3 <- norm2
I0608 10:32:38.110198  6131 net.cpp:368] conv3 -> conv3
I0608 10:32:38.110203  6131 net.cpp:120] Setting up conv3
I0608 10:32:38.111160  6131 net.cpp:127] Top shape: 10 384 13 13 (648960)
I0608 10:32:38.111176  6131 layer_factory.hpp:74] Creating layer relu3
I0608 10:32:38.111183  6131 net.cpp:90] Creating Layer relu3
I0608 10:32:38.111189  6131 net.cpp:410] relu3 <- conv3
I0608 10:32:38.111194  6131 net.cpp:357] relu3 -> conv3 (in-place)
I0608 10:32:38.111202  6131 net.cpp:120] Setting up relu3
I0608 10:32:38.111232  6131 net.cpp:127] Top shape: 10 384 13 13 (648960)
I0608 10:32:38.111238  6131 layer_factory.hpp:74] Creating layer conv4
I0608 10:32:38.111243  6131 net.cpp:90] Creating Layer conv4
I0608 10:32:38.111248  6131 net.cpp:410] conv4 <- conv3
I0608 10:32:38.111253  6131 net.cpp:368] conv4 -> conv4
I0608 10:32:38.111260  6131 net.cpp:120] Setting up conv4
I0608 10:32:38.112344  6131 net.cpp:127] Top shape: 10 384 13 13 (648960)
I0608 10:32:38.112357  6131 layer_factory.hpp:74] Creating layer relu4
I0608 10:32:38.112365  6131 net.cpp:90] Creating Layer relu4
I0608 10:32:38.112370  6131 net.cpp:410] relu4 <- conv4
I0608 10:32:38.112375  6131 net.cpp:357] relu4 -> conv4 (in-place)
I0608 10:32:38.112381  6131 net.cpp:120] Setting up relu4
I0608 10:32:38.112411  6131 net.cpp:127] Top shape: 10 384 13 13 (648960)
I0608 10:32:38.112416  6131 layer_factory.hpp:74] Creating layer conv5
I0608 10:32:38.112422  6131 net.cpp:90] Creating Layer conv5
I0608 10:32:38.112427  6131 net.cpp:410] conv5 <- conv4
I0608 10:32:38.112432  6131 net.cpp:368] conv5 -> conv5
I0608 10:32:38.112439  6131 net.cpp:120] Setting up conv5
I0608 10:32:38.113263  6131 net.cpp:127] Top shape: 10 256 13 13 (432640)
I0608 10:32:38.113279  6131 layer_factory.hpp:74] Creating layer relu5
I0608 10:32:38.113286  6131 net.cpp:90] Creating Layer relu5
I0608 10:32:38.113291  6131 net.cpp:410] relu5 <- conv5
I0608 10:32:38.113297  6131 net.cpp:357] relu5 -> conv5 (in-place)
I0608 10:32:38.113303  6131 net.cpp:120] Setting up relu5
I0608 10:32:38.113333  6131 net.cpp:127] Top shape: 10 256 13 13 (432640)
I0608 10:32:38.113339  6131 layer_factory.hpp:74] Creating layer pool5
I0608 10:32:38.113347  6131 net.cpp:90] Creating Layer pool5
I0608 10:32:38.113350  6131 net.cpp:410] pool5 <- conv5
I0608 10:32:38.113356  6131 net.cpp:368] pool5 -> pool5
I0608 10:32:38.113363  6131 net.cpp:120] Setting up pool5
I0608 10:32:38.113502  6131 net.cpp:127] Top shape: 10 256 6 6 (92160)
I0608 10:32:38.113520  6131 layer_factory.hpp:74] Creating layer fc6
I0608 10:32:38.113528  6131 net.cpp:90] Creating Layer fc6
I0608 10:32:38.113533  6131 net.cpp:410] fc6 <- pool5
I0608 10:32:38.113538  6131 net.cpp:368] fc6 -> fc6
I0608 10:32:38.113545  6131 net.cpp:120] Setting up fc6
I0608 10:32:38.140440  6131 net.cpp:127] Top shape: 10 4096 (40960)
I0608 10:32:38.140478  6131 layer_factory.hpp:74] Creating layer relu6
I0608 10:32:38.140492  6131 net.cpp:90] Creating Layer relu6
I0608 10:32:38.140498  6131 net.cpp:410] relu6 <- fc6
I0608 10:32:38.140506  6131 net.cpp:357] relu6 -> fc6 (in-place)
I0608 10:32:38.140516  6131 net.cpp:120] Setting up relu6
I0608 10:32:38.140576  6131 net.cpp:127] Top shape: 10 4096 (40960)
I0608 10:32:38.140583  6131 layer_factory.hpp:74] Creating layer drop6
I0608 10:32:38.140589  6131 net.cpp:90] Creating Layer drop6
I0608 10:32:38.140594  6131 net.cpp:410] drop6 <- fc6
I0608 10:32:38.140599  6131 net.cpp:357] drop6 -> fc6 (in-place)
I0608 10:32:38.140605  6131 net.cpp:120] Setting up drop6
I0608 10:32:38.140611  6131 net.cpp:127] Top shape: 10 4096 (40960)
I0608 10:32:38.140616  6131 layer_factory.hpp:74] Creating layer fc7
I0608 10:32:38.140622  6131 net.cpp:90] Creating Layer fc7
I0608 10:32:38.140630  6131 net.cpp:410] fc7 <- fc6
I0608 10:32:38.140636  6131 net.cpp:368] fc7 -> fc7
I0608 10:32:38.140643  6131 net.cpp:120] Setting up fc7
I0608 10:32:38.153045  6131 net.cpp:127] Top shape: 10 4096 (40960)
I0608 10:32:38.153095  6131 layer_factory.hpp:74] Creating layer relu7
I0608 10:32:38.153105  6131 net.cpp:90] Creating Layer relu7
I0608 10:32:38.153112  6131 net.cpp:410] relu7 <- fc7
I0608 10:32:38.153120  6131 net.cpp:357] relu7 -> fc7 (in-place)
I0608 10:32:38.153129  6131 net.cpp:120] Setting up relu7
I0608 10:32:38.153200  6131 net.cpp:127] Top shape: 10 4096 (40960)
I0608 10:32:38.153206  6131 layer_factory.hpp:74] Creating layer drop7
I0608 10:32:38.153214  6131 net.cpp:90] Creating Layer drop7
I0608 10:32:38.153219  6131 net.cpp:410] drop7 <- fc7
I0608 10:32:38.153224  6131 net.cpp:357] drop7 -> fc7 (in-place)
I0608 10:32:38.153231  6131 net.cpp:120] Setting up drop7
I0608 10:32:38.153237  6131 net.cpp:127] Top shape: 10 4096 (40960)
I0608 10:32:38.153242  6131 layer_factory.hpp:74] Creating layer fc-rcnn
I0608 10:32:38.153249  6131 net.cpp:90] Creating Layer fc-rcnn
I0608 10:32:38.153254  6131 net.cpp:410] fc-rcnn <- fc7
I0608 10:32:38.153259  6131 net.cpp:368] fc-rcnn -> fc-rcnn
I0608 10:32:38.153267  6131 net.cpp:120] Setting up fc-rcnn
I0608 10:32:38.154058  6131 net.cpp:127] Top shape: 10 200 (2000)
I0608 10:32:38.154080  6131 net.cpp:194] fc-rcnn does not need backward computation.
I0608 10:32:38.154085  6131 net.cpp:194] drop7 does not need backward computation.
I0608 10:32:38.154090  6131 net.cpp:194] relu7 does not need backward computation.
I0608 10:32:38.154095  6131 net.cpp:194] fc7 does not need backward computation.
I0608 10:32:38.154100  6131 net.cpp:194] drop6 does not need backward computation.
I0608 10:32:38.154105  6131 net.cpp:194] relu6 does not need backward computation.
I0608 10:32:38.154110  6131 net.cpp:194] fc6 does not need backward computation.
I0608 10:32:38.154115  6131 net.cpp:194] pool5 does not need backward computation.
I0608 10:32:38.154129  6131 net.cpp:194] relu5 does not need backward computation.
I0608 10:32:38.154134  6131 net.cpp:194] conv5 does not need backward computation.
I0608 10:32:38.154139  6131 net.cpp:194] relu4 does not need backward computation.
I0608 10:32:38.154145  6131 net.cpp:194] conv4 does not need backward computation.
I0608 10:32:38.154150  6131 net.cpp:194] relu3 does not need backward computation.
I0608 10:32:38.154155  6131 net.cpp:194] conv3 does not need backward computation.
I0608 10:32:38.154160  6131 net.cpp:194] norm2 does not need backward computation.
I0608 10:32:38.154165  6131 net.cpp:194] pool2 does not need backward computation.
I0608 10:32:38.154170  6131 net.cpp:194] relu2 does not need backward computation.
I0608 10:32:38.154175  6131 net.cpp:194] conv2 does not need backward computation.
I0608 10:32:38.154180  6131 net.cpp:194] norm1 does not need backward computation.
I0608 10:32:38.154193  6131 net.cpp:194] pool1 does not need backward computation.
I0608 10:32:38.154198  6131 net.cpp:194] relu1 does not need backward computation.
I0608 10:32:38.154203  6131 net.cpp:194] conv1 does not need backward computation.
I0608 10:32:38.154208  6131 net.cpp:235] This network produces output fc-rcnn
I0608 10:32:38.154220  6131 net.cpp:482] Collecting Learning Rate and Weight Decay.
I0608 10:32:38.154227  6131 net.cpp:247] Network initialization done.
I0608 10:32:38.154232  6131 net.cpp:248] Memory required for data: 62425920
E0608 10:32:38.221285  6131 upgrade_proto.cpp:618] Attempting to upgrade input file specified using deprecated V1LayerParameter: models/bvlc_reference_rcnn_ilsvrc13/bvlc_reference_rcnn_ilsvrc13.caffemodel
I0608 10:32:38.324671  6131 upgrade_proto.cpp:626] Successfully upgraded file specified using deprecated V1LayerParameter
Loading input...
selective_search_rcnn({'/home/ouxinyu/caffe-master/examples/images/fish-bike.jpg'}, '/tmp/tmpu85WGa.mat')
Processed 1570 windows in 17.131 s.
/usr/lib/python2.7/dist-packages/pandas/io/pytables.py:2487: PerformanceWarning: 
your performance may suffer as PyTables will pickle object types that it cannot
map directly to c-types [inferred_type->mixed,key->block1_values] [items->['prediction']]

  warnings.warn(ws, PerformanceWarning)
Saved to _temp/det_output.h5 in 0.025 s.

4. 运行后输出的文件名,选择的窗口,检测得分存放在~/_temp/det_outpu.h5文件中,查看结果:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_hdf('_temp/det_output.h5', 'df')
print(df.shape)
print(df.iloc[0])

输出:

(1570, 5)
prediction    [-2.62247, -2.84579, -2.85122, -3.20838, -1.94...
ymin                                                     79.846
xmin                                                       9.62
ymax                                                     246.31
xmax                                                    339.624
Name: /home/sindyz/caffe-master/examples/images/fish-bike.jpg, dtype: object

Selective Search选出了1570个区域,作为R-CNN的输入,图与图的候选框的数量随图像的内容和大小不同而改变,也就是说:selective search不是尺度不变的。

通常,detect.py在运行大量图片时是非常高效的:首先,对所有图片提取候选框,用GPU批处理这些窗口,输出结果。只要在images_file中列出图像名,就可以批处理了。

仅管本例中只给出了Imagenet的R-CNN检测,但是detect.py可以适应不同caffe模型的输入维度,批处理规模及输出类别。你可以根据需要选择模型定义和预处理模型,参考detect.py --help根据数据选择参数。

5. 加载ILSVRC13的检测类别名称,做预测的DataFrame, 注意,通过./data/ilsvrc12/get_ilsvrc12_aux.sh获取数据

with open('../data/ilsvrc12/det_synset_words.txt') as f:
    labels_df = pd.DataFrame([
        {
            'synset_id': l.strip().split(' ')[0],
            'name': ' '.join(l.strip().split(' ')[1:]).split(',')[0]
        }
        for l in f.readlines()
    ])
labels_df.sort('synset_id')
predictions_df = pd.DataFrame(np.vstack(df.prediction.values), columns=labels_df['name'])
print(predictions_df.iloc[0])

输出:

name
accordion      -2.622471
airplane       -2.845789
ant            -2.851220
antelope       -3.208377
apple          -1.949950
armadillo      -2.472936
artichoke      -2.201685
axe            -2.327404
baby bed       -2.737924
backpack       -2.176764
bagel          -2.681061
balance beam   -2.722538
banana         -2.390628
band aid       -1.598909
banjo          -2.298197
...
trombone        -2.582361
trumpet         -2.352853
turtle          -2.360860
tv or monitor   -2.761042
unicycle        -2.218468
vacuum          -1.907718
violin          -2.757080
volleyball      -2.723690
waffle iron     -2.418540
washer          -2.408994
water bottle    -2.174899
watercraft      -2.837426
whale           -3.120339
wine bottle     -2.772961
zebra           -2.742914
Name: 0, Length: 200, dtype: float32

6. 查看激活值并可视化

plt.gray()
plt.matshow(predictions_df.values)
plt.xlabel('Classes')
plt.ylabel('Windows')


7. 取得分最大值,并输出

max_s = predictions_df.max(0)
max_s.sort(ascending=False)
print(max_s[:10])
输出

name
person          1.835771
bicycle         0.866109
unicycle        0.057079
motorcycle     -0.006122
banjo          -0.028208
turtle         -0.189833
electric fan   -0.206787
cart           -0.214237
lizard         -0.393519
helmet         -0.477942
dtype: float32

8. 检测结果最高的是人和自行车,检测还需要定位,于是,选择得分最高的人和自行车来定位

# Find, print, and display the top detections: person and bicycle.
i = predictions_df['person'].argmax()
j = predictions_df['bicycle'].argmax()

# Show top predictions for top detection.
f = pd.Series(df['prediction'].iloc[i], index=labels_df['name'])
print('Top detection:')
print(f.order(ascending=False)[:5])
print('')

# Show top predictions for second-best detection.
f = pd.Series(df['prediction'].iloc[j], index=labels_df['name'])
print('Second-best detection:')
print(f.order(ascending=False)[:5])

# Show top detection in red, second-best top detection in blue.
im = plt.imread('examples/images/fish-bike.jpg')
plt.imshow(im)
currentAxis = plt.gca()

det = df.iloc[i]
coords = (det['xmin'], det['ymin']), det['xmax'] - det['xmin'], det['ymax'] - det['ymin']
currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor='r', linewidth=5))

det = df.iloc[j]
coords = (det['xmin'], det['ymin']), det['xmax'] - det['xmin'], det['ymax'] - det['ymin']
currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor='b', linewidth=5))
输出
Top detection:
name
person             1.835771
swimming trunks   -1.150371
rubber eraser     -1.231106
turtle            -1.266037
plastic bag       -1.303266
dtype: float32

Second-best detection:
name
bicycle     0.866109
unicycle   -0.359140
scorpion   -0.811621
lobster    -0.982891
lamp       -1.096809
dtype: float32


9. 拿所有的自行车检测,并用NMS避免窗口重叠。

def nms_detections(dets, overlap=0.3):
    """
    Non-maximum suppression: Greedily select high-scoring detections and
    skip detections that are significantly covered by a previously
    selected detection.

    This version is translated from Matlab code by Tomasz Malisiewicz,
    who sped up Pedro Felzenszwalb's code.

    Parameters
    ----------
    dets: ndarray
        each row is ['xmin', 'ymin', 'xmax', 'ymax', 'score']
    overlap: float
        minimum overlap ratio (0.3 default)

    Output
    ------
    dets: ndarray
        remaining after suppression.
    """
    x1 = dets[:, 0]
    y1 = dets[:, 1]
    x2 = dets[:, 2]
    y2 = dets[:, 3]
    ind = np.argsort(dets[:, 4])

    w = x2 - x1
    h = y2 - y1
    area = (w * h).astype(float)

    pick = []
    while len(ind) > 0:
        i = ind[-1]
        pick.append(i)
        ind = ind[:-1]

        xx1 = np.maximum(x1[i], x1[ind])
        yy1 = np.maximum(y1[i], y1[ind])
        xx2 = np.minimum(x2[i], x2[ind])
        yy2 = np.minimum(y2[i], y2[ind])

        w = np.maximum(0., xx2 - xx1)
        h = np.maximum(0., yy2 - yy1)

        wh = w * h
        o = wh / (area[i] + area[ind] - wh)

        ind = ind[np.nonzero(o <= overlap)[0]]

    return dets[pick, :]

scores = predictions_df['bicycle']
windows = df[['xmin', 'ymin', 'xmax', 'ymax']].values
dets = np.hstack((windows, scores[:, np.newaxis]))
nms_dets = nms_detections(dets)

10. 显示排名前3的NMS处理过的自行车,注意得分最高的红色的框与其他框之间的差异

plt.imshow(im)
currentAxis = plt.gca()
colors = ['r', 'b', 'y']
for c, det in zip(colors, nms_dets[:3]):
    currentAxis.add_patch(
        plt.Rectangle((det[0], det[1]), det[2]-det[0], det[3]-det[1],
        fill=False, edgecolor=c, linewidth=5)
    )
print 'scores:', nms_dets[:3, 4]


自行车的检测是个简单的实例,因为在训练数据中由这个类别的数据,但是人的结果是一个真正的检测因为训练数据中没有这个类别的数据。

下面,你也可以用自己的图像做检测。

11. 删除_temp目录

!rm -rf _temp



参考资料:

http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/detection.ipynb

http://nbviewer.jupyter.org/github/ouxinyu/ouxinyu.github.io/blob/master/MyCodes/caffe-master/detection.ipynb


caffe学习笔记1-7-完整版-薛开宇 立即下载

相关推荐

caffe 学习笔记

CAFFE 学习笔记详细翻译了CAFFE 官网tutorial中给出的例子,有每一步的操作过程,和对应的讲解。适合初学者上手

Caffe版Faster R-CNN可视化——网络模型,图像特征,Loss图,PR曲线

可视化网络模型   Caffe目前有两种常用的可视化模型方式: 使用Netscope在线可视化 Caffe代码包内置的draw_net.py文件可以可视化网络模型 Netscope能可视化神经网络体系结构(或技术上说,Netscope能可视化任何有向无环图)。目前Netscope能可视化Caffe的prototxt 文件。网址为: ethereon.github.io/netscope/#/...

qq_39501363的博客 734

caffe学习笔记完整版

以具体的实例讲解caffe的使用(附代码),包括MNIST、CIFAR10在caffe的应用,可视化卷积层,如何训练自己的网络等。

Caffe学习系列——Faster-RCNN训练自己的数据集

2016-10-23 Deep Learning►Caffe Caffe学习系列——6使用Faster-RCNN进行目标检测 Contents 1. 配置与运行Demo 1.1. 1.配置、编译与安装环境1.2. 2.运行demo1.3. 3.训练PASCAL VOC 2007的数据集1.4. 4.遇到的问题 2. 使用Faster-RCNN训

CV_adventurer的博客 3万+

caffe学习笔记全系列

caffe学习笔记全系列

3D模型文件格式全解析:从STL到glTF,10种主流格式与转换实战指南

在三维数字内容创作与工程制造领域,3D模型文件格式是数据交换与协作的基石。其核心原理在于以不同的数据结构(如三角网格、NURBS曲面、边界表示等)对三维物体的几何、外观及场景信息进行编码。理解这些格式的技术特性,对于保障数据完整性、提升工作流效率具有关键价值,广泛应用于3D打印、游戏开发、影视动画及工业设计等场景。例如,面向增材制造的STL格式以其极简的三角面片结构成为行业通用语,而支持丰富材质与动画的FBX格式则在影视游戏管线中扮演核心角色。本文聚焦于STL、OBJ、FBX、3MF、STEP等10种主流格

weixin_28520495的博客 356

【caffe-MATLAB】自己编译faster-rcnn的MATLAB版本

今天在自己的电脑上编译MATLAB版本的faster-RCNN代码,将过程在这作一记录。 1.我的环境:Windows10 ,VS2013 , MATLAB2017a ,CUDA7.5 首先下载作者的源码:https://github.com/ShaoqingRen/faster_rcnn [html] view plain copy ### Preparat

浩瀚之水的专栏 2450

dell r630 配置raid_DELL服务器RAID配置图文教程

名称解释:Disk Group:磁盘组,这里相当于是阵列,例如配置了一个RAID5,就是一个磁盘组VD(Virtual Disk): 虚拟磁盘,虚拟磁盘可以不使用阵列的全部容量,也就是说一个磁盘组可以分为多个VDPD(Physical Disk): 物理磁盘HS:Hot Spare 热备Mgmt:管理【一】创建逻辑磁盘1、按照屏幕下方的虚拟磁盘管理器提示,在VD Mgmt菜单(可以通过CTRL+P...

weixin_33253741的博客 3510

Caffe基础介绍

Caffe基础介绍!

网络资源是无限的 4万+

本地快速部署谷歌开放模型Gemma教程(基于Ollama)

谷歌最近发布了新一代开源AI模型Gemma,此次发布的 Gemma 相比自家的 Gemini 更加轻量级,模型权重也一并开源。不仅可以在笔记本电脑上运行,而且还免费可商用,支持中文。运行速度飞快。

特立独行的博客 6716

数控系统(CNC)系列:Fanuc 31i-B_(5).基本操作与编程

Fanuc 31i-B 系统使用 G 代码和 M 代码进行编程。G 代码主要用于控制机床的运动,M 代码用于控制辅助功能,如冷却液开关、主轴启动等。G 代码:用于指定机床的运动方式。例如,G00 用于快速定位,G01 用于直线插补,G02 用于顺时针圆弧插补,G03 用于逆时针圆弧插补。M 代码:用于控制机床的辅助功能。例如,M03 用于启动主轴顺时针旋转,M05 用于停止主轴,M08 用于开启冷却液,M09 用于关闭冷却液。

2401_87715305的博客 1766

ssd网络详解之detection output layer

ssd网络详解之detection out layer 本文原创,转载请引用 闲话少说,本文基本结构:首先介绍detection out 这一层的基本理解,之后给出ssd所有代码的详细注释,最后给出caffe中该层各个参数的定义和默认值。 detection out layer是ssd网络最后一层,用于整合预选框、预选框偏移以及得分三项结果,最终输出满足条件的目标检测框、目标的label和得...

dan_teng的博客 1万+

AI agents在公司财务报表分析中的应用

在当今竞争激烈的商业环境中,公司财务报表分析对于企业的决策制定、风险评估、战略规划等方面起着至关重要的作用。传统的财务报表分析方法往往依赖于人工操作,存在效率低下、容易出错、难以处理海量数据等问题。而AI agents作为人工智能领域的重要成果,具有自动化、智能化、高效性等特点,能够为财务报表分析带来新的突破和变革。

SuperAGI2025 1611

caffe样例_R-CNN detection基于Ubuntu_Caffe

R-CNN detection1.背景R-CNN是通过Caffe微调模型拟分类区域的检测器,详细内容可以参考项目网址和论文: Rich feature hierarchies for accurate object detection and semantic segmentation. Ross Girshick, Jeff Donahue, Trevor Darrell, Jitendra

dawin_2008的博客 755

RK AVS双目融合记录

NOTE] 调试平台双目avs融合调试,需要先保证两个摄像头能正常出图同时出流。使用默认工具测试vi->avs->venc通路是否正常,-a可指定isp效果文件需要开启CONFIG_VIDEO_ROCKCHIP_AVSP和CONFIG_VIDEO_ROCKCHIP_FEC,dts中使能。

mangofu的博客 104

QT实现MQTT服务端(附完整源码)

QT实现MQTT服务端(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 1253

(目标检测)Faster R-CNN 论文解读+复现

Faster R-CNN xyang 声明:本篇文章借用了他人理解,如有侵权,请联系,另如需转载,请注明出处 关于最新最全的目标检测论文,可以查看awesome-object-detection 《Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks》 NIPS 2015 arxiv: ...

Bryce1010's Blog 5555

ADT MCP Server 把 ABAP 开发带进 Agent 模式

今天讨论 ADT MCP Server,不能只把它看成 Visual Studio Code 里多出来的一个开关。它真正有意思的地方,在于它把 ABAP 后端开发里那些原本需要手工点击、手工创建、手工激活、手工查服务元数据的动作,包装成一组可以被 GitHub Copilot 这类 coding agent 调用的工具。SAP 在 RAP130 练习里把它描述为运行在 ADT for Visual Studio Code 扩展内部的本地 HTTP Server,它实现的是 Model Context Pro

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 184

Rich feature hierarchies for accurate object detection and semantic segmentation 笔记

CVPR2014   物体检测算法,R-CNN,即Regions with CNN features。该论文采用的方法在PASCAL VOC 2010上mAP达到53.7%,比之前传统的方法要高很多。   论文总体思路可以分成3个步骤: 1.     产生大约2000个region proposals 2.     对这些region proposals进行CNN训练,提取特征向量

hjl240的专栏 1074

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

RCNN学习笔记(11):R-FCN: Object Detection via Region-based Fully Convolutional Networks

转自:http://blog.youkuaiyun.com/shadow_guo/article/details/51767036 作者代季峰 1,14年毕业的清华博士到微软亚洲研究院的视觉计算组,CVPR 16 两篇一作的会议主持人同时公布了源码~ 2 1. 简介 物体检测的深度网络按感兴趣区域 (RoI) 池化层分为两大主流:共享计算的全卷积子网络 (每个子网络与 RoI 无关) 和

Focusing on your own Mind :) -> 站在巨人的肩膀上 1万+

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

【深度学习:目标检测】 RCNN学习笔记(11):R-FCN: Object Detection via Region-based Fully Convolutional Networks

转自:http://blog.youkuaiyun.com/shadow_guo/article/details/51767036 作者代季峰1,14年毕业的清华博士到微软亚洲研究院的视觉计算组,CVPR 16 两篇一作的会议主持人同时公布了源码~2 1. 简介 物体检测的深度网络按感兴趣区域 (RoI) 池化层分为两大主流:共享计算的全卷积子网络 (每个子网络与 RoI 无关) 和 不

荪荪的博客 3921

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

目标检测:SSD的multibox_loss_layer和MineHardExamples的理解

SSD(single-shot multibox detector)源码学习笔记SSD是Wei Liu等人去年提出来的一个object detection框架,在PascalVOC上mAP可以超过著名的Faster RCNN,同时速度可以做到实时,简直强无敌。之前用别人的MXNet代码跑过实验,最近需要改进一下算法,所以去翻了一下原作者用Caffe实现的代码。在看代码之前先简述一下SSD的做法:图...

BigCowPeking 3226

项目 | 超强PyTorch目标检测库Detectron2,FaceBook出品

栗子 发自 凹非寺量子位 报道 | 公众号 QbitAIPyTorch目标检测库Detectron2诞生了,Facebook出品。站在初代的肩膀上,它训练比从前更快,功能比从前更全,...

机器学习算法与Python学习 953

SSD源码解读 - detection_output_layer

这段代码是DetectionOut层的实现,表示怎么从PriorBox、loc、conf三个层得到检测框的。 源码如下: detection_output_layer.cpp #include &lt;algorithm&gt; #include &lt;fstream&gt; // NOLINT(readability/streams) #include &lt;map&gt...

wyg1997 3106

caffe学习系列:训练自己的图片集(超详细教程)

学习的caffe的目的,不是简单的做几个练习,而是最终落实到自己的项目或科研中去。因此,本文介绍一下,从自己的原始图片到lmdb数据,再到训练和测试的整个流程。 一、数据的准备     有条件的同学,可以去ImageNet的官网点击打开链接,下载ImageNet图片来训练。但是我没有下载,因为我注册过程中一直出现bug。     我重新找了500张图片来代替,分为大巴车、恐龙、大象、鲜花和马

Cche的博客 6万+
上一篇: caffe学习笔记10 -- Fine-tuning a Pretrained Network for Style Recognitio
下一篇: caffe学习笔记13 -- Setup
thystar
博客等级 码龄17年 407粉丝 151原创
评论 20
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值