【CV12】如何在Keras使用 Mask R-CNN 進行目標檢測



1. Mask R-CNN for Object Detection

目標檢測(Object Detection)是一類計算機視覺任務,涉及定位(localizing)圖像中的一個或多個目標以及對圖像中的每個目標進行分類。這是一項具有挑戰性的計算機視覺任務,需要成功進行目標定位以在圖像中的每個目標周圍定位和繪製邊界框(bounding box),還需要目標分類以預測已定位目標的正確類別。

目標檢測的擴展涉及標記圖像中屬於每個檢測到的目標的特定像素,而不是在目標定位(object localization)過程中使用粗糙的邊界框。此問題的較難版本通常稱爲目標分割(object segmentation)或語義分割(semantic segmentation)。

基於區域的卷積神經網絡(Region-Based Convolutional Neural Network,R-CNN)是由Ross Girshick等人開發的一系列用於目標檢測的卷積神經網絡模型。該方法有四個主要變體,最新的模型稱爲Mask R-CNN。四個變體分別如下:

  • 【R-CNN】: 邊界框是由**選擇性搜索(selective search)**算法提出的,每個邊界框都經過拉伸,並通過深度卷積神經網絡(例如AlexNet)提取特徵,然後使用線性SVM進行最終的對象分類。
  • 【Fast R-CNN】: 使用單個模型的簡化設計,仍將邊界框指定爲輸入,但是在深CNN合併區域後將使用感興趣區域池化層來合併區域,並且該模型可以直接預測類標籤和感興趣區域(regions-of-interest)
  • 【Faster R-CNN】: 添加區域提議網絡(Region Proposal Network),該網絡解釋從深層CNN中提取的特徵並學習直接提議感興趣的區域。
  • 【Mask R-CNN】: Faster R-CNN的擴展,增加了用於預測每個檢測到的對象的mask的輸出模型。

2018年的論文Mask R-CNN中介紹的Mask R-CNN模型是R-CNN模型的最新變體,同時支持目標檢測和目標分割,這篇文章提供了關於此模型的很好的總結:

The Region-based CNN (R-CNN) approach to bounding-box object detection is to attend to a manageable number of candidate object regions and evaluate convolutional networks independently on each RoI. R-CNN was extended to allow attending to RoIs on feature maps using RoIPool, leading to fast speed and better accuracy. Faster R-CNN advanced this stream by learning the attention mechanism with a Region Proposal Network (RPN). Faster R-CNN is flexible and robust to many follow-up improvements, and is the current leading framework in several benchmarks.

這一系列方法可能是最有效的對象檢測方法,從而可以在計算機視覺基準數據集上獲得最新的結果。儘管是準確的,但是與諸如YOLO之類的替代模型(準確性較低但專爲實時預測而設計)相比,進行預測時模型可能會變慢。


2. Matterport Mask R-CNN Project

Mask R-CNN的實現比較複雜,尤其是與簡單甚至最新的深度卷積神經網絡模型相比。R-CNN模型的每個版本均提供源代碼,這些代碼在單獨的GitHub存儲庫中提供,並具有基於Caffe深度學習框架的原型模型。例如:

可以使用Keras構建的可靠第三方實現,而無需從頭開發R-CNN或Mask R-CNN模型的實現。Mask R-CNN最好的第三方實現是Matterport開發的Mask R-CNN項目,該項目是根據MIT許可證開放源代碼發佈的,該代碼已廣泛用於各種項目和Kaggle競賽中。

該項目提供了許多Python筆記本形式的示例,可以通過以下兩個筆記本來了解其如何使用:

Matterport庫中,使用Mask R-CNN模型有三個主要用例:

  • 【Object Detection Application】: 使用預先訓練的模型對新圖像進行對象檢測。
  • 【New Model via Transfer Learning】: 以預先訓練的模型爲起點,爲新的對象檢測數據集開發模型。
  • 【New Model from Scratch】: 從頭開始開發一個新的模型對象檢測數據集。

3. Object Detection With Mask R-CNN

3.1 安裝 Mask R-CNN

git clone https://github.com/matterport/Mask_RCNN.git

cd Mask_RCNN

python setup.py install

# 確認是否安裝成功
pip show mask-rcnn

3.2 目標檢測流程

下載模型權重:mask_rcnn_coco.h5

準備樣本照片:elephant.jpg

加載模型並進行預測:
首先,必須通過實例MaskRCNN類定義模型,此類需要配置對象作爲參數,配置對象定義在訓練或推理期間如何使用模型。在這種情況下,配置將僅指定每批圖像的數量以及要預測的類的數量。可以在config.py文件中配置對象的完整範圍以及可以覆蓋的屬性。

# define the test configuration
class TestConfig(Config):
     NAME = "test"
     GPU_COUNT = 1
     IMAGES_PER_GPU = 1
     NUM_CLASSES = 1 + 80

