This blog is to explain how to install Tensorflow object detection API in Anaconda in Windows 10 as well as how to train train a convolution neural network to do object detection on your own data set.

Steps:

1. Installation and Configuration

Install Anaconda

First we need to install Anaconda on Windows 10. For specific introduction see this link

https://medium.com/@GalarnykMichael/install-python-on-windows-anaconda-c63c7c3d1444

After we have installed Anaconda in windows, lets start to install tensorflow

Install Tensorflow

open an Anaconda Prompt and run the following code

C:\>conda create --name tf_obj_detect python=3.6

This command will create an environment first named with ‘tf_obj_detect’ and will install all the packages required by python3.5. (I tried to install tensorflow-gpu at frist but failed, so I switch to install regular tensorflow)

Then, activate the environment by issuing

C:\>conda activate tf_onj_detect

Install tensorflow-gpu in this environment by issuing

(tf_obj_detect)C:\>pip install tensorflow

Install the other necessary packages by issuing the following commands

(tf_obj_detect) C:\> pip install pillow
(tf_obj_detect) C:\> pip install lxml
(tf_obj_detect) C:\> pip install Cython
(tf_obj_detect) C:\> pip install jupyter
(tf_obj_detect) C:\> pip install matplotlib
(tf_obj_detect) C:\> pip install pandas
(tf_obj_detect) C:\> pip install opencv-python

Download TensorFlow Object Detection API repository from GitHub

Create a folder named tensorflow1 in C, this working directory will contain all  Tensorflow object detection frameworks, and also the test/train images, configuration files etc. Download the full Tensorflow object detection repository  by clicking Clone or download. Open the downloaded file and extract the model-master file to the C:\tensorflow1 and rename the models-master folder to models

Download Faster-RCNN-Inception-V2 model

This post will use the Faster-RCNN-Inception-V2 model, you could download the model here . Open the downloaded file and   faster_rcnn_inception_v2_coco_2018_01_28 folder to the C:\tensorflow1\models\research\object_detection folder. (Note: The model date and version will likely change in the future, but it should still work with this post.)

Download useful python script

Download the repositoryhere. It contains useful python scripts for generating the training data. extract all the contents directly into the C:\tensorflow1\models\research\object_detection directory

To train our own dataset we need to delete the following files

  • All files in \object_detection\images\train and \object_detection\images\test
  • The “test_labels.csv” and “train_labels.csv” files in \object_detection\images
  • All files in \object_detection\training
  • All files in \object_detection\inference_graph

Configure PYTHONPATH environment variable

(test) C:\> set PYTHONPATH=C:\tensorflow1\models;C:\tensorflow1\models\research;C:\tensorflow1\models\research\slim

  (Note: Every time the "tensorflow1" virtual environment is exited, the PYTHONPATH variable is reset and needs to be set up again.)

Compile Protobufs and run setup.py'

The compilation command posted on TensorFlow’s Object Detection API ,https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md, does not work on Windows. In the Anaconda Command Prompt, change directories to the \models\research directory and copy and paste the following command into the command line and press Enter:

protoc --python_out=. .\object_detection\protos\anchor_generator.proto .\object_detection\protos\argmax_matcher.proto .\object_detection\protos\bipartite_matcher.proto .\object_detection\protos\box_coder.proto .\object_detection\protos\box_predictor.proto .\object_detection\protos\eval.proto .\object_detection\protos\faster_rcnn.proto .\object_detection\protos\faster_rcnn_box_coder.proto .\object_detection\protos\grid_anchor_generator.proto .\object_detection\protos\hyperparams.proto .\object_detection\protos\image_resizer.proto .\object_detection\protos\input_reader.proto .\object_detection\protos\losses.proto .\object_detection\protos\matcher.proto .\object_detection\protos\mean_stddev_box_coder.proto .\object_detection\protos\model.proto .\object_detection\protos\optimizer.proto .\object_detection\protos\pipeline.proto .\object_detection\protos\post_processing.proto .\object_detection\protos\preprocessor.proto .\object_detection\protos\region_similarity_calculator.proto .\object_detection\protos\square_box_coder.proto .\object_detection\protos\ssd.proto .\object_detection\protos\ssd_anchor_generator.proto .\object_detection\protos\string_int_label_map.proto .\object_detection\protos\train.proto .\object_detection\protos\keypoint_box_coder.proto .\object_detection\protos\multiscale_anchor_generator.proto .\object_detection\protos\graph_rewriter.proto

