zoukankan      html  css  js  c++  java
  • 使用Faster-Rcnn进行目标检测(实践篇)转载

    文链接:http://blog.csdn.net/gavin__zhou/article/details/52052915

    原理

    上一篇文章,已经说过了,大家可以参考一下,Faster-Rcnn进行目标检测(原理篇)

    实验

    我使用的代码是Python版本的Faster Rcnn,官方也有Matlab版本的,链接如下:

    py-faster-rcnn(python)

    faster-rcnn(matlab)

    环境配置

    按照官方的README进行配置就好,不过在这之前大家还是看下硬件要求吧

    • For training smaller networks (ZF, VGG_CNN_M_1024) a good GPU (e.g., Titan, K20, K40, …) with at least 3G of memory suffices

    • For training Fast R-CNN with VGG16, you’ll need a K40 (~11G of memory)

    • For training the end-to-end version of Faster R-CNN with VGG16, 3G of GPU memory is sufficient (using CUDNN)

    我的是环境是Ubuntu 14.04 + Titan X(12GB) + cuda 7.0 + cudnn V3

    Caffe环境配置

    Caffe环境需要python layer的支持,在你的Caffe的Makefile.config中去掉以下的注释

    • WITH_PYTHON_LAYER := 1
    • USE_CUDNN := 1

    2 安装python库依赖

    cython,python-OpenCVeasydict

    pip install cython
    pip install python-opencv
    pip install easydict

    3 克隆py-faster-rcnn源代码

    git clone --recursive https://github.com/rbgirshick/py-faster-rcnn.git

    4 编译cython模块

    cd $FRCN_ROOT/lib
    make 

    5 编译Caffepycaffe

    cd $FRCN_ROOT/caffe-fast-rcnn
    make -j8 && make pycaffe

    -j8的选项是进行多核编译,可以加速编译过程,推荐使用

    数据集

    参考VOC2007的数据集格式,主要包括三个部分:

    • JPEGImages

    • Annotations

    • ImageSets/Main

    JPEGImages —> 存放你用来训练的原始图像

    Annotations —> 存放原始图像中的Object的坐标信息,XML格式

    ImageSets/Main —> 指定用来train,trainval,val和test的图片的编号

    这部分非常重要,数据集做不好直接导致代码出现异常,无法运行,或者出现奇怪的错误,我也是掉进了很多坑,爬上来之后才写的这篇博客,希望大家不要趟我趟过的浑水!每一个部分我都会细说的!

    JPEGImages

    这个没什么,直接把你的图片放入就可以了,但是有三点注意:

    • 编号要以6为数字命名,例如000034.jpg

    • 图片要是JPEG/JPG格式的,PNG之类的需要自己转换下

    • 图片的长宽比(width/height)要在0.462-6.828之间,就是太过瘦长的图片不要

    0.462-6.828是我自己实验得出来的,就我的数据集而言是这个比例,总之长宽比太大或者太小的,你要注意将其剔除,否则可能会出现下面我实验时候出的错:

    Traceback (most recent call last): 
    File “/usr/lib/python2.7/multiprocessing/process.py”, line 258, in _bootstrap 
    self.run() 
    File “/usr/lib/python2.7/multiprocessing/process.py”, line 114, in run 
    self._target(*self._args, **self._kwargs) 
    File “./tools/train_faster_rcnn_alt_opt.py”, line 130, in train_rpn 
    max_iters=max_iters) 
    File “/home/work-station/zx/py-faster-rcnn/tools/../lib/fast_rcnn/train.py”, line 160, in train_net 
    model_paths = sw.train_model(max_iters) 
    File “/home/work-station/zx/py-faster-rcnn/tools/../lib/fast_rcnn/train.py”, line 101, in train_model 
    self.solver.step(1) 
    File “/home/work-station/zx/py-faster-rcnn/tools/../lib/rpn/anchor_target_layer.py”, line 137, in forward 
    gt_argmax_overlaps = overlaps.argmax(axis=0) 
    ValueError: attempt to get argmax of an empty sequence

    Google给出的原因是 Because the ratio of images width and heights is too small or large,这个非常重要

    Annotations

    faster rcnn训练需要图像的bounding box信息作为监督(ground truth),所以你需要将你的所有可能的object使用框标注,并写上坐标,最终是一个XML格式的文件,一个训练图片对应Annotations下的一个同名的XML文件

    参考官方VOC的Annotations的格式:

    <annotation>
        <folder>VOC2007</folder> #数据集文件夹
        <filename>000105.jpg</filename> #图片的name
        <source> #注释信息,无所谓有无
            <database>The VOC2007 Database</database>
            <annotation>PASCAL VOC2007</annotation>
            <image>flickr</image>
            <flickrid>321862192</flickrid>
        </source>
        <owner> #注释信息,无所谓有无
            <flickrid>Eric T. Johnson</flickrid>
            <name>?</name>
        </owner>
        <size> #图片大小
            <width>500</width>
            <height>333</height>
            <depth>3</depth>
        </size>
        <segmented>0</segmented>
        <object> #多少个框就有多少个object标签
            <name>boat</name> #bounding box中的object的class name
            <pose>Frontal</pose>
            <truncated>1</truncated>
            <difficult>0</difficult>
            <bndbox>
                <xmin>22</xmin> #框的坐标
                <ymin>1</ymin>
                <xmax>320</xmax>
                <ymax>314</ymax>
            </bndbox>
        </object>
        <object>
            <name>person</name>
            <pose>Frontal</pose>
            <truncated>1</truncated>
            <difficult>0</difficult>
            <bndbox>
                <xmin>202</xmin>
                <ymin>71</ymin>
                <xmax>295</xmax>
                <ymax>215</ymax>
            </bndbox>
        </object>
        <object>
            <name>person</name>
            <pose>Frontal</pose>
            <truncated>1</truncated>
            <difficult>0</difficult>
            <bndbox>
                <xmin>170</xmin>
                <ymin>107</ymin>
                <xmax>239</xmax>
                <ymax>206</ymax>
            </bndbox>
        </object>
    </annotation>

    这里有一个非常好用的工具VOC框图工具,可以自动帮你生成需要的XML格式,实际中发现格式基本无误,只有小的地方需要改动下,大家对比下就知道怎么改了,我是在Linux下借助sed修改的,这个不难

    Imagesets/Main

    因为VOC的数据集可以做很多的CV任务,比如Object detection, Semantic segementation, Edge detection等,所以Imageset下有几个子文件夹(Layout, Main, Segementation),我们只要修改下Main下的文件就可以了(train.txttrainval.txtval.txttest.txt),里面写上你想要进行任务的图片的编号

    将上述你的数据集放在py-faster-rcnn/data/VOCdevkit2007/VOC2007下面,替换原始VOC2007的JPEGIMages,Imagesets,Annotations

    原始VOC2007下载地址: VOC20007数据集

    代码修改

    工程目录介绍

    • caffe-fast-rcnn —> caffe框架

    • data —> 存放数据,以及读取文件的cache

    • experiments —>存放配置文件以及运行的log文件,配置文件

    • lib —> python接口

    • models —> 三种模型, ZF(S)/VGG1024(M)/VGG16(L)

    • output —> 输出的model存放的位置,不训练此文件夹没有

    • tools —> 训练和测试的python文件

    修改源文件

    faster rcnn有两种各种训练方式:

    • Alternative training(alt-opt)

    • Approximate joint training(end-to-end)

    推荐使用第二种,因为第二种使用的显存更小,而且训练会更快,同时准确率差不多,两种方式需要修改的代码是不一样的,同时faster rcnn提供了三种训练模型,小型的ZFmodel,中型的VGG_CNN_M_1024和大型的VGG16,论文中说VGG16效果比其他两个好,但是同时占用更大的GPU显存(~11GB)

    我使用的是VGG model + alternative training,需要检测的类别只有一类,加上背景所以总共是两类(background + captcha)

    py-faster-rcnn/models/pascal_voc/VGG16/faster_rcnn_alt_opt/stage1_fast_rcnn_train.pt

    layer {  
      name: 'data'  
      type: 'Python'  
      top: 'data'  
      top: 'rois'  
      top: 'labels'  
      top: 'bbox_targets'  
      top: 'bbox_inside_weights'  
      top: 'bbox_outside_weights'  
      python_param {  
        module: 'roi_data_layer.layer'  
        layer: 'RoIDataLayer'  
        param_str: "'num_classes': 2" #按训练集类别改,该值为类别数+1  
      }  
    }  
    layer {  
      name: "cls_score"  
      type: "InnerProduct"  
      bottom: "fc7"  
      top: "cls_score"  
      param { 
      lr_mult: 1.0
      }  
      param {
      lr_mult: 2.0 
      }  
      inner_product_param {  
        num_output: 2 #按训练集类别改,该值为类别数+1  
        weight_filler {  
          type: "gaussian"  
          std: 0.01  
        }  
        bias_filler {  
          type: "constant"  
          value: 0  
        }  
      }  
    }  
    layer {  
      name: "bbox_pred"  
      type: "InnerProduct"  
      bottom: "fc7"  
      top: "bbox_pred"  
      param { 
      lr_mult: 1.0 
      }  
      param { 
      lr_mult: 2.0 
      }  
      inner_product_param {  
        num_output: 8 #按训练集类别改,该值为(类别数+1)*4,四个顶点坐标  
        weight_filler {  
          type: "gaussian"  
          std: 0.001  
        }  
        bias_filler {  
          type: "constant"  
          value: 0  
        }  
      }  
    }  
    
    

    py-faster-rcnn/models/pascal_voc/VGG16/faster_rcnn_alt_opt/stage1_rpn_train.pt

    layer {  
      name: 'input-data'  
      type: 'Python'  
      top: 'data'  
      top: 'im_info'  
      top: 'gt_boxes'  
      python_param {  
        module: 'roi_data_layer.layer'  
        layer: 'RoIDataLayer'  
        param_str: "'num_classes': 2" #按训练集类别改,该值为类别数+1  
      }  
    }  
    

    py-faster-rcnn/models/pascal_voc/VGG16/faster_rcnn_alt_opt/stage2_fast_rcnn_train.pt

    layer {  
      name: 'data'  
      type: 'Python'  
      top: 'data'  
      top: 'rois'  
      top: 'labels'  
      top: 'bbox_targets'  
      top: 'bbox_inside_weights'  
      top: 'bbox_outside_weights'  
      python_param {  
        module: 'roi_data_layer.layer'  
        layer: 'RoIDataLayer'  
        param_str: "'num_classes': 2" #按训练集类别改,该值为类别数+1  
      }  
    }  
    layer {  
      name: "cls_score"  
      type: "InnerProduct"  
      bottom: "fc7"  
      top: "cls_score"  
      param { 
      lr_mult: 1.0 
      }  
      param { 
      lr_mult: 2.0 
      }  
      inner_product_param {  
        num_output: 2 #按训练集类别改,该值为类别数+1  
        weight_filler {  
          type: "gaussian"  
          std: 0.01  
        }  
        bias_filler {  
          type: "constant"  
          value: 0  
        }  
      }  
    }  

    layer {  

      name: "bbox_pred"  
      type: "InnerProduct"  
      bottom: "fc7"  
      top: "bbox_pred"  
      param { 
      lr_mult: 1.0
      }  
      param { 
      lr_mult: 2.0 
      }  
      inner_product_param {  
        num_output: 8 #按训练集类别改,该值为(类别数+1)*4,四个顶点坐标  
        weight_filler {  
          type: "gaussian"  
          std: 0.001  
        }  
        bias_filler {  
          type: "constant"  
          value: 0  
        }  
      }  
    }  

    py-faster-rcnn/models/pascal_voc/VGG16/faster_rcnn_alt_opt/stage2_rpn_train.pt

    layer {  
      name: 'input-data'  
      type: 'Python'  
      top: 'data'  
      top: 'im_info'  
      top: 'gt_boxes'  
      python_param {  
        module: 'roi_data_layer.layer'  
        layer: 'RoIDataLayer'  
        param_str: "'num_classes': 2" #按训练集类别改,该值为类别数+1  
      }  
    }  

    py-faster-rcnn/models/pascal_voc/VGG16/faster_rcnn_alt_opt/faster_rcnn_test.pt

    layer {  
      name: "cls_score"  
      type: "InnerProduct"  
      bottom: "fc7"  
      top: "cls_score"  
      inner_product_param {  
        num_output: 2 #按训练集类别改,该值为类别数+1  
      }  
    }  

    layer {
    name: "bbox_pred"
    type: "InnerProduct"
    bottom: "fc7"
    top: "bbox_pred"
    inner_product_param {
    num_output: 8      #按训练集类别改,该值为(类别数+1)*4,四个顶点坐标


    }
    }

    py-faster-rcnn/lib/datasets/pascal_voc.py

    class pascal_voc(imdb):  
        def __init__(self, image_set, year, devkit_path=None):  
            imdb.__init__(self, 'voc_' + year + '_' + image_set)  
            self._year = year  
            self._image_set = image_set  
            self._devkit_path = self._get_default_path() if devkit_path is None   
                                else devkit_path  
            self._data_path = os.path.join(self._devkit_path, 'VOC' + self._year)  
            self._classes = ('__background__', # always index 0  
                             captcha' # 有几个类别此处就写几个,我是两个
                          )  

    line 212

    cls = self._class_to_ind[obj.find('name').text.lower().strip()]  

    如果你的标签含有大写字母,可能会出现KeyError的错误,所以建议全部使用小写字母

    py-faster-rcnn/lib/datasets/imdb.py

    将append_flipped_images函数改为如下形式:

    def append_flipped_images(self):  
            num_images = self.num_images  
            widths = [PIL.Image.open(self.image_path_at(i)).size[0]  
                      for i in xrange(num_images)]  
            for i in xrange(num_images):  
                boxes = self.roidb[i]['boxes'].copy()  
                oldx1 = boxes[:, 0].copy()  
                oldx2 = boxes[:, 2].copy()  
                boxes[:, 0] = widths[i] - oldx2 - 1  
                print boxes[:, 0]  
                boxes[:, 2] = widths[i] - oldx1 - 1  
                print boxes[:, 0]  
                assert (boxes[:, 2] >= boxes[:, 0]).all()  
                entry = {'boxes' : boxes,  
                         'gt_overlaps' : self.roidb[i]['gt_overlaps'],  
                         'gt_classes' : self.roidb[i]['gt_classes'],  
                         'flipped' : True}  
                self.roidb.append(entry)  
            self._image_index = self._image_index * 2  

    到此代码修改就搞定了

    训练

    训练前还需要注意几个地方

    1 cache问题

    假如你之前训练了官方的VOC2007的数据集或其他的数据集,是会产生cache的问题的,建议在重新训练新的数据之前将其删除

    (1) py-faster-rcnn/output 
    (2) py-faster-rcnn/data/cache

    2 训练参数

    py-faster-rcnn/models/pascal_voc/VGG16/faster_rcnn_alt_opt/stage_fast_rcnn_solver*.pt

    base_lr: 0.001
    lr_policy: 'step'
    step_size: 30000
    display: 20
    ....

    迭代次数在文件py-faster-rcnn/tools/train_faster_rcnn_alt_opt.py中进行修改

    line 80

    max_iters = [80000, 40000, 80000, 40000]

    分别对应rpn第1阶段,fast rcnn第1阶段,rpn第2阶段,fast rcnn第2阶段的迭代次数,自己修改即可,不过注意这里的值不要小于上面的solver里面的step_size的大小,大家自己修改吧

    开始训练:

    cd py-faster-rcnn
    ./experiments/scripts/faster_rcnn_alt_opt.sh 0 VGG16 pascal_voc 

    指明使用第一块GPU(0),模型是VGG16,训练数据是pascal_voc(voc2007),没问题的话应该可以迭代训练了

    结果

    训练完毕,得到我们的训练模型,我们就可以使用它来进行我们的object detection了,具体是: 
    1 将py-faster-rcnn/output/faster_rcnn_alt_opt/voc_2007_trainval/VGG16_faster_rcnn_final.caffemodel,拷贝到py-faster-rcnn/data/faster_rcnn_models

    2 将你需要进行test的images放在py-faster-rcnn/data/demo

    3 修改py-faster-rcnn/tools/demo.py文件


    CLASSES = ('_background_', 'captcha') #参考你自己的类别写 


    NETS = {'vgg16': ('VGG16', 
    'VGG16_faster_rcnn_final.caffemodel'), #改成你训练得到的model的name 
    'zf': ('ZF', 
    'ZF_faster_rcnn_final.caffemodel') 

    im_names = ['1559.jpg','1564.jpg']  # 改成自己的test image的name

    上几张我的检测结果吧

    1

    2

    参考

    faster rcnn 做自己的数据集

    faster rcnn 教程

    使用ZF训练自己的faster rcnn model

    一些错误的解决方法

    https://www.zhihu.com/question/57091642

    作者:Jing
    链接:https://www.zhihu.com/question/57091642/answer/165134753
    来源:知乎
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    1. 制作数据集

    程序/工具:VOC2007文件夹、labelImg

    处理流程:图像重命名为6位数字,使用labelImg工具标定,根据xml生成四个txt(train.txt、val.txt、test.txt、trainval.txt),将jpg、xml、txt等文件按照逻辑图所示位置存放


    2. 修改网络文件

    VGG16的Train.prototxt

    Line:11

    Line 530:num_classes:”3‘’修改成 损伤类型数目+1(背景算一类)

    Line 620:num_output 修改同上

    Line 643:num_output: 12 此处数字应为 (损伤类别数+1)*4 “4”是指bbox的四个角

    Lib/datasets/pascal_voc.py 修改line 31

    VGG16的Test.prototxt

    line567

    line592

    ZF的Train.prototxt 

    line11

    line364

    line444

    line463

    ZF的Test.prototxt

    line352

    line361


    3. 运行程序

    参考链接:


    终端访问py-faster-rcnn目录,输入以下命令:

    1. ./experiments/scripts/faster_rcnn_alt_opt.sh 0 ZF pascal_voc  

    ./experiments/scripts/faster_rcnn_end2end.sh 0 VGG16 pascal_voc

    迭代次数在faster rcnnend2end.sh中修改

    0表示使用GPU 0运行程序,可修改;VGG16表示使用的网络

    3.训练自己的数据

    1. 修改prototxt配置文件
    这些配置文件都在models下的pascal_voc下。里面有三种网络结构:ZF、VGG16、VGG_CNN_M_1024,本文选择的是VGG_CNN_M_1024 。每个网络结构中都有三个文件夹,分别是faster_rcnn_end2end、faster_rcnn_alt_opt、faster_rcnn。使用近似联合训练,比交替优化快1.5倍,但是准确率相近,所以推荐使用这种方法。更改faster_rcnn_end2end文件夹下的train.prototxt和test.prototxt,train中需要更改的地方有三处,
    第一处是input-data层,将原先的21改成:你的实际类别数+1(背景),我目标检测一共有46类,所以加上背景这一类,一共47类。

    第二处是cls_score层

    第三处是bbox_pred,这里需将原来的84改成(你的类别数+1)4,即(46+1)4=188

    test.prototxt中没有input-data层,所以只需按照train中的修改cls_score层以及bbox_pred层即可
    2. 修改lib/datasets/pascal_voc.py,将类别改成自己的类别

    这里有一个注意点就是,这里的类别以及你之前的类别名称最好是全部小写,假如是大写的话,则会报keyError的错误,这时只需要在pascal_voc。py中第218行的lower去掉即可

    datasets目录下主要有三个文件,分别是
    (1) factory.py:这是一个工厂类,用类生成imdb类并且返回数据库供网络训练和测试使用;
    (2) imdb.py:是数据库读写类的基类,封装了许多db的操作;
    (3) pascl_voc.pyRoss用这个类来操作
    3. 修改py-faster-rcnn/lib/datasets/imdb.py
    在使用自己的数据进行训练时,假如你的数据集中的图片没有统一整理过就会报 assert(boxes[:,2] >= boxes[:,0]).all() 这个错误,故需在imdb.py中加入如下几行

    4. 开始训练

    cd py-faster-rcnn
    ./experiments/scripts/faster_rcnn_end2end.sh 0 VGG_CNN_M_1024 pascal_voc
    

    由于训练过程太长,可以将训练过程产生的输出定向输入到log文件中,这样可方便查看。只需在上述命令中加入定向输入的命令即可,如下:

    ./experiments/scripts/faster_rcnn_end2end.sh 0 VGG_CNN_M_1024 pascal_voc > /home/lby/log/clothdirector.log 2>&1
    

    !!!训练前需要将cache中的pki文件以及VOCdevkit2007中annotations_cache的缓存删掉。

    训练过程中会遇到的问题

    1. roidb[i][‘image’] = imdb.image_path_at(i)
      IndexError: list index out of range

      解决方法:删除data/cache里面的pki文件
      注意:不管在训练过程中遇到什么问题,修正过后,重新训练之前都需要将cache中的pki文件删除之后再重新运行,
    2. R = [obj for obj in recs[imagename] if obj[‘name’] == classname]
      KeyError: ‘0000001’

      这是在测试时出现错误,删掉VOCdevkit2007中annotations_cache的缓存

    4.测试结果

    训练完成之后,将output中的最终模型拷贝到data/faster_rcnn_models,修改tools下的demo.py,我是使用VGG_CNN_M_1024这个中型网络,不是默认的ZF,所以要改的地方挺多
    1. 修改class

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    CLASSES = ('__background__',
    'Blouse', 'Sweatpants', 'Cardigan', 'Button-Down',
    'Cutoffs', 'Chinos', 'Top', 'Anorak', 'Kimono',
    'Tank', 'Robe', 'Parka', 'Jodhpurs',
    'Halter', 'Shorts', 'Caftan','Turtleneck',
    'Leggings', 'Joggers', 'Hoodie', 'Culottes',
    'Sweater', 'Flannel', 'Jeggings', 'Blazer',
    'Onesie', 'Coat', 'Henley', 'Jacket',
    'Trunks', 'Gauchos', 'Sweatshorts', 'Romper',
    'Jersey', 'Bomber', 'Sarong', 'Dress','Jeans',
    'Tee', 'Coverup', 'Capris', 'Kaftan','Peacoat',
    'Poncho', 'Skirt', 'Jumpsuit')

    2. 增加你自己训练的模型

    1
    2
    3
    4
    5
    NETS = {'vgg16': ('VGG16',
    'VGG16_faster_rcnn_final.caffemodel'),
    'zf': ('ZF',
    'ZF_faster_rcnn_final.caffemodel'),
    'myvgg1024':('VGG_CNN_M_1024','vgg_cnn_m_1024_faster_rcnn_iter_70000.caffemodel')}

    3. 修改prototxt,如果你用的是ZF,就不用改了

    1
    2
    prototxt = os.path.join(cfg.MODELS_DIR, NETS[args.demo_net][0],
    'faster_rcnn_end2end', 'test.prototxt')

    4. 开始检测
    执行 ./tools/demo.py –net myvgg1024
    假如不想那么麻烦输入参数,可以在demo的parse_args()里修改默认参数
    parser.add_argument(‘–net’, dest=’demo_net’, help=’Network to use [myvgg1024]’,
    choices=NETS.keys(), default=’myvgg1024’)
    这样只需要输入 ./tools/demo.py 就可以了
    检测结果:

    遇到的问题

      1. Cannot copy param 0 weights from layer“”:已放弃(核心已转储)

        没有修改prototxt,详情请见第3步
      2. Makefile:2: recipe for target ‘all’ failed

        Traceback (most recent call last):
        File “setup.py”, line 59, in 
        CUDA = locate_cuda()
        File “setup.py”, line 56, in locate_cuda
        raise EnvironmentError(‘The CUDA %s path could not be located in %s’ % (k, v))
        EnvironmentError: The CUDA lib64 path could not be located in /usr/lib64
        Makefile:2: recipe for target ‘all’ failed
        解决方法:打开 setup.py,把lib64改为lib

        cudaconfig = {‘home’:home, ‘nvcc’:nvcc,

        'include': pjoin(home, 'include'),  
         'lib64': pjoin(home, 'lib')} 
        
      3. make error:command ‘/usr/local/bin/nvcc’ failed with exit status 1

        添加 export PATH=/usr/local/cuda/bin:”$PATH” 到你的 ~/.bashrc

    http://bealin.github.io/2016/10/23/Caffe%E5%AD%A6%E4%B9%A0%E7%B3%BB%E5%88%97%E2%80%94%E2%80%946%E4%BD%BF%E7%94%A8Faster-RCNN%E8%BF%9B%E8%A1%8C%E7%9B%AE%E6%A0%87%E6%A3%80%E6%B5%8B/
     
    ZF测试

    9.测试

    将训练得到的py-faster-rcnnoutputfaster_rcnn_alt_opt***_trainval中ZF的caffemodel拷贝至py-faster-rcnndatafaster_rcnn_models(如果没有这个文件夹,就新建一个),然后,修改:

    py-faster-rcnn oolsdemo.py,主要修改:

    [plain] view plain copy
     
    1. CLASSES = ('__background__',  
    2.        '你的标签1', '你的标签2', '你的标签3', '你的标签4')  

    改成你的数据集标签;

    [plain] view plain copy
     
    1. NETS = {'vgg16': ('VGG16',  
    2.                   'VGG16_faster_rcnn_final.caffemodel'),  
    3.         'zf': ('ZF',  
    4.                   'ZF_faster_rcnn_final.caffemodel')}  

    上面ZF的caffemodel改成你的caffemodel。

    [plain] view plain copy
     
    1. im_names = ['1559.jpg','1564.jpg']  

    改成你的测试图片。(测试图片放在py-faster-rcnndatademo中)

    10.结果

    在py-faster-rcnn下,

    执行:

    [plain] view plain copy
    1. ./tools/demo.py --net zf  

    或者将默认的模型改为zf:

    [html] view plain copy
    1. parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16]',  
    2.                         choices=NETS.keys(), default='vgg16')  
    修改:
    [html] view plain copy
    1. default='zf'  
    执行: 
    [plain] view plain copy

    ./tools/demo.py 

    faster rcnn运行自带Demo出现Unknown layer type错误解决

    faster rcnn配置好之后运行 ./tools/demo.py出现如下错误:: Check failed: registry.count(type) == 1 (0 vs. 1) Unknown layer type: Python

    两种可能:
    1.makefile 文件下LIBRARIES += opencv_core opencv_highgui opencv_imgproc opencv_imgcodecs没有加上
    2.makefile.config 文件下WITH_PYTHON_LAYER := 1的注释没去掉

    /home/ryan/py-faster-rcnn/caffe-fast-rcnn

    make -j16 && make pycaffe

    Traceback (most recent call last):
    File "./tools/demo.py", line 187, in 
    demo(net, im_name)
    File "./tools/demo.py", line 124, in demo
    cls_scores = scores[:, cls_ind]
    IndexError: index 2 is out of bounds for axis 1 with size 2

    Looks like you are using 66 classes. Have you modified your prototxt (.pt) files to represent this? You should change the num_classes parameter, and possibly others. I apologize as I have not worked with the alt opt model.

    因为,模型中的类的数量与demo中CLASS的数量不匹配。把CLASS的类别按模型定义的结果该好即可。

  • 相关阅读:
    resteasy和springmvc的区别
    队列
    栈的顺序存储和链式存储
    线性表链表存储结构(单链表)
    线性表顺序存储结构
    maven创建分model的工程
    使用throw和throws 引发异常
    手写web框架之加载Controller,初始化框架
    手写web框架之实现依赖注入功能
    Kruskal算法(贪心+并查集=最小生成树)
  • 原文地址:https://www.cnblogs.com/JZ-Ser/p/7411429.html
Copyright © 2011-2022 走看看