Windows下RCNN的使用

RCNN

一种把目标图像分割转化为CNN分类问题进行目标检测的方法。
 
Ross B. Girshick的RCNN使用region proposal(具体用的是Selective Search Koen van de Sande: Segmentation as Selective Search for Object Recognition)来得到有可能得到是object的若干(大概10^3量级)图像局部区域,然后把这些区域分别输入到CNN中,得到区域的feature,再在feature上加上分类器,判断feature对应的区域是属于具体某类object还是背景。当然,RBG还用了区域对应的feature做了针对boundingbox的回归,用来修正预测的boundingbox的位置。RCNN在VOC2007上的mAP是58%左右。

RCNN存在着重复计算的问题(proposal的region有几千个,多数都是互相重叠,重叠部分会被多次重复提取feature),于是RBG借鉴Kaiming He的SPP-net的思路单枪匹马搞出了Fast-RCNN,跟RCNN最大区别就是Fast-RCNN将proposal的region映射到CNN的最后一层conv layer的feature map上,这样一张图片只需要提取一次feature,大大提高了速度,也由于流程的整合以及其他原因,在VOC2007上的mAP也提高到了68%。

探索是无止境的。Fast-RCNN的速度瓶颈在Region proposal上,于是RBG和Kaiming He一帮人将Region proposal也交给CNN来做,提出了Faster-RCNN。Fater-RCNN中的region proposal netwrok实质是一个Fast-RCNN,这个Fast-RCNN输入的region proposal的是固定的(把一张图片划分成n*n个区域,每个区域给出9个不同ratio和scale的proposal),输出的是对输入的固定proposal是属于背景还是前景的判断和对齐位置的修正(regression)。Region proposal network的输出再输入第二个Fast-RCNN做更精细的分类和Boundingbox的位置修正。Fater-RCNN速度更快了,而且用VGG net作为feature extractor时在VOC2007上mAP能到73%。

个人觉得制约RCNN框架内的方法精度提升的瓶颈是将dectection问题转化成了对图片局部区域的分类问题后,不能充分利用图片局部object在整个图片中的context信息。可能RBG也意识到了这一点,所以他最新的一篇文章YOLO)又回到了regression的方法下,这个方法效果很好,在VOC2007上mAP能到63.4%,而且速度非常快,能达到对视频的实时处理(油管视频:),虽然不如Fast-RCNN,但是比传统的实时方法精度提升了太多,而且我觉得还有提升空间。

安装

1.下载https://github.com/sergeyk/selective_search_ijcv_with_python运行demo编译必要的函数,
复制到<python>Libsite-packages中重命名为selective_search_ijcv_with_python
2.下载ImageNet的RCNN的Caffe模型bvlc_reference_rcnn_ilsvrc13.caffemodel和deploy.prototxt
放到<caffe>modelsvlc_reference_rcnn_ilsvrc13文件夹
3.将<caffe>examplesimagesfish-bike.jpg复制到<caffe>Buildx64Releasepycaffe
4.将caffe_ilsvrc12.tar.gz解压到caffe-windowsdatailsvrc12
5.将ilsvrc_2012_mean.npy复制到caffe-windowsBuildx64Releasepycaffecaffeimagenet
4.将caffe_ilsvrc12.tar.gz解压到caffe-windowsdatailsvrc12
5.Cmd到<caffe>Buildx64Releasepycaffe目录运行下面代码(det_input.txt 为pycaffe中需要检测的图片名)

python detect.py 
--crop_mode=selective_search 
--pretrained_model=改成你自己的路径modelsvlc_reference_rcnn_ilsvrc13vlc_reference_rcnn_ilsvrc13.caffemodel 
--model_def=改成你自己的路径modelsvlc_reference_rcnn_ilsvrc13deploy.prototxt 
--gpu 
--raw_scale=255 
C:Users改成你自己Desktopdet_input.txt 
C:Users改成你自己Desktopdet_output.h5

6.如果出现错误ValueError: 'axis' entry 2 is out of bounds [-2, 2)
依据https://github.com/BVLC/caffe/issues/2041
将<caffe>Buildx64Releasepycaffecaffedetector.py第86行的 out[self.outputs[0]].squeeze(axis=(2,3))
修改为 out[self.outputs[0]].squeeze()

7.运行下面python代码获取检测结果

 1 import numpy as np
 2 import pandas as pd
 3 import matplotlib.pyplot as plt
 4 
 5 
 6 df = pd.read_hdf('det_output.h5', 'df')
 7 print(df.shape)
 8 print(df.iloc[0])
 9 with open('acaffe-windowsdatailsvrc12det_synset_words.txt') as f:
10     labels_df = pd.DataFrame([
11         {
12             'synset_id': l.strip().split(' ')[0],
13             'name': ' '.join(l.strip().split(' ')[1:]).split(',')[0]
14         }
15         for l in f.readlines()
16     ])
17 labels_df.sort_values(by='synset_id')# sort('synset_id')
18 predictions_df = pd.DataFrame(np.vstack(df.prediction.values), columns=labels_df['name'])
19 print(predictions_df.iloc[0])
20 
21 max_s = predictions_df.max(0)
22 max_s = max_s.sort_values(ascending=False)
23 
24 # Find, print, and display the top detections: person and bicycle.
25 i = predictions_df[max_s.keys()[0]].argmax()  #person
26 j = predictions_df[max_s.keys()[1]].argmax()  #bicycle
27 
28 # Show top predictions for top detection.
29 f = pd.Series(df['prediction'].iloc[i], index=labels_df['name'])
30 print('Top detection:')
31 print(f.sort_values(ascending=False)[:5])
32 
33 # Show top predictions for second-best detection.
34 f = pd.Series(df['prediction'].iloc[j], index=labels_df['name'])
35 print('Second-best detection:')
36 print(f.sort_values(ascending=False)[:5])
37 
38 # Show top detection in red, second-best top detection in blue.
39 im = plt.imread('acaffe-windowsexamplesimages\fish-bike.jpg')
40 plt.imshow(im)
41 currentAxis = plt.gca()
42 
43 det = df.iloc[i]
44 coords = (det['xmin'], det['ymin']), det['xmax'] - det['xmin'], det['ymax'] - det['ymin']
45 currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor='r', linewidth=5))
46 
47 det = df.iloc[j]
48 coords = (det['xmin'], det['ymin']), det['xmax'] - det['xmin'], det['ymax'] - det['ymin']
49 currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor='b', linewidth=5))
50 plt.show()

输出结果

Top detection:
name
person             1.835771
swimming trunks   -1.150371
rubber eraser     -1.231106
turtle            -1.266038
plastic bag       -1.303266
dtype: float32

Second-best detection:
name
bicycle     0.866110
unicycle   -0.359140
scorpion   -0.811621
lobster    -0.982891
lamp       -1.096809
dtype: float32
 
原文地址:https://www.cnblogs.com/qw12/p/6172119.html