(Note: TensorFlow occassionally adds new .proto files to the \protos folder. If you get an error saying ImportError: cannot import name 'something_something_pb2' , you may need to update the protoc command to include the new .proto files.)

Finally, run the following commands from the C:\tensorflow1\models\research directory:

(test) C:\tensorflow1\models\research> python setup.py build
(test) C:\tensorflow1\models\research> python setup.py install

Test Tensorflow object API works properly

once you finish the installation, you can verify installation is working by launching the object_detection_tutorial.ipynb script with Jupyter. From the \object_detection directory, issue this command:

(test) C:\tensorflow1\models\research\object_detection> jupyter notebook object_detection_tutorial.ipynb

Go to the Cell menu option, and then "Run All." you should see two labeled images at the bottom section the page. If you see this, then everything is working properly! If not, the bottom section will report any errors encountered.

                

2. Build your own dataset

Gather pictures

I use the To obtain a robust detector, the training data should have different background and illumination condition.There should be some images where the desired object is partially obscured, overlapped with something else, or only halfway in the picture.

For my bolt detector I only have one object, bolt, to detect. The original dataset is quite small, only have  30 images. To enlarge my dataset I first crop the images and then do the data agumentation on the cropped images. I use the code in this page for data augmentation, and now there are more than 300 pictures in my datasets

Label pictures

Next download and install LabelImg, point it to your \images\train directory, and then draw a box around each object in each image. Repeat the process for all the images in the \images\test directory. This will take a whileLabelImg could generate XML file containing label data for each image. We need to convert these XML files to singular CSV files that can be then converted to the TFRecord files which are one of the inputs to the TensorFlow trainer. These XML files should be placed in the same folder and same name with images, but with .xml-extension,

Generating training data

To do this I make use of python scripts from datitrans github. ,with some slight modifications to work with our directory structure. To begin, we're going to usexml_to_csv.py.   From the \object_detection folder, issue the following command in the Anaconda command prompt:

(test) C:\tensorflow1\models\research\object_detection> python xml_to_csv.py

Now, grab generate_tfrecord.py. The only modification that you will need to make here is in the class_text_to_int function. You need to change this to your specific class. In our case, we just have ONE class, we will replace the following code in generate_tfrecord.py:

# TO-DO replace this with label map
def class_text_to_int(row_label):
if row_label == 'nine':
return 1
elif row_label == 'ten':
return 2
elif row_label == 'jack':
return 3
elif row_label == 'queen':
return 4
elif row_label == 'king':
return 5
elif row_label == 'ace':
return 6
else:
return None

  with this

# TO-DO replace this with label map
def class_text_to_int(row_label):
if row_label == 'bolt':
return 1
else:
None

  Then, generate the TFRecord files by issuing these commands from the \object_detection folder:

python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record
python generate_tfrecord.py --csv_input=images\test_labels.csv --image_dir=images\test --output_path=test.record

3. Create Labelmap and Configure Training

Label Map

The label map tell the classifier what each object is by definig a map from the class names to class IDs. Create a labelmap.pbtxt in\object_detection\training folder. The type in the label map in the format below

item {
id: 1
name: 'bolt'
}

  

 Configure training