定義MaskRCNN實例。將模型定義爲推斷類型,表示要做預測而非訓練。還必須指定一個目錄,可以在其中寫入任何日誌消息。

# define the model
rcnn = MaskRCNN(mode='inference', model_dir='./', config=TestConfig())

加載下載的權重:

# load coco model weights
rcnn.load_weights('mask_rcnn_coco.h5', by_name=True)

對圖像進行預測:

# load photograph
img = load_img('elephant.jpg')
img = img_to_array(img)
# make prediction
results = rcnn.detect([img], verbose=0)

結果包含傳遞到detect()函數中的每個圖像的字典,在這種情況下,是一個圖像的單個字典的列表。

字典具有用於邊界框,mask等的鍵,每個鍵都指向圖像中檢測到的多個可能目標的列表。註釋字典的鍵如下:

  • rois:檢測到的目標的bound boxes或感興趣區域(regions-of-interest,ROI)。
  • masks:檢測到的目標的mask。
  • class_ids:檢測到的目標的類。
  • scores:每個預測類別的概率或置信度。

可以通過首先獲取第一張圖像的字典(例如results [0]),然後檢索邊界框的列表(例如[‘rois’])來繪製圖像中檢測到的每個框。

boxes = results[0]['rois']

每個邊界框都是根據圖像中邊界框的左下角和右上角座標定義的

y1, x1, y2, x2 = boxes[0]

將每個矩形繪製在圖像中:

# example of inference with a pre-trained coco model
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from mrcnn.config import Config
from mrcnn.model import MaskRCNN
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

# draw an image with detected objects
def draw_image_with_boxes(filename, boxes_list):
     # load the image
     data = plt.imread(filename)
     # plot the image
     plt.imshow(data)
     # get the context for drawing boxes
     ax = pyplot.gca()
     # plot each box
     for box in boxes_list:
          # get coordinates
          y1, x1, y2, x2 = box
          # calculate width and height of the box
          width, height = x2 - x1, y2 - y1
          # create the shape
          rect = Rectangle((x1, y1), width, height, fill=False, color='red')
          # draw the box
          ax.add_patch(rect)
     # show the plot
     plt.show()

# define the test configuration
class TestConfig(Config):
     NAME = "test"
     GPU_COUNT = 1
     IMAGES_PER_GPU = 1
     NUM_CLASSES = 1 + 80

# define the model
rcnn = MaskRCNN(mode='inference', model_dir='./', config=TestConfig())
# load coco model weights
rcnn.load_weights('mask_rcnn_coco.h5', by_name=True)
# load photograph
img = load_img('elephant.jpg')
img = img_to_array(img)
# make prediction
results = rcnn.detect([img], verbose=0)
# visualize the results
draw_image_with_boxes('elephant.jpg', results[0]['rois'])

在這裏插入圖片描述

3.3 目標檢測示例

知道了如何加載模型並使用它進行預測,現在執行真實對象檢測,也就是說,除了本地化對象外,還想知道它們是什麼。Mask_RCNN API提供的函數叫做 display_instances() ,將所加載的圖像陣列和預測詞典的各方面,如邊界框,比分,和類別標籤,繪製在圖像中。

參數之一是字典的’ class_ids '鍵中可用的預測類標識符列表。該函數還需要將id映射到類標籤。預先訓練的模型適合具有80個(包括背景的)81個類別標籤的數據集,在下面列出的Mask R-CNN演示,筆記本教程中提供了該列表。

# example of inference with a pre-trained coco model
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from mrcnn.visualize import display_instances
from mrcnn.config import Config
from mrcnn.model import MaskRCNN

# define 81 classes that the coco model knowns about
class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
               'bus', 'train', 'truck', 'boat', 'traffic light',
               'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
               'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
               'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
               'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
               'kite', 'baseball bat', 'baseball glove', 'skateboard',
               'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
               'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
               'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
               'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
               'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
               'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
               'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
               'teddy bear', 'hair drier', 'toothbrush']

# define the test configuration
class TestConfig(Config):
     NAME = "test"
     GPU_COUNT = 1
     IMAGES_PER_GPU = 1
     NUM_CLASSES = 1 + 80

# define the model
rcnn = MaskRCNN(mode='inference', model_dir='./', config=TestConfig())
# load coco model weights
rcnn.load_weights('mask_rcnn_coco.h5', by_name=True)
# load photograph
img = load_img('elephant.jpg')
img = img_to_array(img)
# make prediction
results = rcnn.detect([img], verbose=0)
# get dictionary for first prediction
r = results[0]
# show photo with bounding boxes, masks, class labels and scores
display_instances(img, r['rois'], r['masks'], r['class_ids'], class_names, r['scores'])

在這裏插入圖片描述


參考:
https://machinelearningmastery.com/how-to-perform-object-detection-in-photographs-with-mask-r-cnn-in-keras/

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