<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://huangying-zhan.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://huangying-zhan.github.io/" rel="alternate" type="text/html" /><updated>2025-09-18T22:00:24-07:00</updated><id>https://huangying-zhan.github.io/feed.xml</id><title type="html">Huangying Zhan / 粘煌熒</title><subtitle>Tech Lead Manager</subtitle><author><name>Huangying Zhan</name><email>zhanhuangying.work@gmail.com</email></author><entry><title type="html">Detection: Faster R-CNN</title><link href="https://huangying-zhan.github.io/2016/09/22/detection-faster-rcnn" rel="alternate" type="text/html" title="Detection: Faster R-CNN" /><published>2016-09-22T00:00:00-07:00</published><updated>2016-09-22T00:00:00-07:00</updated><id>https://huangying-zhan.github.io/2016/09/22/detection-faster-rcnn</id><content type="html" xml:base="https://huangying-zhan.github.io/2016/09/22/detection-faster-rcnn"><![CDATA[<h3 id="summary">Summary</h3>

<p>This post records my experience with py-faster-rcnn, including how to setup py-faster-rcnn from scratch, how to perform a demo training on PASCAL VOC dataset by py-faster-rcnn, how to train your own dataset, and some errors I encountered. All the steps are based on Ubuntu 14.04 + CUDA 8.0. Faster R-CNN is an important research result for object detection with an end-to-end deep convolutional neural network architure. For the details, please refer to <a href="https://huangying-zhan.github.io/public/post_resource/Paper/detection/2016_faster-r-cnn-towards-real-time-object-detection-with-region-proposal-networks.pdf">original paper</a>.</p>