Navigate to C:\tensorflow1\models\research\object_detection\samples\configs and copy the faster_rcnn_inception_v2_pets.config file into the \object_detection\training directory. Then make the following changes to the faster_rcnn_inception_v2_pets.config file

  • Line 9. Change num_classes to the number of different objects you want the classifier to detect. For the above basketball, shirt, and shoe detector, it would be num_classes : 3 .

  • Line 110. Change fine_tune_checkpoint to:

    • fine_tune_checkpoint : "C:/tensorflow1/models/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt"
  • Lines 126 and 128. In the train_input_reader section, change input_path and label_map_path to:

    • input_path : "C:/tensorflow1/models/research/object_detection/train.record"
    • label_map_path: "C:/tensorflow1/models/research/object_detection/training/labelmap.pbtxt"
  • Line 132. Change num_examples to the number of images you have in the \images\test directory.

  • Lines 140 and 142. In the eval_input_reader section, change input_path and label_map_path to:

    • input_path : "C:/tensorflow1/models/research/object_detection/test.record"
    • label_map_path: "C:/tensorflow1/models/research/object_detection/training/labelmap.pbtxt"

Save the file after the changes have been made. That’s it! The training job is all configured and ready to go!

4. Run Training

Move train.py from /object_detection/legacy into the /object_detection folder and issue the following command to begin training:

python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config

If everything has been set up correctly, TensorFlow will initialize the training. The initialization can take up to 30 seconds before the actual training begins. When training begins, it will look like this:

You'd better train your model to train until the loss consistently drops below 0.05, which will take about 50,000 steps for me.

You can view the progress of the training job by using TensorBoard. To do this, open a new instance of Anaconda Prompt, activate the tensorflow1 virtual environment, change to the C:\tensorflow1\models\research\object_detection directory, and issue the following command

(test) C:\tensorflow1\models\research\object_detection>tensorboard --logdir=training

If you see nothing in the tensorboard in IE try to use chorme. Here is my result.

5. Export Inference Graph

The last step is to generate the frozen inference graph (.pb file). From the \object_detection folder, issue the following command, where “XXXX” in “model.ckpt-XXXX” should be replaced with the highest-numbered .ckpt file in the training folder:

python export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_pets.config
--trained_checkpoint_prefix training/model.ckpt-XXXX --output_directory inference_graph

This creates a frozen_inference_graph.pb file in the \object_detection\inference_graph folder. The .pb file contains the object detection classifier.

6. Test on your own dataset

I copied some of my images into the models/object_detection/test_images directory, and renamed them to be image3.jpg, image4.jpg...etc. Booting up jupyter notebook and opening the object_detection_tutorial.ipynb with some modifications. First head to the Variables section, and let's change the model name, and the paths to the checkpoint and the labels:

# What model to download.
MODEL_NAME = 'inference_graph' # Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb' # List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('training', 'labelmap.pbtxt') NUM_CLASSES = 1

  

Next, we can just delete the entire Download Model section, since we don't need to download anymore.

Finally, in the Detection section, change the TEST_IMAGE_PATHS var to:

TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(4, 13) ]

  

With that, you can go to the Cell menu option, and then "Run All."

Here are a few of my results:

Referencehttps://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10

        https://pythonprogramming.net/testing-custom-object-detector-tensorflow-object-detection-api-tutorial/?completed=/training-custom-objects-tensorflow-object-detection-api-tutorial/

