TensorFlow多物體檢測(Object Detection API)

下載安裝

  1. 首先,下載tensorflow/models,命令:git clone https://github.com/tensorflow/models.git;
  2. 編譯proto文件,從models/research執行以下命令:protoc object_detection/protos/*.proto --python_out=.,windows系統需要逐個編譯。
    安裝protobuf,從https://github.com/google/protobuf/releases下載編譯好的文件包protoc-*-win32.zip。然後,解壓並把bin加入到可執行目錄或系統的path路徑。

問題記錄

  1. windows環境下,object_detection模塊Not found的問題。
    標準做法是,在models/research目錄下執行export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim。而在windows環境中需要在Anaconda安裝目錄的Lib目錄中添加tensorflow_model.pth文件,文件內容爲:
F:\tensorflow\models\research
F:\tensorflow\models\research\slim
  1. 安裝完成測試時,serialized_options參數問題。
    測試命令(在models/research目錄下執行):python .\object_detection\builders\model_builder_test.py
    問題文件:models\research\object_detection\protos\grid_anchor_generator_pb2.py
    該文件是grid_anchor_generator.proto使用protoc object_detection\protos\grid_anchor_generator.proto --python_out=.編譯得出的。該問題是,使用了多餘的serialized_options=None全局替換爲空即可(從文件中刪除所有的)。

啓動,圖片目標檢測

models/research/object_detection目錄下,打開cmd窗口,輸入 jupyter notebook,打開瀏覽器窗口;
頁面找到object_detection_tutorial.ipynb示例文件,單擊進入;
使用shift + enter依次執行命令,最後看到圖片檢測效果:
圖片中狗的檢測結果,還不錯哦!

檢測自己的圖片

把圖片放置在models\research\object_detection\test_images目錄中,比如新圖片爲image3.jpg。
把圖片檢測的代碼單獨提取出來,定義爲 detect_image(image_path):

def detect_image(image_path):
  image = Image.open(image_path)
  # the array based representation of the image will be used later in order to prepare the
  # result image with boxes and labels on it.
  image_np = load_image_into_numpy_array(image)
  # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  image_np_expanded = np.expand_dims(image_np, axis=0)
  # Actual detection.
  output_dict = run_inference_for_single_image(image_np, detection_graph)
  # Visualization of the results of a detection.
  vis_util.visualize_boxes_and_labels_on_image_array(
      image_np,
      output_dict['detection_boxes'],
      output_dict['detection_classes'],
      output_dict['detection_scores'],
      category_index,
      instance_masks=output_dict.get('detection_masks'),
      use_normalized_coordinates=True,
      line_thickness=8)
  plt.figure(figsize=IMAGE_SIZE)
  plt.imshow(image_np)

執行檢測命令detect_image('test_images/image3.jpg),得到如下的檢測結果:
簡單背景的

模型對比


  1. MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
    ssd
  2. MODEL_NAME = 'faster_rcnn_resnet101_coco_11_06_2017'
    faster

faster的精度明顯更高,檢測到的物體種類更多,花費的時間更長。
更換模型,修改模型的名字,重新下載新的模型,再重新加載到網絡中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章