<p>The source code related to adding own dataset is provided at: (https://github.com/Huangying-Zhan/py-faster-rcnn)[https://github.com/Huangying-Zhan/py-faster-rcnn]</p>

<hr />

<h3 id="contents">Contents</h3>

<ol>
  <li><a href="#Setup py-faster-rcnn">Setup py-faster-rcnn</a></li>
  <li><a href="#Demo Training on PASCAL VOC">Demo Training on PASCAL VOC</a></li>
  <li><a href="#Training on new dataset">Training on new dataset</a></li>
  <li><a href="#Error and solution">Error and solution</a></li>
</ol>

<hr />

<p><a name="Setup py-faster-rcnn"></a></p>

<h3 id="part-1-setup-py-faster-rcnn">Part 1. Setup py-faster-rcnn</h3>

<p>In this part, a simple instruction for install py-faster-rcnn is introduced. The instruction mainly refers to <a href="https://github.com/rbgirshick/py-faster-rcnn">py-faster-rcnn</a>.</p>

<ol>
  <li>
    <p>Clone the Faster R-CNN repo</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> # Make sure to clone with --recursive
 $ git clone --recursive https://github.com/rbgirshick/py-faster-rcnn.git
</code></pre></div>    </div>
  </li>
  <li>
    <p>Lets call the directory as <code class="language-plaintext highlighter-rouge">$FRCN</code></p>
  </li>
  <li>
    <p>Build the Cython modules</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ cd $FRCN/lib
 $ make
</code></pre></div>    </div>
  </li>
  <li>
    <p>Build Caffe and PyCaffe</p>

    <p>For this part, please refer to <a href="http://caffe.berkeleyvision.org/installation.html">Caffe official installation instruction</a> or my post about <a href="https://huangying-zhan.github.io/2016/09/09/GPU-and-Caffe-installation-in-Ubuntu.html#Caffe%20installation">Caffe installation</a>.
 If you have experience with Caffe, just follow the instruction below.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ cd $FRCN/caffe-fast-rcnn
 $ cp Makefile.config.example Makefile.config
    
 # Modify Makefile.config, uncommment this line
 WITH_PYTHON_LAYER := 1
 # Modifiy Makefile.config according to your need, such as setup related to GPU support, cuDNN, CUDA version, Anaconda, OpenCV, etc.
    
 # After modification on Makefile.config
 $ make all -j4 # -j4 is for complilation acceleration only. 4 is the number of core in your CPU, change it according to your computer CPU. 
 # Suppose you have installed prerequites for PyCaffe, otherwise, go back to the Caffe installation instructions.
 $ make pycaffe -j4
</code></pre></div>    </div>
  </li>
  <li>
    <p>Download pre-computed Faster R-CNN models</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ cd $FRCN
 $ ./data/scripts/fetch_faster_rcnn_models.sh
</code></pre></div>    </div>
  </li>
  <li>
    <p>Run the demo</p>

    <p>However, in this part you might get into trouble with different errors, such as without some packages. At the end of this post, some encountered errors and solution are provided. For those unexpected error, google the error and you should be able to find a solution.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ ./tools/demo.py
</code></pre></div>    </div>
  </li>
</ol>

<hr />

<p><a name="Demo Training on PASCAL VOC"></a></p>

<h3 id="part-2-demo-training-on-pascal-voc">Part 2. Demo Training on PASCAL VOC</h3>

<p>In this part, the training of py-faster-rcnn will be explained. Firstly, an original training procedure on PASCAL VOC dataset is provided. The purpose is to understand the structure of dataset and training steps.</p>

<h4 id="21-prepare-dataset-and-pre-trained-model">2.1. Prepare dataset and Pre-trained model</h4>

<ol>
  <li>
    <p>Download VOC dataset</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ cd $FRCN/data
 $ 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
 $ wget http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCdevkit_08-Jun-2007.tar

 $ tar xvf VOCdevkit_08-Jun-2007.tar 
 $ tar xvf VOCtrainval_06-Nov-2007.tar
 $ tar xvf VOCtest_06-Nov-2007.tar

 $ ln -s VOCdevkit VOCdevkit2007 #create a softlink
</code></pre></div>    </div>
  </li>
  <li>
    <p>Download pre-trained models</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ cd $FRCN
 $ ./data/scripts/fetch_imagenet_models.sh
 $ ./data/scripts/fetch_faster_rcnn_models.sh
</code></pre></div>    </div>
  </li>
</ol>

<h4 id="22-training">2.2. Training</h4>

<p>There are 2 types of training methods provided by <a href="https://github.com/rbgirshick/py-faster-rcnn">py-faster-rcnn</a>. One is using the alternating optimization algrithm while another one is approximate joint training method. In this post, approximate joint training method is introduced. For the details, please refer to the paper, <a href="https://huangying-zhan.github.io/2016/08/24/detection.html#Faster%20R-CNN">Faster R-CNN</a>.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cd $FRCN
# ./experiments/scripts/faster_rcnn_end2end.sh [GPU_ID] [NET] [DATASET]
# Directly run this command might have an error "AssertionError: Selective search data not found at:". For the solution, please refer to Part 4.
$ ./experiments/scripts/faster_rcnn_end2end.sh 0 ZF pascal_voc
</code></pre></div></div>

<p>Here is a remark about the logic and idea behind the training script.</p>

<ol>
  <li>
    <p><code class="language-plaintext highlighter-rouge">faster_rcnn_end2end.sh</code></p>

    <p>This is a shell script, which is the toppest layer of the whole pipeline, it monitors the input arguments, including GPU ID, network structure(ZF-Net, VGG, or others), dataset (PASCAL VOC, COCO or others), and extra configurations.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> # Part of the script
 GPU_ID=$1
 NET=$2
 NET_lc=${NET,,}
 DATASET=$3

 array=( $@ )
 len=${#array[@]}
 EXTRA_ARGS=${array[@]:3:$len}
 EXTRA_ARGS_SLUG=${EXTRA_ARGS// /_}
</code></pre></div>    </div>

    <p>Then, it will call two programs, <code class="language-plaintext highlighter-rouge">train_net.py</code> and  followed by <code class="language-plaintext highlighter-rouge">test_net.py</code>. As the name given, <code class="language-plaintext highlighter-rouge">train_net.py</code> is to train a model while <code class="language-plaintext highlighter-rouge">test_net.py</code> is to evaluate performance of the trained model.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> # Part of the script
 time ./tools/train_net.py --gpu ${GPU_ID} \
   --solver models/${PT_DIR}/${NET}/faster_rcnn_end2end/solver.prototxt \
   --weights data/imagenet_models/${NET}.v2.caffemodel \
   --imdb ${TRAIN_IMDB} \
   --iters ${ITERS} \
   --cfg experiments/cfgs/faster_rcnn_end2end.yml \
   ${EXTRA_ARGS}

 set +x
 NET_FINAL=`grep -B 1 "done solving" ${LOG} | grep "Wrote snapshot" | awk '{print $4}'`
 set -x

 time ./tools/test_net.py --gpu ${GPU_ID} \
   --def models/${PT_DIR}/${NET}/faster_rcnn_end2end/test.prototxt \
   --net ${NET_FINAL} \
   --imdb ${TEST_IMDB} \
   --cfg experiments/cfgs/faster_rcnn_end2end.yml \
   ${EXTRA_ARGS}
</code></pre></div>    </div>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">faster_rcnn_end2end.yml</code></p>

    <p>As we can see from <code class="language-plaintext highlighter-rouge">faster_rcnn_end2end.sh</code>, <code class="language-plaintext highlighter-rouge">cfg</code> comes from <code class="language-plaintext highlighter-rouge">faster_rcnn_end2end.yml</code>, which means that this file stores many importatnt configurations. Here shows some original configurations provided.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> EXP_DIR: faster_rcnn_end2end
 TRAIN:
   HAS_RPN: True
   IMS_PER_BATCH: 1
   BBOX_NORMALIZE_TARGETS_PRECOMPUTED: True
   RPN_POSITIVE_OVERLAP: 0.7
   RPN_BATCHSIZE: 256
   PROPOSAL_METHOD: gt
   BG_THRESH_LO: 0.0
 TEST:
   HAS_RPN: True
</code></pre></div>    </div>

    <p>However, if you wish to add your own configurations, such as number of iterations to take a model snapshot while training, you may refer to <code class="language-plaintext highlighter-rouge">$FRCN/lib/fast_rcnn/config.py</code>. This file contains all the configuration parameters. You don’t need to set the configuration in this <code class="language-plaintext highlighter-rouge">config.py</code> but just add a statement in <code class="language-plaintext highlighter-rouge">faster_rcnn_end2end.yml</code>. The program can parse the arguments automatically. Of course there exists default values if you do not declare the items in the .yml file.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> # Example to add SNAPSHOT_ITERS into the configuration
 EXP_DIR: faster_rcnn_end2end
 TRAIN:
   HAS_RPN: True
   IMS_PER_BATCH: 1
   BBOX_NORMALIZE_TARGETS_PRECOMPUTED: True
   RPN_POSITIVE_OVERLAP: 0.7
   RPN_BATCHSIZE: 256
   PROPOSAL_METHOD: gt
   BG_THRESH_LO: 0.0
   SNAPSHOT_ITERS: 10000 # This line is an example to add arguments.
 TEST:
   HAS_RPN: True
</code></pre></div>    </div>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">train_net.py</code></p>

    <p>Basically, there are 3 things included in the file.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> # Read dataset
 imdb, roidb = combined_roidb(args.imdb_name)

 # Pass configurations from `faster_rcnn_end2end.sh` and `faster_rcnn_end2end.yml` to lower layer programs/functions
 # Call `fast_rcnn.train_net` for training
     train_net(args.solver, roidb, output_dir, pretrained_model=args.pretrained_model, max_iters=args.max_iters)
</code></pre></div>    </div>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">combined_roidb</code> &amp; <code class="language-plaintext highlighter-rouge">pascal_voc.py</code></p>

    <p>Recall that in <code class="language-plaintext highlighter-rouge">faster_rcnn_end2end.sh</code>. You have entered an argument,</p>

 	–imdb ${TRAIN_IMDB}

    <p><code class="language-plaintext highlighter-rouge">combined_roidb</code> do nothing but just trace back and read the datasets, such as train, val, and test using functions in <code class="language-plaintext highlighter-rouge">$FRCN/lib/datasets/pascal_voc.py</code>.</p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">fast_rcnn.train_net</code></p>

    <p>This function is at <code class="language-plaintext highlighter-rouge">$FRCN/lib/fast_rcnn/train.py</code> This function is the core of whole training pipeline since it calls <code class="language-plaintext highlighter-rouge">solver.prototxt</code>, but in fact you don’t need to care this part in most of the time.</p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">solver.prototxt</code> &amp; <code class="language-plaintext highlighter-rouge">train.prototxt</code></p>

    <p>If you are familiar with Caffe, you should know the purpose of <code class="language-plaintext highlighter-rouge">solver.prototxt</code> and <code class="language-plaintext highlighter-rouge">train.prototxt</code>. Otherwise, you are suggested to go through <a href="http://caffe.berkeleyvision.org/gathered/examples/mnist.html">Caffe’s MNIST tutorial</a>. In here, the idea will be described briefly only.</p>

    <p>Basically, <code class="language-plaintext highlighter-rouge">solver.prototxt</code> tells the program where to find your ConvNet structure prototxt and some training setups, such as learning rate, learning policy, etc.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> train_net: "models/pascal_voc/ZF/faster_rcnn_end2end/train.prototxt"
 base_lr: 0.001
 lr_policy: "step"
 gamma: 0.1
 stepsize: 50000
 display: 20
 average_loss: 100
 momentum: 0.9
 weight_decay: 0.0005
 snapshot_prefix: "zf_faster_rcnn"
 iter_size: 2
</code></pre></div>    </div>

    <p><code class="language-plaintext highlighter-rouge">train.prototxt</code> describes the network structure, including number of layer, type of layer, number of neurons in each layer, etc. Again, refer to <a href="http://caffe.berkeleyvision.org/gathered/examples/mnist.html">Caffe’s MNIST tutorial</a> in order to understand <code class="language-plaintext highlighter-rouge">train.prototxt</code>.</p>
  </li>
</ol>

<hr />

<p><a name="Training on new dataset"></a></p>
<h3 id="part-3-training-on-new-dataset">Part 3. Training on new dataset</h3>

<p>In this part, <strong>basketball detection</strong> will be used as an example to illustrate how to train a new dataset using py-faster-rcnn.</p>

<p><img src="https://cloud.githubusercontent.com/assets/13748721/19177713/203fc01a-8c7e-11e6-8e7b-3f67d0755482.png" alt="basketball_detection_demo" /></p>

<h4 id="31-prepare-dataset">3.1. Prepare dataset</h4>

<p>The dataset used in this part is downloaded from ImageNet.</p>

<p>DISCLAIMER: This dataset should be only used for non-commercial research activities. Please follow the ImageNet rules about the use of the dataset.</p>

<ol>
  <li>
    <p>Download dataset</p>

    <p>Here provides a link to download <a href="https://www.dropbox.com/s/iywkgsrx2fx6t5q/basketball.tar.gz?dl=0">Basketball Dataset</a>. This dataset has the following structure.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> |-- basketball
     |-- JPEGImages 
         Contains all raw .JPEG images
     |-- ImageSets
         .txt files state training set, validataion set. Extension is not required in these files
     |-- Annotations
         Bounding boxes annotation for each image. The annotation files are written in .xml format. 
</code></pre></div>    </div>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> # Unzip the folder
 $ mv basketball.tar.gz $FRCN/data/
 $ cd $FRCN/data
 $ tar xzf basketball.tar.gz
</code></pre></div>    </div>
  </li>
  <li>
    <p>Add a dataset python file</p>

    <p>Add a <code class="language-plaintext highlighter-rouge">basketball.py</code> to <code class="language-plaintext highlighter-rouge">$FRCN/lib/datasets/</code>. You may check on the source code for reference. If you wish to modify this file, basically, you can just <em>find and replace</em> basketball by your new dataset name.</p>
  </li>
  <li>
    <p>Add <code class="language-plaintext highlighter-rouge">basketball_eval.py</code></p>

    <p>Add a <code class="language-plaintext highlighter-rouge">basketball_eval.py</code> to <code class="language-plaintext highlighter-rouge">$FRCN/lib/datasets/</code>. Again, check on the source code for reference. Again, <em>find and replace</em> basketabll.</p>
  </li>
  <li>
    <p>Update <code class="language-plaintext highlighter-rouge">/lib/datasets/factory.py</code></p>

    <p>The purpose of <code class="language-plaintext highlighter-rouge">basketball.py</code> is to read a part of whole dataset, such as train_set or val_set. The purpose of function in <code class="language-plaintext highlighter-rouge">factory.py</code> is to get all sets of whole dataset.</p>
  </li>
  <li>
    <p>Add config file</p>

    <p>As mentioned in Part 2.2 (2), we need a <code class="language-plaintext highlighter-rouge">config.yml</code> to store configurations. In here, we can use the original <code class="language-plaintext highlighter-rouge">faster_rcnn_end2end.yml</code> as a reference. However, there are many configurations you can set in this file. In here, we may set <code class="language-plaintext highlighter-rouge">EXP_DIR</code> first and others if necessary.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ cd $FRCN/experiments/cfgs
 $ cp faster_rcnn_end2end.yml config.yml
</code></pre></div>    </div>
  </li>
  <li>
    <p>Update <code class="language-plaintext highlighter-rouge">imdb.py</code></p>

    <p>Since new dataset may have conflicts in annotation with original PASCAL VOC dataset. For example, ImageNet images start with index 0 in row and col while PASCAL VOC dataset starts with index 1. In <code class="language-plaintext highlighter-rouge">imdb.py</code>, a part of code should be inserted in <code class="language-plaintext highlighter-rouge">append_flipped_images()</code>. Refer to source code.</p>
  </li>
</ol>

<h4 id="32-prepare-network-and-pre-trained-model">3.2. Prepare network and pre-trained model</h4>

<p>To train our own model, basically we don’t need to train the model from scratch unless you have a huge dataset which is comparable to ImageNet. Otherwise, we can train our model from fine-tuning a pre-trained Faster R-CNN model. The reason is because a pre-trained Faster R-CNN contains a lot of good lower level features, which can be used generally. Even you are using a new and self-defined architure (i.e. no existing pre-trained Faster R-CNN model), follow the training method of Faster R-CNN and train a Faster R-CNN first, followed by fine-tuning on your own dataset is suggested.</p>

<p>For simplicity, the network and model adopted in this part is ZF-net and a pre-trained Faster R-CNN (ZF) respectively.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cd $FRCN/models
# copy a well-defined network and make modification based on it
$ mkdir basketball
$ cp ./pascal_voc/ZF/faster_rcnn_end2end/* ./basketball/
$ cd basketball
</code></pre></div></div>

<p>Now, we should modify all files in <code class="language-plaintext highlighter-rouge">basketball/</code>, including,</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">solver.prototxt</code>
    <ul>
      <li>train_net</li>
      <li>snapshot_prefix</li>
      <li>Others if necessary</li>
    </ul>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">train.prototxt</code> &amp; <code class="language-plaintext highlighter-rouge">test.prototxt</code></p>

    <p>For <code class="language-plaintext highlighter-rouge">train.prototxt</code> and <code class="language-plaintext highlighter-rouge">val.prototxt</code>, basically we need to update the number of output in final layers. Let’s say, in this basketball dataset, we only need 2 classes (background + basketball) and 8 output for bounding box regressor. Orignial pascal_voc have 21 classes including background and 21*4 bounding box regressor output.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  $ cd $FRCN/models/basketball
  $ grep 21 *
  $ grep 84 *
  # These two commands help you to check the lines that you should modify in the files.
</code></pre></div>    </div>

    <p>In this part, there are two more items we need to modify. Since we are <strong>fine-tuning a pre-trained ConvNet model</strong> on our own dataset and the number of output at last fully-connected layers (cls_score &amp; bbox_pred) has been changed, the <strong>original weight</strong> in pre-trained ConvNet model is not suitable for our current network. The dimension is totally different. The details can be refered to <a href="http://caffe.berkeleyvision.org/gathered/examples/finetune_flickr_style.html">Caffe’s fine-tuning tutorial</a>. The solution is to rename the layers such that the weights for the layers will be initialized randomly instead of copying from pre-trained model (actually copying from pre-trained model will cause error).</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  name: "cls_score" -&gt; name: "cls_score_basketball"
  name: "bbox_pred" -&gt; name: "bbox_pred_basketball"
</code></pre></div>    </div>

    <p>However, renaming the layers may cause problems in later parts since “cls_score” and “bbox_pred” are used as keys in testing. Therefore, in the training part, we can train the model accroding to the following procedure.</p>
  </li>
</ul>

<ol>
  <li>Rename the layers to <em>cls_score_basketball</em> and <em>bbox_pred_basketball</em></li>
  <li>Fine-tune pre-trained Faster R-CNN (FRCN) model and snapshot at iteration 0. Let’s call the snapshot <strong>Basketball_0.caffemodel</strong>. Stop training.</li>
  <li>Rename the layers back to <em>cls_score</em> and <em>bbox_pred</em>.</li>
  <li>Fine-tune <strong>Basketball_0.caffemodel</strong> to get our final model.</li>
</ol>

<p>The details and code will be explained in the following part.</p>

<h4 id="33-training-and-evaluation">3.3. Training and evaluation</h4>

<p>Before training on your new dataset, you may need to check <code class="language-plaintext highlighter-rouge">$FRCN/data/cache</code> to remove caches if necessary. Caches stores information of previously trained dataset. It may cause problem while training.</p>

<ol>
  <li>
    <p>Rename the layers</p>

    <p>As mentions in the previous part, rename the two layers.</p>

    <p>Reminder: if you are using <em>find and replace</em>, please find the name with quotes(i.e. “cls_score”). If you just search for cls_score, without quotes, it may also replace some other layers since there is a layer named rpn_cls_score.</p>
  </li>
  <li>
    <p>First fine-tuning</p>

    <p>The purpose of first fine-tuning is to get a caffemodel which has two outputs at final fully-connected layers.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ ./tools/train_net.py --gpu 0 --weights data/faster_rcnn_models/ZF_faster_rcnn_final.caffemodel --imdb basketball_train --cfg experiments/cfgs/config.yml --solver models/basketball/solver.prototxt --iter 0
</code></pre></div>    </div>

    <p>After this fine-tuning, we should get the model we needed.</p>
  </li>
  <li>
    <p>Rename the layers back</p>

    <p>Rename the two layers back to <em>“cls_score”</em> and <em>“bbox_pred”</em>.</p>
  </li>
  <li>
    <p>Second fine-tuning</p>

    <p>This fine-tuning should train models for our final use. The pre-trained model in this stage is the model we saved in stage 2.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ ./tools/train_net.py --gpu 0 --weights output/basketball/train/zf_faster_rcnn_basketball_iter_0.caffemodel --imdb basketball_train --cfg experiments/cfgs/config.yml --solver models/basketball/solver.prototxt --iter 10000
</code></pre></div>    </div>
  </li>
  <li>
    <p>Evaluation / Testing</p>

    <p>To test the performance of trained model, we can use the provided <code class="language-plaintext highlighter-rouge">test_net.py</code> for the purpose.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ ./tools/test_net.py --gpu 0 --def models/basketball/test.prototxt --net output/basketball/train/zf_faster_rcnn_basketball_iter_20000.caffemodel --imdb basketball_val --cfg experiments/cfgs/config.yml
</code></pre></div>    </div>

    <p>At the end, you should be able to see something like this.</p>

    <p><img src="https://cloud.githubusercontent.com/assets/13748721/19177712/203d190a-8c7e-11e6-91e8-54ced87b9495.png" alt="result_sample" /></p>
  </li>
</ol>

<p>After going through such long path, training on py-faster-rcnn is completed!</p>

<hr />

<p><a name="Error and solution"></a></p>

<h3 id="part-4-error-and-solution">Part 4. Error and solution</h3>

<ol>
  <li>
    <p>no easydict, cv2</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> # Without Anaconda
 $ sudo pip install easydict
 $ sudo apt-get install python-opencv
    
 # With Anaconda
 $ conda install -c verydeep easydict
 $ conda install opencv
 # Normally, people will follow the online instruction at https://anaconda.org/auto/easydict and install auto/easydict. However, this easydict (ver.1.4) has a problem in passing the message of configuration and cause many unexpected error while verydeep/easydict (ver.1.6) won't cause these errors.
</code></pre></div>    </div>
  </li>
  <li>
    <p>assertionError: Selective Search data is not found</p>

    <p>Solution: install verydeep/easydict rather than auto/easydict</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ conda install -c verydeep easydict
</code></pre></div>    </div>
  </li>
  <li>
    <p>box [:, 0] &gt; box[:, 2]</p>

    <p>Solution: add the following code block in imdb.py</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> def append_flipped_images(self):
     num_images = self.num_images
     widths = self._get_widths()
     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
         boxes[:, 2] = widths[i] - oldx1
         for b in range(len(boxes)):
                 if boxes[b][2] &lt; boxes[b][0]:
                     boxes[b][0]=0
         assert (boxes[:, 2] &gt;= boxes[:, 0]).all()
</code></pre></div>    </div>
  </li>
  <li>
    <p>For ImageNet detection dataset, no need to minus one on coordinates</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> # Load object bounding boxes into a data frame.
 for ix, obj in enumerate(objs):
     bbox = obj.find('bndbox')
     # Make pixel indexes 0-based
     x1 = float(bbox.find('xmin').text)
     y1 = float(bbox.find('ymin').text)
     x2 = float(bbox.find('xmax').text)
     y2 = float(bbox.find('ymax').text)
     cls = self._class_to_ind[obj.find('name').text.lower().strip()]
</code></pre></div>    </div>
  </li>
</ol>

<h3 id="reference">Reference</h3>

<p><a href="http://blog.csdn.net/zhang_shuai12/article/details/52295438">zhang_shuai’s blog</a></p>

<p><a href="https://github.com/deboc/py-faster-rcnn/tree/master/help">deboc’s tutorial</a></p>]]></content><author><name>Huangying Zhan</name><email>zhanhuangying.work@gmail.com</email></author><category term="Detection" /><summary type="html"><![CDATA[Summary]]></summary></entry><entry><title type="html">GPU and Caffe Installation in Ubuntu</title><link href="https://huangying-zhan.github.io/2016/09/09/GPU-and-Caffe-installation-in-Ubuntu" rel="alternate" type="text/html" title="GPU and Caffe Installation in Ubuntu" /><published>2016-09-09T00:00:00-07:00</published><updated>2016-09-09T00:00:00-07:00</updated><id>https://huangying-zhan.github.io/2016/09/09/GPU-and-Caffe-installation-in-Ubuntu</id><content type="html" xml:base="https://huangying-zhan.github.io/2016/09/09/GPU-and-Caffe-installation-in-Ubuntu"><![CDATA[<h3 id="summary">Summary</h3>

<p><a href="http://caffe.berkeleyvision.org/">Caffe</a> is a deep learning framework developed by Berkeley Vision and Learning Center (BVLC). It is specifically designed for deep neural network training and application, especially for convolutional neural networks. However, the training/computation is time-consuming in CPU mode. Therefore, GPU computing is introduced to accelerate the computation. In this post, NVIDIA GTX-1080 is used. GTX-1080 and Caffe installation procedure is recorded. The whole process is operated in Ubuntu 14.04.</p>

<hr />

<h3 id="contents">Contents</h3>

<ol>
  <li><a href="#GTX-1080 installation">GTX-1080 installation</a></li>
  <li><a href="#Caffe installation">Caffe installation</a></li>
</ol>

<hr />

<p><a name="GTX-1080 installation"></a></p>
<h3 id="part-1-gtx-1080-installation">Part 1. GTX-1080 installation</h3>

<p>The installation of GTX-1080 mainly refers to <a href="yangcha.github.io/GTX-1080">yangcha’s tutorial</a>.</p>

<p>For different GPU devices, different driver should be installed. In here, the instruction is just for GTX-1080.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo add-apt-repository ppa:graphics-drivers/ppa
$ sudo apt-get update
$ sudo apt-get install nvidia-367
$ sudo apt-get install mesa-common-dev
$ sudo apt-get install freeglut3-dev
# Reboot the system to load the driver
$ sudo reboot
</code></pre></div></div>

<p><br />&lt;/br&gt;
___</p>

<p><a name="Caffe installation"></a></p>
<h3 id="part-2-caffe-installation">Part 2. Caffe installation</h3>

<p>In this part, a simple installation instruction of Caffe is recorded. Basically, the steps are as following. First, install some dependencies for Caffe; Second, download and install Caffe; Third, compile Caffe.</p>

<p>The installation mainly refers to the following websites.</p>

<ul>
  <li><a href="http://caffe.berkeleyvision.org/installation.html">Caffe’s installation guideline</a></li>
  <li><a href="http://caffe.berkeleyvision.org/install_apt.html">Caffe’s guideline (dependencies installation)</a></li>
</ul>

<p><br />&lt;/br&gt;</p>

<h4 id="21-install-cuda">2.1 Install CUDA</h4>

<p>If you do not have a NVIDIA GPU supporting CUDA, you actually can ignore this step and move on to next step. Running Caffe without GPU is still possible, but losing the GPU computing feature. Now, for GPU users, visit NVIDIA’s <a href="https://developer.nvidia.com/cuda-toolkit">cuda-toolkit</a> and download CUDA 8.0RC. However, this requrest requires a NVIDIA membership, so join it and download CUDA 8.0RC.</p>

<p>After entering the download page, you will see that there are 3 types of installer. Just pick one and follow the installation instructions.</p>

<p><img src="https://cloud.githubusercontent.com/assets/13748721/19178166/f7ba32ec-8c82-11e6-8f61-26166eadc6a1.png" alt="cuda" /></p>

<p>After installation, you need to set CUDA environment.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ echo "# Add CUDA bin &amp; library paths:" &gt;&gt; ~/.bashrc
$ echo "export PATH=/usr/local/cuda-8.0/bin:$PATH" &gt;&gt; ~/.bashrc
$ echo "export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib:$LD_LIBRARY_PATH" &gt;&gt; ~/.bashrc
$ source ~/.bashrc
</code></pre></div></div>

<p>If you later on find that this <code class="language-plaintext highlighter-rouge">export</code> doesn’t work for Caffe, you can directly update Makefile.config in Caffe. We will see.</p>

<p><br />&lt;/br&gt;</p>

<h4 id="22-install-dependencies">2.2. Install dependencies</h4>

<ol>
  <li>
    <p>Install general dependencies</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ sudo apt-get install libprotobuf-dev libleveldb-dev libsnappy-dev libopencv-dev libhdf5-serial-dev protobuf-compiler
    
 $ sudo apt-get install libboost-all-dev
</code></pre></div>    </div>
  </li>
  <li>
    <p>Install ATLAS</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ sudo apt-get install libatlas-base-dev
</code></pre></div>    </div>
  </li>
  <li>
    <p>Install remaining dependencies</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ sudo apt-get install libgflags-dev libgoogle-glog-dev liblmdb-dev
</code></pre></div>    </div>

    <p>If you are not using Ubuntu 14.04, you may not be able to install these dependencies. Please refer to <a href="http://caffe.berkeleyvision.org/install_apt.html">here</a>.</p>
  </li>
</ol>

<p><br />&lt;/br&gt;</p>

<h4 id="23-optional-anaconda-python">2.3. (Optional) Anaconda-python</h4>
<p>Anaconda is a package which includes a lot of useful python packages/libraries.
It is recommended to install Anaconda but not a compulsory part for Caffe.</p>

<p>Downalod the installer from the Anaconda’s <a href="https://www.continuum.io/downloads#linux">dowloads pag一e</a>.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cd ~/Downloads

# For different version's installer, 'xxx' is different, just refer to your downloaded installer.
$ bash Anaconda2-xxx.sh 
</code></pre></div></div>

<p>Follow the installation guideline and accept the statements.
After installation, open a new terminal and check for it by typing <code class="language-plaintext highlighter-rouge">python</code> in the terminal.
After entering Python, you should see the Python version is something like <code class="language-plaintext highlighter-rouge">Python 2.7.12 |Anaconda 4.1.1 (64-bit)|</code></p>

<p>Installation of Anaconda is completed! To know more, please refer to <a href="http://conda.pydata.org/docs/">Anaconda’s tutorial</a> or homepage.</p>

<p><br />&lt;/br&gt;</p>

<h4 id="24-optional-opencv">2.4. (Optional) OpenCV</h4>

<p>Official requirement: OpenCV &gt;=2.4, including 3.0. Installation of OpenCV is quite ugly, there are already some good instructions. Currently, this part is <strong>to be edited.</strong></p>

<ul>
  <li><a href="http://sysads.co.uk/2014/05/install-opencv-2-4-9-ubuntu-14-04-13-10/">OpenCV installation instruction</a></li>
</ul>

<p><br />&lt;/br&gt;</p>

<h4 id="25-download-caffe">2.5. Download Caffe</h4>

<p>First, <code class="language-plaintext highlighter-rouge">git</code> is required, can be installed by</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo apt-get install git
</code></pre></div></div>

<p>Then, clone caffe to a local directory</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ git clone https://github.com/BVLC/caffe.git
$ cd $CAFFE # $CAFFE is the directory of your downloaded Caffe
$ cp Makefile.config.example Makefile.config
</code></pre></div></div>

<p>You can modify the configuration before <code class="language-plaintext highlighter-rouge">make</code> in this <code class="language-plaintext highlighter-rouge">Makefile.config</code>. Here are some possible modifications.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Anaconda (Uncomment the related part)
# If you are using Anaconda2, remember to udpate ANACONDA_HOME to anaconda2, uncomment this part and comment the original python setup

# PYTHON_INCLUDE := /usr/include/python2.7 \
#                /usr/lib/python2.7/dist-packages/numpy/core/include

ANACONDA_HOME := $(HOME)/anaconda2
PYTHON_INCLUDE := $(ANACONDA_HOME)/include \
                 $(ANACONDA_HOME)/include/python2.7 \
                 $(ANACONDA_HOME)/lib/python2.7/site-packages/numpy/core/include \

# If you don't have a NVIDIA GPU supporting CUDA, you can uncomment a CPU-only switch to build without GPU support.
# CPU-only switch (uncomment to build without GPU support).
CPU_ONLY := 1

# Remember to update the CUDA_DIR as well.
$ CUDA_DIR := /usr/local/cuda-8.0
</code></pre></div></div>

<p>Then, we can start compiling Caffe.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ make clean
$ make all -j8 # where -j8 means use 8 cores of your CPU for compilation which can accelerate the compilation. you should change -j according to the number of your CPU cores. 
$ make test -j8
$ make runtest -j8
</code></pre></div></div>
<p>If there is no error up to this stage, Caffe installation is completed.</p>

<p><br />&lt;/br&gt;</p>

<h4 id="26-optional-install-pycaffe-python-caffe-interface">2.6. (Optional) Install PyCaffe (Python Caffe Interface)</h4>

<p>If Python interface is used, follow the guideline to install PyCaffe</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo apt-get install python-dev
$ cd $CAFFE/python

$ sudo apt-get install python-pip

$ for req in $(cat requirements.txt); do pip install $req; done

$ cd ..
$ make pycaffe
</code></pre></div></div>

<p>Up to here, the installation is completed!</p>]]></content><author><name>Huangying Zhan</name><email>zhanhuangying.work@gmail.com</email></author><category term="Caffe" /><summary type="html"><![CDATA[Summary]]></summary></entry><entry><title type="html">ZED Stereo Camera Setup and Practice on Jetson TK1</title><link href="https://huangying-zhan.github.io/2016/08/23/ZED-stereo-camera-setup-and-practice-on-Jetson-TK1" rel="alternate" type="text/html" title="ZED Stereo Camera Setup and Practice on Jetson TK1" /><published>2016-08-23T00:00:00-07:00</published><updated>2016-08-23T00:00:00-07:00</updated><id>https://huangying-zhan.github.io/2016/08/23/ZED-stereo-camera-setup-and-practice-on-Jetson-TK1</id><content type="html" xml:base="https://huangying-zhan.github.io/2016/08/23/ZED-stereo-camera-setup-and-practice-on-Jetson-TK1"><![CDATA[<h3 id="summary">Summary</h3>

<p>As the name given, ZED Stereo Camera(ZED) is a stereo camera produced by <a href="https://www.stereolabs.com/">Steteolabs</a>. Basically, ZED is able to capture high-resolution pictures and depth perception. For details, please refer to the official website. In this article, the installation and a simple practice example of ZED is provided. Again, all the produces are based on Ubuntu 14.04.</p>

<h3 id="contents">Contents</h3>

<ol>
  <li><a href="#Setup of ZED camera">Setup of ZED on TK1</a></li>
  <li><a href="#Capture picture and depth map">Capture picture and depth map</a></li>
  <li><a href="#Detection with Depth">Detection with Depth</a></li>
</ol>

<hr />
<p><a name="Setup of ZED camera"></a></p>
<h3 id="part-1-setup-of-zed-camera">Part 1. Setup of ZED camera</h3>

<p>The installation of ZED on TK1 is actually quite straightforward. The <a href="https://www.stereolabs.com/blog/index.php/2015/09/24/getting-started-with-jetson-tk1-and-zed/">official instruction: TK1 &amp; ZED</a> is well written. Just follow the steps and everything should be done. Here is a quick summary for all steps.</p>

<p><em>Requirement: (refer to <a href="https://huangying-zhan.github.io/2016/08/16/Caffe-installation-and-practice-on-Jetson-TK1.html#Caffe%20installation%20on%20TK1">here</a>)</em></p>

<ul>
  <li>CUDA 6.5 R.21</li>
  <li>openCV4tegra 2.4.10</li>
</ul>

<p>Now, let’s start!</p>

<ol>
  <li>
    <p>Enable USB3.0</p>

    <p>ZED Camera requires a USB3.0 port. TK1 has only one USB3.0 port. Make good use of it~</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ sudo vi /boot/extlinux/extlinux.conf
 # Replace ‘usb_port_owner_info=0‘ by ‘usb_port_owner_info=2‘.
 # Save and exit (*:wq*)
</code></pre></div>    </div>
  </li>
  <li>
    <p>Download and install ZED SDK for Jetson</p>

    <p>Visit <a href="https://www.stereolabs.com/developers/#download_anchor">ZED download page</a> and download ZED SDK for Jetson, which is a <em>.run</em> file</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ chmod +x ZED_SDK_JTK1_v*.run
 $ ./ZED_SDK_JTK1_v*.run
 # Accept the statement and follow installation instruction.
</code></pre></div>    </div>

    <p>Now, ZED SDK should be installed and there are many interesting demos. The SDK is installed at <code class="language-plaintext highlighter-rouge">/usr/local/zed</code> by default. However, before running these examples, you might encounter a problem, there is only one USB port on TK1. It is not enough for your keyboard, mouse, and ZED. Unless you have a USB3.0 hub, you need to <a href="https://huangying-zhan.github.io/2016/09/13/Linux-cheat-sheet.html#Remote">remote control</a> TK1 from your computer.</p>
  </li>
</ol>

<p><br />&lt;/br&gt;
___</p>

<p><a name="Capture picture and depth map"></a></p>
<h3 id="part-2-capture-picture-and-depth-map">Part 2. Capture picture and depth map</h3>

<h4 id="21-summary">2.1. Summary</h4>
<p>To study ZED, we can learn from it’s <a href="https://www.stereolabs.com/blog/">blog examples</a> or study the <a href="https://github.com/stereolabs">Github examples</a>. Basically, the examples are the same. Blog examples provide more detailed explanations but some parts of the code are quite outdated. The reason is that ZED released Ver.1.0 and made some changes. The blog examples were written before Ver.1.0. Nevertheless, Github examples provide update codes. In summary, study both at the same time should be more efficient.</p>

<p><br />&lt;/br&gt;</p>

<h4 id="22-hello-world">2.2. Hello World</h4>
<p>Before jumping to the later content, a simple <a href="https://www.stereolabs.com/blog/index.php/2015/07/15/hello-world/">“Hello-world” example</a> is suggested to be implemented by yourself first. Follow the instruction and build a Hello-World program. However, as mentioned before, the blog examples are quite outdated. Please use this <a href="https://www.dropbox.com/s/i9zhg15stjfgp5u/main-hello-world.cpp?dl=0">main-hello-world.cpp</a> and <a href="https://www.dropbox.com/s/uoe0iwjp582klq0/CMakeLists.txt?dl=0">CMakeLists.txt</a> to build the program. Remember to rename <em>main-hello-world.cpp</em> as <em>main.cpp</em>.</p>

<p><br />&lt;/br&gt;</p>

<h4 id="23-capture-pictures-and-depth-maps">2.3. Capture pictures and depth maps</h4>
<p>Suppose you have built your <code class="language-plaintext highlighter-rouge">Hello World</code>. In this part, we will see a simple modification based on a ZED’s <a href="https://github.com/stereolabs/zed-opencv">OpenCV example</a>. The ultimate goal is to capture RGB pictures, their corresponding dispartiy image and depth map from time to time. First, let’s have a taste on the original example.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cp /usr/local/zed/sample/cpu/with\ OpenCV ~/Desktop/zed_capture #copy and rename the example to desktop
$ cd $zed_capture # For simplicity, $zed_capture represents the full directory of /zed_capture
$ mkdir build
$ cd build
$ cmake ..
$ make # If you can see "Linking CXX executable "ZED with OpenCV" ", the program is built sucessfully
$ ./ZED\ with\ OpenCV
</code></pre></div></div>

<p>Play around with the program first. Then, download and rename <a href="https://www.dropbox.com/s/g2g7m0flsubfe5v/main_capture.cpp?dl=0">main-capture.cpp</a> as <em>main.cpp</em>.
Now, replace the original <em>main.cpp</em> by this new <em>main.cpp</em> and build the program again.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cd $zed_capture/build
$ make
$ ./ZED\ with\ OpenCV
</code></pre></div></div>

<p>This program allows you to save images, disparity images and depth maps from time to time. However, there are some settings you can modify in the <em>main.cpp</em>. Please refer to <em>main setup parameters</em> at the beginning of the code. After modification, you have to build the program again.</p>

<p><br />&lt;/br&gt;
___</p>

<p><a name="Detection with Depth"></a></p>

<h3 id="part-3-detection-with-depth">Part 3. Detection with Depth</h3>

<p>In this part, we are going to use both RGB images and depth maps in a detection algorithm. The detection algorithm is <a href="https://github.com/rbgirshick/py-faster-rcnn">Faster R-CNN</a>. Download and install py-faster-rcnn first by following the official guideline or Part 1 in <a href="https://huangying-zhan.github.io/2016/09/22/detection-faster-rcnn.html">my post</a>.</p>

<p>General speaking, the goal of this part is to find out the distance from the camera of detected objects. We also need this <a href="https://www.dropbox.com/s/o3hboq7svgm1reh/detection_depth_multiple.py?dl=0">detection_depth_multiple.py</a>. Save the script in <code class="language-plaintext highlighter-rouge">py-faster-rcnn/tools/</code>. This scipt is designed for VOC dataset only. However, making simple modifications can make this script works for other detection task under py-faster-rcnn framework.</p>

<p>Suppose you save RBG images at <code class="language-plaintext highlighter-rouge">$rgb_img_dir</code> and depth maps at <code class="language-plaintext highlighter-rouge">$depth_map_dir</code>.</p>

<ol>
  <li>
    <p>Update directories in line 210, 211 in <code class="language-plaintext highlighter-rouge">detection_depth_multiple.py</code>.</p>
  </li>
  <li>
    <p>Usage</p>

    <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="p">.</span><span class="o">/</span><span class="n">detection_depth_multiple</span><span class="p">.</span><span class="n">py</span> <span class="p">[</span><span class="n">options</span><span class="p">]</span>
 <span class="n">options</span><span class="p">:</span>
 <span class="o">--</span><span class="n">gpu</span> <span class="p">[</span><span class="n">GPU_ID</span><span class="p">]:</span> <span class="n">use</span> <span class="n">gpu</span> <span class="n">mode</span> <span class="ow">and</span> <span class="n">select</span> <span class="n">the</span> <span class="n">GPU</span> <span class="nb">id</span><span class="p">.</span>
 <span class="o">--</span><span class="n">cpu</span> <span class="p">:</span> <span class="n">use</span> <span class="n">cpu</span> <span class="n">mode</span>
 <span class="o">--</span><span class="n">net</span> <span class="p">[</span><span class="n">zf</span> <span class="o">/</span> <span class="n">vgg</span><span class="p">]:</span> <span class="n">select</span> <span class="n">the</span> <span class="n">network</span> <span class="ow">and</span> <span class="n">corresponding</span> <span class="n">model</span><span class="p">,</span> <span class="n">e</span><span class="p">.</span><span class="n">g</span><span class="p">.</span> <span class="n">zf</span><span class="p">,</span> <span class="n">vgg</span>
 <span class="o">--</span><span class="n">image_source</span> <span class="p">[</span><span class="mi">0</span> <span class="o">/</span> <span class="mi">1</span><span class="p">]:</span> <span class="n">there</span> <span class="n">are</span> <span class="n">two</span> <span class="n">kinds</span> <span class="n">of</span> <span class="nb">input</span> <span class="n">source</span> <span class="n">mode</span><span class="p">.</span> <span class="n">Mode</span> <span class="mi">0</span> <span class="n">means</span> <span class="n">online</span> <span class="n">loading</span><span class="p">,</span> <span class="n">which</span> <span class="n">loads</span> <span class="n">same</span> <span class="n">rgb</span> <span class="n">image</span> <span class="ow">and</span> <span class="n">depth</span> <span class="nb">map</span> <span class="k">from</span> <span class="n">the</span> <span class="n">directories</span><span class="p">.</span> <span class="n">Mode</span> <span class="mi">1</span> <span class="ow">is</span> <span class="n">offline</span> <span class="n">loading</span> <span class="n">mode</span><span class="p">.</span> <span class="n">It</span> <span class="n">loads</span> <span class="n">a</span> <span class="nb">set</span> <span class="n">of</span> <span class="n">images</span><span class="p">.</span>
 <span class="o">--</span><span class="n">mode</span> <span class="p">[</span><span class="mi">0</span> <span class="o">/</span> <span class="mi">1</span><span class="p">]:</span> <span class="n">There</span> <span class="n">are</span> <span class="n">two</span> <span class="n">modes</span><span class="p">.</span> <span class="n">Mode</span> <span class="mi">0</span> <span class="n">only</span> <span class="n">exports</span> <span class="n">numerical</span> <span class="n">information</span><span class="p">,</span> <span class="n">including</span> <span class="n">bounding</span> <span class="n">boxes</span> <span class="n">coordinates</span> <span class="ow">and</span> <span class="n">depth</span><span class="p">;</span> <span class="n">Mode</span> <span class="mi">1</span> <span class="n">visualizes</span> <span class="n">the</span> <span class="n">result</span><span class="p">.</span>
 <span class="o">--</span><span class="k">class</span> <span class="err">[</span><span class="nc">CLASS_ID</span><span class="p">,</span> <span class="p">...,</span> <span class="n">CLASS_ID</span><span class="p">]:</span> <span class="n">select</span> <span class="n">the</span> <span class="k">class</span> <span class="nc">indexs</span> <span class="n">that</span> <span class="n">you</span> <span class="n">are</span> <span class="n">going</span> <span class="n">to</span> <span class="n">detect</span><span class="p">.</span> <span class="n">In</span> <span class="n">VOC</span> <span class="n">dataset</span><span class="p">,</span> <span class="n">there</span> <span class="n">are</span> <span class="mi">20</span> <span class="n">classes</span><span class="p">.</span>
    
 <span class="c1"># Example: gpu mode, zf net, offline loading, output visualization, 15th class is interested
</span> <span class="p">.</span><span class="o">/</span><span class="n">detection_depth_multiple</span><span class="p">.</span><span class="n">py</span> <span class="o">--</span><span class="n">gpu</span> <span class="mi">0</span> <span class="o">--</span><span class="n">net</span> <span class="n">zf</span> <span class="o">--</span><span class="n">image_source</span> <span class="mi">1</span> <span class="o">--</span><span class="n">mode</span> <span class="mi">1</span> <span class="o">--</span><span class="k">class</span> <span class="err">[15]
</span></code></pre></div>    </div>
  </li>
</ol>

<h3 id="reference">Reference</h3>

<p><a href="https://www.stereolabs.com/blog/index.php/2015/09/24/getting-started-with-jetson-tk1-and-zed/">official blog: TK1 &amp; ZED</a></p>]]></content><author><name>Huangying Zhan</name><email>zhanhuangying.work@gmail.com</email></author><category term="JetsonTK1" /><category term="ZEDCamera" /><summary type="html"><![CDATA[Summary]]></summary></entry><entry><title type="html">Caffe Installation and Practice on Jetson TK1</title><link href="https://huangying-zhan.github.io/2016/08/16/Caffe-installation-and-practice-on-Jetson-TK1" rel="alternate" type="text/html" title="Caffe Installation and Practice on Jetson TK1" /><published>2016-08-16T00:00:00-07:00</published><updated>2016-08-16T00:00:00-07:00</updated><id>https://huangying-zhan.github.io/2016/08/16/Caffe-installation-and-practice-on-Jetson-TK1</id><content type="html" xml:base="https://huangying-zhan.github.io/2016/08/16/Caffe-installation-and-practice-on-Jetson-TK1"><![CDATA[<h3 id="summary">Summary</h3>

<p>Jetson Tegra-K1(<a href="http://www.nvidia.com/object/tegra-k1-processor.html">TK1</a>) is an embedded system provided by NVIDIA. It is designed for applications involving GPU computing, such as deep learning. While <a href="http://caffe.berkeleyvision.org/">Caffe</a> is a deep learning framework developed by Berkeley Vision and Learning Center (BVLC). This article records the procedures for installation of Caffe on TK1 and a simple implementation example, a real-time handwritten digit recognition system (<a href="http://yann.lecun.com/exdb/lenet/">LeNet</a>). All the procedures are based on Ubuntu 14.04.</p>

<center>![tk1](https://cloud.githubusercontent.com/assets/13748721/19178013/67c98378-8c81-11e6-90d5-236392c34759.png)</center>
<center><u>Jetson TK1</u></center>

<hr />

<h3 id="contents">Contents</h3>

<ol>
  <li><a href="#Caffe installation on TK1">Caffe installation on TK1</a></li>
  <li><a href="#Real-time handwritten digit recognition on TK1">Real-time handwritten digit recognition on TK1</a></li>
</ol>

<hr />
<p><a name="Caffe installation on TK1"></a></p>
<h3 id="part-1-caffe-installation-on-tk1">Part 1. Caffe installation on TK1</h3>

<h4 id="11-remote-access-tk1">1.1. Remote access TK1</h4>

<p>Remote accessing TK1 is not a compulsory procedure to operate TK1, provide that you have prepared necessary computer accessories, including a display monitor, a keyboard and mouse. However, if you prefer using your computer to operate TK1 remotely, there are many ways to do this. Here is a simple way using <em>ssh</em> service.</p>

<p>General speaking, you need to setup a ssh server on TK1 first, and then access TK1 from your own computer. Now, suppose your TK1 is connected to internet via ethernet, follow the <a href="https://huangying-zhan.github.io/2016/09/13/Linux-cheat-sheet.html#Remote">instruction</a> to remote access TK1 from your computer</p>

<p><br />&lt;/br&gt;</p>

<h4 id="12-install-prerequisites-for-caffe">1.2. Install prerequisites for Caffe</h4>

<p>Now, we need to install some prerequisites for Caffe, including,</p>

<ul>
  <li>General dependencies</li>
  <li>CUDA for ARM package</li>
  <li>OpenCV for Tegra</li>
</ul>

<ol>
  <li>
    <p>Install  general dependencies for Caffe</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ sudo add-apt-repository universe
 $ sudo apt-get install libprotobuf-dev protobuf-compiler gfortran \
 $ libboost-dev cmake libleveldb-dev libsnappy-dev \
 $ libboost-thread-dev libboost-system-dev \
 $ libatlas-base-dev libhdf5-serial-dev libgflags-dev \
 $ libgoogle-glog-dev liblmdb-dev gcc-4.7 g++-4.7 \
 $ libboost-all-dev
</code></pre></div>    </div>
  </li>
  <li>
    <p>Install CUDA package</p>

    <p>Visit <a href="https://developer.nvidia.com/linux-tegra-rel-21">NVIDIA’s developer page for Tegra</a> and download <em>CUDA 6.5 Toolkit for L4T Rel 21.x</em>. Let’s make directory on Desktop to store all downloaded package. The installation is based on the official <a href="http://elinux.org/Jetson/Installing_CUDA">CUDA for Jetson installation instruction</a>. If there is any unexpected problem, please refer to the official instruction.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ mkdir /home/ubuntu/Desktop/packages_for_caffe
 $ cd /home/ubuntu/Desktop/packages_for_caffe

 $ sudo dpkg -i cuda-repo-l4t-r21.2-6-5-prod_6.5-34_armhf.deb
 $ sudo apt-get update
 $ sudo apt-get install cuda-toolkit-6-5
 $ sudo usermod -a -G video $USER
    
 $ echo "# Add CUDA bin &amp; library paths:" &gt;&gt; ~/.bashrc
 $ echo "export PATH=/usr/local/cuda/bin:$PATH" &gt;&gt; ~/.bashrc
 $ echo "export LD_LIBRARY_PATH=/usr/local/cuda/lib:$LD_LIBRARY_PATH" &gt;&gt; ~/.bashrc
 $ source ~/.bashrc
</code></pre></div>    </div>

    <p>After installation of CUDA, run <code class="language-plaintext highlighter-rouge">nvcc -V</code> to check whether everything is installed correctly. 
 CUDA 6.5 should be installed.</p>
  </li>
  <li>
    <p>Install OpenCV for TK1</p>

    <p>Now, we can install OpenCV for Jetson. The installation is also based on the official <a href="http://elinux.org/Jetson/Installing_OpenCV">OpenCV for Jeton installation guideline</a>. Again, refer to the page if there is any problem. Before installation, visit <a href="https://developer.nvidia.com/linux-tegra-rel-21">NVIDIA’s developer page for Tegra</a> again and download <em>OpenCV4Tegra for L4T 21.x</em>.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ cd /home/ubuntu/Desktop/packages_for_caffe

 $ sudo dpkg -i libopencv4tegra-repo_l4t-r21_2.4.10.1_armhf.deb
 $ sudo apt-get update
 $ sudo apt-get install libopencv4tegra libopencv4tegra-dev
</code></pre></div>    </div>
  </li>
</ol>

<p><br />&lt;/br&gt;</p>

<h4 id="13-install-caffe-and-pycaffe">1.3. Install Caffe and PyCaffe</h4>

<p>In this part, we are finally going to download and install Caffe! First, make sure you have installed git <code class="language-plaintext highlighter-rouge">sudo apt-get install git</code>. PyCaffe is the Python interface for Caffe. For Caffe installation, there might be some unexpected errors. Please try to google the error. There must be other people encounted same error as you. Specifically, you can refer to the <a href="https://groups.google.com/forum/#!forum/caffe-users">Caffe Google group</a> or <a href="https://github.com/BVLC/caffe/issues">Caffe Github</a> and look for a solution to your problem.</p>

<ol>
  <li>
    <p>Clone and Complie Caffe</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> # Suppose you are going to install Caffe on Desktop
 $ cd /home/ubuntu/Desktop
 $ git clone https://github.com/BVLC/caffe.git
 $ cd $CAFFE # From now on, for simplicity, $CAFFE refers to Caffe's directory
 $ cp Makefile.config.example Makefile.config
 $ sudo apt-get install gcc-4.6 g++-4.6 gcc-4.6-multilib g++-4.6-multilib
 $ sed -i "s/# CUSTOM_CXX := g++/CUSTOM_CXX := g++-4.6/" Makefile.config

 $ make all -j4
 $ make test -j4
 # After installation, runtest to test Caffe layers.
 $ make runtest -j4
 # Run a benchmark test to check again.
 $ build/tools/caffe time --model=models/bvlc_alexnet/deploy.prototxt --gpu=0
</code></pre></div>    </div>
  </li>
  <li>
    <p>Install Python related package</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ cd $CAFFE/python
 $ sudo apt-get install python-pip
 $ for req in $(cat requirements.txt); do sudo pip install $req; done
 $ cd ../
 $ make all
 $ sudo apt-get install python-numpy
 $ make pycaffe
</code></pre></div>    </div>
  </li>
</ol>

<p>Up to this stage, if you didn’t encounter any error. Caffe is installed on TK1!</p>

<p><br />&lt;/br&gt;
___</p>

<p><a name="Real-time handwritten digit recognition on TK1"></a></p>
<h3 id="part-2-real-time-handwritten-digit-recognition">Part 2. Real-time handwritten digit recognition</h3>

<p>In this part, we will see how to train a classical convolutional neural network (<a href="http://yann.lecun.com/exdb/lenet/">LeNet</a>) on TK1 and implement a handwritten digit recognition system in real-time. Actually, TK1 is not designed for deep neural network training due to its hardware limits. It is more likely an embedded device for implementation of trained neural network models. Therefore, <strong>DON’T TRAIN</strong> other deep neural networks on TK1. However, our ultimate goal is to build a real-time recognition system using TK1. We certainly need a trained model.</p>

<p>For the preparation of dataset and network training, basically, follow the tutorial of <a href="http://caffe.berkeleyvision.org/gathered/examples/mnist.html">MNIST example</a> in Caffe official page.</p>

<h4 id="21--train-lenet">2.1.  Train LeNet</h4>

<ol>
  <li>
    <p>Prepare dataset</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ cd $CAFFE
 $ ./data/mnist/get_mnist.sh
 $ ./examples/mnist/create_mnist.sh
</code></pre></div>    </div>
  </li>
  <li>
    <p>Train LeNet
 This step takes about 15 minutes. Go and make a cup of coffee first~</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> $ cd $CAFFE_ROOT
 $ ./examples/mnist/train_lenet.sh # The trained model is stored in $CAFFE/example/mnist/ and named *lenet_iter_10000.caffemodel*
</code></pre></div>    </div>

    <p>Now, LeNet model is ready for use!</p>
  </li>
</ol>

<p><br />&lt;/br&gt;</p>

<h4 id="22-real-time-recognition">2.2. Real-time recognition</h4>

<p>A simple <a href="https://www.dropbox.com/s/dbbaeoddwfg4cfg/end_to_end_digit_recognition.py?dl=0">end-to-end-digit recognition</a> written by Python is provided for testing LeNet. However, make sure that you are using a white paper and the digit written on the paper is large enough. If the digit is too small / lines are too thin, the system might not be able to recognize the digit correctly. Before the details of real-time implementation, we try to recognize a digit in a single picture first.</p>

<ol>
  <li>Take a photo and store as $CAFFE/data/mnist/sample_digit.png</li>
  <li>Run <code class="language-plaintext highlighter-rouge">python end_to_end_digit_recognition.py</code></li>
</ol>

<p>To make this as a real-time implementation, there are many ways, such as reading captured image from camera or reading a locally saved  picutre from time to time. The later one is implemented since it suits to different cameras. Basically, the idea is,</p>

<ol>
  <li>Use a camera to capture and save pictures from time to time</li>
  <li>The saved picture must be stored in same directory and same name, i.e. <em>sample_digit.png</em></li>
  <li><code class="language-plaintext highlighter-rouge">end_to_end_digit_recognition.py</code> reads the picture from time to time.</li>
</ol>

<p>Here is a simple demo video.</p>

<iframe width="427" height="240" src="https://www.youtube.com/embed/5_aONXUhKbE" frameborder="0" allowfullscreen=""></iframe>

<p><br />&lt;/br&gt;</p>

<h3 id="reference">Reference</h3>

<p><a href="https://petewarden.com/2014/10/25/how-to-run-the-caffe-deep-learning-vision-library-on-nvidias-jetson-mobile-gpu-board/">Run caffe on TK1</a></p>]]></content><author><name>Huangying Zhan</name><email>zhanhuangying.work@gmail.com</email></author><category term="Caffe" /><category term="JetsonTK1" /><category term="MNIST" /><summary type="html"><![CDATA[Summary]]></summary></entry></feed>