Install Tensorflow object detection API in Anaconda (Windows)的更多相关文章

  1. Tensorflow object detection API ——环境搭建与测试

    1.开发环境搭建 ①.安装Anaconda 建议选择 Anaconda3-5.0.1 版本,已经集成大多数库,并将其作为默认python版本(3.6.3),配置好环境变量(Anaconda安装则已经配 ...

  2. 对于谷歌开源的TensorFlow Object Detection API视频物体识别系统实现教程

    本教程针对Windows10实现谷歌近期公布的TensorFlow Object Detection API视频物体识别系统,其他平台也可借鉴. 本教程将网络上相关资料筛选整合(文末附上参考资料链接) ...

  3. 安装运行谷歌开源的TensorFlow Object Detection API视频物体识别系统

    Linux安装 参照官方文档:https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/inst ...

  4. Tensorflow object detection API 搭建物体识别模型(三)

    三.模型训练 1)错误一: 在桌面的目标检测文件夹中打开cmd,即在路径中输入cmd后按Enter键运行.在cmd中运行命令: python /your_path/models-master/rese ...

  5. Tensorflow object detection API(1)---环境搭建与测试

    参考: https://blog.csdn.net/dy_guox/article/details/79081499 https://blog.csdn.net/u010103202/article/ ...

  6. 使用TensorFlow Object Detection API+Google ML Engine训练自己的手掌识别器

    上次使用Google ML Engine跑了一下TensorFlow Object Detection API中的Quick Start(http://www.cnblogs.com/take-fet ...

  7. 谷歌开源的TensorFlow Object Detection API视频物体识别系统实现教程

    视频中的物体识别 摘要 物体识别(Object Recognition)在计算机视觉领域里指的是在一张图像或一组视频序列中找到给定的物体.本文主要是利用谷歌开源TensorFlow Object De ...

  8. Tensorflow object detection API 搭建属于自己的物体识别模型

    一.下载Tensorflow object detection API工程源码 网址:https://github.com/tensorflow/models,可通过Git下载,打开Git Bash, ...

  9. Tensorflow object detection API 搭建物体识别模型(一)

    一.开发环境 1)python3.5 2)tensorflow1.12.0 3)Tensorflow object detection API :https://github.com/tensorfl ...

随机推荐

  1. sklearn中的pipeline的创建与访问

    前期博文提到管道(pipeline)在机器学习实践中的重要性以及必要性,本文则递进一步,探讨实际操作中管道的创建与访问. 已经了解到,管道本质上是一定数量的估计器连接而成的数据处理流,所以成功创建管道 ...

  2. 深入浅出的JS执行机制(图文教程)

    前序 作为一个有理想有抱负的前端攻城狮,想要走向人生巅峰,我们必须将我们使用的功法练到天人合一的地步.我在们日常工作中,使用最多的语言就是JavaScript了,为了写出完美的.能装逼的代码,我们必须 ...

  3. python基础(2)字符串常用方法

    python字符串常用方法 find(sub[, start[, end]]) 在索引start和end之间查找字符串sub ​找到,则返回最左端的索引值,未找到,则返回-1 ​start和end都可 ...

  4. HDFS中的NameNode名节点——FSimage

    HDFS缓冲区 Fsimage 文件映射,Edits文件操作记录. 与ES的缓冲区不同,ES是维护数据的变更,而HDFS缓冲区是用于名结点维护文件系统元数据(目录树)的机制. 在HDFS集群中,Nam ...

  5. iOS拍照定制之AVCapturePhotoOutput

    问题 领导安排任务,写个拍照功能,界面跟系统拍照有点出入 拍完照片,底部显示已拍照片,有个拍照上限[在此不论] 点击已拍照片,可以预览.放大缩小查看 思路 系统拍照肯定不行了,只能定制,没提是否拍照禁 ...

  6. nacos集群

    本章分析一下nacos集群之间nacos服务器上线,下线原理 每5秒运行定时任务ServerListManager.ServerListUpdater获取新上线的节点或下线的节点 每2秒运行定时任务S ...

  7. 聊聊Dotnet的垃圾回收

    最近在做一个项目,用到了大量的非托管技术,所以垃圾回收变得很重要.   在说垃圾回收之前,先说说两个概念: 托管代码,是由CLR管理的代码 非托管代码,是由操作系统直接执行的代码 在早期C++的时候, ...

  8. pytorch(09)transform模块(基础)

    transforms transforms运行机制 torchvision.transforms:常用的图像预处理方法 torchvision.datasets:常用数据及的dataset实现,mni ...

  9. docker 部署mysql服务之后,执行sql脚本

    1,先将.sql文件copy到docker容器里 docker ps //找到容器的短ID或者指定的name. docker inspect  -f '{{.Id}}' id or name 得到指定 ...

  10. 代理模式详解:静态代理、JDK动态代理与Cglib动态代理

    代理模式简介分类 概念 ​ 代理,是为了在不修改目标对象的基础上,增强目标方法的业务逻辑. ​ 客户类需要执行的是目标对象的目标方法,但是真正执行的是代理对象的代理方法,客户类对目标对象的访问是通过代 ...