imageAI使用教程

github地址: https://github.com/OlafenwaMoses/ImageAI

相關文件可見百度雲盤

鏈接:https://pan.baidu.com/s/10mUt_2qUzsXXgE0Osd0X6A 
提取碼:ttsp

Table of Contents

1 安裝

1.1 相關依賴

1.2 imageAI安裝

2 圖像預測

2.1 基本模型

2.2 多圖預測

2.3 預測速度調整

2.4 多線程預測

3 目標檢測

3.1 基本檢測

3.2 目標檢測、提取與微調

3.3 自定義對象檢測

3.4 加速

3.5 隱藏/顯示對象名稱和概率

3.6 圖像輸入輸出類型

4 視頻目標檢測、跟蹤與分析

4.1 基礎視頻

4.2 自定義類型

4.3 攝像機/實時流視頻檢測。

4.4 視頻分析

5 自定義模型培訓

6 自定義圖像預測


 

1 安裝

1.1 相關依賴

pip3 install --upgrade tensorflow 
pip3 install numpy 
pip3 install scipy 
pip3 install opencv-python 
pip3 install pillow 
pip3 install matplotlib 
pip3 install h5py 
pip3 install keras

1.2 imageAI安裝

pip3 install https://github.com/OlafenwaMoses/ImageAI/releases/download/2.0.2/imageai-2.0.2-py3-none-any.whl 

或者直接下載 imageai-2.0.2-py3-none-any.whl,再在下載目錄下用pip3安裝,例如

pip3 install C:\User\MyUser\Downloads\imageai-2.0.2-py3-none-any.whl 

2 圖像預測

2.1 基本模型

ImageAI提供了4種不同的算法和模型類型來執行圖像預測。要對任何圖片執行圖像預測,請執行以下簡單步驟。圖像預測的4種算法包括SqueezeNet算法、ResNet算法、InceptionV3算法和DenseNet算法。這些算法中的每一個都有單獨的模型文件,您必須使用這些文件,具體取決於算法的選擇。要下載模型文件以供選擇算法,請單擊以下任意鏈接:

-SqueezeNet(大小=4.82 mb,預測時間最快,精度中等)。
-Microsoft Research提供的ResNet50(大小=98mb,預測時間快,精度高)。
-由Google Brain團隊執行的InceptionV3(大小=91.6mb,預測速度慢且精度更高)。
-DenseNet121,由Facebook AI Research提供(Size=31.6mb,預測時間較慢,精度最高)

太棒了!下載此模型文件後,啓動一個新的python項目,然後將該模型文件複製到項目文件夾中,python文件(.py文件)將位於該文件夾中。下載下面的圖像,或者在您的計算機上獲取任何圖像並將其複製到python項目的文件夾中。然後創建一個python文件併爲其命名;FirstPrediction.py就是一個例子。然後將下面的代碼編寫到python文件中:

1.jpg

提示:

模型文件下載在根目錄的models子目錄下

圖片文件在根目錄的images子目錄下

樣例代碼(First_Prediction.py)

# 導入ImageAI庫和python os類
from imageai.Prediction import ImagePrediction
import os

execution_path = 'E:\imageAI'  # imageAI 根目錄
prediction = ImagePrediction()  # 圖片預測預備

# 模型文件下載在根目錄的models子目錄下
# 選擇一個神經網絡

# 1 DenseNet 預測時間較慢,精度最高
# prediction.setModelTypeAsDenseNet()
# prediction.setModelPath(
#     os.path.join(execution_path, 'models',
#                  "DenseNet-BC-121-32.h5"))  # 加載模型文件地址

# 2 InceptionV3 預測速度慢且精度更高
# prediction.setModelTypeAsInceptionV3()
# prediction.setModelPath(
#     os.path.join(execution_path, 'models',
#                  'inception_v3_weights_tf_dim_ordering_tf_kernels.h5'))

# 3 ResNet 預測時間快,精度高
prediction.setModelTypeAsResNet()
prediction.setModelPath(
    os.path.join(execution_path, 'models',
                 'resnet50_weights_tf_dim_ordering_tf_kernels.h5'))

# 4 squeezenet 預測時間最快,精度中等
# prediction.setModelTypeAsSqueezeNet()
# prediction.setModelPath(
#     os.path.join(execution_path, 'models',
#                  'squeezenet_weights_tf_dim_ordering_tf_kernels.h5'))

prediction.loadModel()  # 加載模型

# 圖片文件在執行目錄的images子目錄下
redictions, probabilities = prediction.predictImage(
    os.path.join(execution_path, 'images', "1.jpg"),
    result_count=5)  # 加載待預測的圖片地址,輸出5個最高可能的類型
for eachPrediction, eachProbability in zip(predictions,
                                           probabilities):  # 輸出格式 預測類型 : 可能性大小
    print(eachPrediction, ' : ', eachProbability)

結果(選擇了ResNet):

convertible  :  52.459537982940674
sports_car  :  37.61286735534668
pickup  :  3.175118938088417
car_wheel  :  1.8175017088651657
minivan  :  1.7487028613686562

2.2 多圖預測

可以使用單個函數(即.pretMultipleImage()函數)對多個圖像運行圖像預測。它的工作原理如下:

-定義普通圖像預測實例。
-設置模型類型和模型路徑。
-調用.loadModel()函數。
-創建一個數組,並將要預測的每個映像的所有字符串路徑添加到該數組中。
-然後通過調用.pretMultipleImage()函數並在圖像數組中進行解析來執行預測,還可以通過解析RESULT_COUNT_PER_IMAGE=5來設置每個圖像所需的預測數(默認值爲2)

樣例代碼(Multi_Prediction.py)

# 導入ImageAI庫和python os類
from imageai.Prediction import ImagePrediction
import os

execution_path = 'E:\imageAI'  # imageAI 根目錄
multiple_prediction = ImagePrediction()  # 圖片預測預備

multiple_prediction.setModelTypeAsResNet()
multiple_prediction.setModelPath(
    os.path.join(execution_path, 'models',
                 'resnet50_weights_tf_dim_ordering_tf_kernels.h5'))

multiple_prediction.loadModel()  # 加載模型

all_images_array = []  # 存放所有的測試圖片的數組

all_files = os.listdir(os.path.join(execution_path, 'myimages'))  # 多圖片文件目錄
for each_file in all_files:
    if (each_file.endswith("jpg")
            or each_file.endswith('.png')):  # 只預測jpg和png格式的文件
        all_images_array.append(
            os.path.join(execution_path, 'myimages', each_file))

results_array = multiple_prediction.predictMultipleImages(
    all_images_array, result_count_per_image=5)  # 輸出5個最高可能的類型

for each_result in results_array:
    # 輸出每個圖片的五個可能類別
    predictions, percentage_probabilities = each_result[
        'predictions'], each_result['percentage_probabilities']
    for index in range(len(predictions)):
        # 輸出每個類別的可能性大小
        print(predictions[index], ' : ', percentage_probabilities[index])
    print('---------------------------')

結果(選擇了ResNet):

king_penguin  :  99.17049407958984
magpie  :  0.5325432866811752
killer_whale  :  0.10074214078485966
black_stork  :  0.04736874543596059
Boston_bull  :  0.02190503873862326
---------------------------
park_bench  :  54.671889543533325
patio  :  30.31955659389496
lakeside  :  3.775469958782196
folding_chair  :  1.6704175621271133
shopping_cart  :  1.4237137511372566
---------------------------
pay-phone  :  34.05987322330475
CD_player  :  8.037229627370834
desktop_computer  :  6.571460515260696
loudspeaker  :  4.9332063645124435
parking_meter  :  4.163774847984314
---------------------------

2.3 預測速度調整

ImageAI現在爲所有圖像預測任務提供預測速度。預測速度允許您以20%-60%的速率縮短預測時間,但只有輕微的變化,但預測結果是準確的。可用的預測速度是"normal"(默認), "fast""faster" and "fastest"。您所需要做的就是說明加載模型時所需的速度模式,如下所示。

將MultiPrediction.py中的

multiple_prediction.loadModel()  # 加載模型

改爲

multiple_prediction.loadModel(prediction_speed='fastest')  # 快速加載模型

速度將大大提高,時間將大大縮短。

2.4 多線程預測

當開發在多線程(如用戶界面)上運行繁重任務的程序時,您應該考慮在一個新線程中運行您的預測。在新線程中使用ImageAI運行圖像預測時,必須注意以下事項:

-您可以創建預測對象,設置它的模型類型,在新線程之外設置模型路徑和json路徑。
-.loadModel()必須位於新線程中,並且圖像預測(predictImage()必須發生在新線程中。

下面是使用多線程進行圖像預測的示例代碼:

# 導入ImageAI庫和python os類
from imageai.Prediction import ImagePrediction
import os
import threading

execution_path = 'E:\imageAI'  # imageAI 根目錄
prediction = ImagePrediction()  # 圖片預測預備

prediction.setModelTypeAsResNet()
prediction.setModelPath(
    os.path.join(execution_path, 'models',
                 'resnet50_weights_tf_dim_ordering_tf_kernels.h5'))

pictures_folder = os.path.join(execution_path, 'myimages')
all_files = os.listdir(pictures_folder)  # 多圖片文件目錄


class PredictionThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global prediction
        prediction_thread = prediction
        prediction_thread.loadModel()
        for eachPicture in all_files:
            if (eachPicture.endswith('.png') or eachPicture.endswith('.jpg')):
                predictions, percentage_probabilities = prediction_thread.predictImage(
                    os.path.join(pictures_folder, eachPicture), result_count=1)
                for prediction, percentage_probability in zip(
                        predictions, percentage_probabilities):
                    print(prediction, " : ", percentage_probability)


predictionThread = PredictionThread()
predictionThread.start()

 

3 目標檢測

ImageAI提供了非常方便和強大的方法來對圖像進行物體檢測和從圖像中提取每個對象。對象檢測類支持RetinaNet,YOLOv3和TinyYOLOv3。要開始執行物體檢測,您必須通過以下鏈接下載RetinaNet,YOLOv3或TinyYOLOv3物體檢測模型:

RetinaNet (尺寸= 145 mb,高性能和準確性,檢測時間更長) 

YOLOv3 (尺寸= 237 mb,性能和準確度適中,檢測時間適中) 

TinyYOLOv3 (大小= 34 mb,針對速度和中等性能進行了優化,檢測時間快) 

3.1 基本檢測

下載對象檢測模型文件後,應將模型文件複製到.py文件所在的項目文件夾中。然後創建一個python文件併爲其命名; 一個例子是FirstObjectDetection.py。然後將下面的代碼寫入python文件:

# coding: utf-8
from imageai.Detection import ObjectDetection
import os

execution_path = '..\..'  # imageAI根目錄

detector = ObjectDetection()  # 加載檢測器

# resnet png格式可以正常輸出文本,且有標記的新圖片
# detector.setModelTypeAsRetinaNet()  # 設置模型網絡類型
# detector.setModelPath(
#     os.path.join(execution_path, 'models', 'Object Detection',
#                  "resnet50_coco_best_v2.0.1.h5"))  # 設置模型文件路徑

# YOLOv3 用不了
# detector.setModelTypeAsYOLOv3()
# detector.setModelPath(
#     os.path.join(execution_path, 'models', 'Object Detection', 'yolo.h5'))

# TinyYOLOv3 png格式可以正常輸出文本,且有標記的新圖片
detector.setModelTypeAsTinyYOLOv3()
detector.setModelPath(
    os.path.join(execution_path, 'models', 'Object Detection',
                 "yolo-tiny.h5"))

detector.loadModel()  # 加載模型
detections = detector.detectObjectsFromImage(
    input_image=os.path.join(execution_path, 'myimages',
                             "image2.jpg"),  # 輸入待檢測圖片路勁
    output_image_path=os.path.join(execution_path, 'myimages',
                                   "image2new.png"),  # 輸出圖片路徑 特別提醒用png別用jpg
    minimum_percentage_probability=30)  # 輸出檢測到的物品的最小可能性閾值

for eachObject in detections:
    print(eachObject["name"], " : ", eachObject["percentage_probability"],
          ' : ', eachObject['box_points'])  # 目標名 : 可能性大小 : 目標區域
    print("--------------------------------")

針對使用github上教程代碼會報錯如下的問題

ensure you specified correct input image, input type, output type and/or output image path

我的方案是,將輸出格式以jpg換爲png格式,則resnet和TinyYOLOv3可以正常執行,而YOLOv3依然故障,不管了233

輸出結果如下:

laptop  :  30.240696668624878  :  (305, 241, 387, 283)
--------------------------------
donut  :  54.28292155265808  :  (15, 379, 130, 438)
--------------------------------
person  :  58.40651988983154  :  (170, 104, 285, 296)
--------------------------------
person  :  62.51210570335388  :  (412, 120, 567, 282)
--------------------------------
person  :  84.3508780002594  :  (307, 169, 384, 256)
--------------------------------

3.2 目標檢測、提取與微調

在上面使用的示例中,我們對圖像運行對象檢測,它將檢測到的對象返回到一個數組中,並保存在每個對象上繪製了矩形標記的新圖像。在我們的下一個示例中,我們將能夠從輸入圖像中提取每個對象並獨立保存它。
下面的示例代碼與前面的對象確定代碼非常相同,我們將把檢測到的每個對象保存爲單獨的圖像。

Object Detection, Extraction and Fine-tune.py

from imageai.Detection import ObjectDetection
import os

execution_path = '..\..'

detector = ObjectDetection()
detector.setModelTypeAsTinyYOLOv3()
detector.setModelPath(
    os.path.join(execution_path, 'models', 'Object Detection', "yolo-tiny.h5"))
detector.loadModel()

detections, objects_path = detector.detectObjectsFromImage(
    input_image=os.path.join(execution_path, 'myimages', 'image3.jpg'),
    output_image_path=os.path.join(execution_path, 'myimages',
                                   'image3new.jpg'),
    minimum_percentage_probability=30,
    extract_detected_objects=True)  # 提取檢測到的物體

for eachObject, eachObjectPath in zip(detections, objects_path):
    print(eachObject['name'], ' : ', eachObject['percentage_probability'],
          ' : ', eachObject['box_points'])
    print("Object's image saved in " + eachObjectPath)
    print('------------------')

針對出現的同樣的問題

ensure you specified correct input image, input type, output type and/or output image path

這一次我沒有改成png格式輸出,事實證明改成png也沒用。我改了detector.detectObjectsFromImage所在文件的源碼

首先添加包(沒有scipy包的自行 pip install scipy)

from scipy.misc import imsave

其次(建議刪除的代碼選擇註釋掉而不要直接刪除,以免誤刪),將每一個

pltimage.imsave(splitted_image_path, splitted_copy)

註釋掉,在其後添加

imsave(splitted_image_path, splitted_copy)

將每一個

pltimage.imsave(output_image_path, detected_copy)

註釋掉,在其後添加

imsave(output_image_path, detected_copy)

即可正確輸出結果如下:

dog  :  56.6261887550354  :  (395, 324, 449, 434)
Object's image saved in ..\..\myimages\image3new.jpg-objects\dog-1.jpg
------------------
motorcycle  :  42.00790226459503  :  (264, 190, 354, 306)
Object's image saved in ..\..\myimages\image3new.jpg-objects\motorcycle-2.jpg
------------------
person  :  34.74055230617523  :  (143, 119, 170, 159)
Object's image saved in ..\..\myimages\image3new.jpg-objects\person-3.jpg
------------------
person  :  40.157753229141235  :  (461, 131, 509, 222)
Object's image saved in ..\..\myimages\image3new.jpg-objects\person-4.jpg
------------------
person  :  64.91311192512512  :  (157, 159, 246, 362)
Object's image saved in ..\..\myimages\image3new.jpg-objects\person-5.jpg
------------------
person  :  78.07609438896179  :  (601, 130, 640, 222)
Object's image saved in ..\..\myimages\image3new.jpg-objects\person-6.jpg
------------------
person  :  89.72328901290894  :  (10, 100, 65, 252)
Object's image saved in ..\..\myimages\image3new.jpg-objects\person-7.jpg
------------------
person  :  97.73168563842773  :  (536, 99, 580, 228)
Object's image saved in ..\..\myimages\image3new.jpg-objects\person-8.jpg
------------------

輸出文件夾內的圖片爲

還有一個重要的功能你需要知道!
您會記得,檢測到的每個對象的百分比概率都是由DetectObjectsFromImage()函數返回的。該函數有一個參數Minimum_Percentage_Probability,其默認值爲50(值範圍在0-100之間),但在本例中它設置爲30。這意味着該函數只返回檢測到的對象(如果其百分比概率爲30或更高)。該值保持在這一數值上,以確保檢測結果的完整性。通過將Minimum_Percentage_Probability設置爲等於較小的值以檢測更多的對象,或將較大的值設置爲檢測較少的對象數,可以微調對象檢測。

3.3 自定義對象檢測

ImageAI支持的對象檢測模型(Retinanet)可以檢測80種不同類型的對象。它們包括:

'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', 'donot', '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 dryer', 'toothbrush'

對應中文爲

'人', '自行車', '汽車', '摩托車', '飛機', '公共汽車', '火車', '卡車', '船', '交通燈', '消防栓',
'停車標誌', '停車收費表', '長椅', '鳥', '貓', '狗', '馬', '羊', '牛', '大象', '熊', '斑馬',
'長頸鹿', '揹包', '傘', '手提包', '領帶', '手提箱', '飛盤', '滑雪板', '運動球', '風箏', '棒球棒',
'棒球手套', '滑板', '衝浪板', '網球拍', '瓶子', '酒杯', '杯子', '叉子', '刀', '勺子', '碗', '香蕉',
'蘋果', '三明治', '橙', '花椰菜', '胡蘿蔔', '熱狗', '披薩', '不要', '蛋糕', '椅子', '沙發', '盆栽',
'牀', '餐桌', '衛生間', '電視', '筆記本電腦', '鼠標', '遙控器', '鍵盤', '手機', '微波爐', '烤箱',
'水槽', '冰箱', '書籍', '時鐘', '花瓶', '剪刀', '泰迪熊', '吹風機', '牙刷'

有趣的是,ImageAI允許您對上面的一個或多個項目執行檢測。這意味着您可以自定義要在圖像中檢測到的對象類型。讓我們看看下面的代碼:

from imageai.Detection import ObjectDetection
import os

execution_path = '..\..'

detector = ObjectDetection()

# detector.setModelTypeAsTinyYOLOv3()
# detector.setModelPath(
#     os.path.join(execution_path, 'models', 'Object Detection', "yolo-tiny.h5"))

detector.setModelTypeAsRetinaNet()
detector.setModelPath(
    os.path.join(execution_path, 'models', 'Object Detection',
                 "resnet50_coco_best_v2.0.1.h5"))

detector.loadModel()

custom_objects = detector.CustomObjects(car=True, motorcycle=True)
detections = detector.detectCustomObjectsFromImage(
    custom_objects=custom_objects,
    input_image=os.path.join(execution_path, 'myimages', 'image3.jpg'),
    output_image_path=os.path.join(execution_path, 'myimages',
                                   'image3custom.jpg'),
    minimum_percentage_probability=30)

for eachObject in detections:
    print(eachObject['name'], " : ", eachObject['percentage_probability'],
          ' : ', eachObject['box_points'])
    print('----------------')

文本結果輸出爲

motorcycle  :  34.51491296291351  :  [237 154 362 304]
----------------
motorcycle  :  71.0715651512146  :  [273 180 346 306]
----------------
car  :  37.305331230163574  :  [ 67 159 361 313]
----------------
car  :  42.52847731113434  :  [145 151 305 332]
----------------
car  :  55.41401505470276  :  [215 140 388 299]
----------------

圖片輸出爲

3.4 加速

類似於第二章,ImageAI現在爲所有對象檢測任務提供檢測速度。檢測速度使您能夠以20%-80%的速度縮短檢測時間,但檢測結果只有輕微變化,但檢測結果準確。在降低最小百分比概率參數的同時,檢測速度可以與正常速度相匹配,同時大大縮短了檢測時間。可用的檢測速度爲 "normal"(default), "fast""faster" , "fastest" 和 "flash"。您所需要做的就是說明加載模型時所需的速度模式,如下所示。

detector.loadModel(detection_speed="fast")

3.5 隱藏/顯示對象名稱和概率

ImageAI提供了隱藏檢測到的對象名稱和/或百分比概率的選項,使其不會顯示在保存/返回的檢測到的圖像上。使用DetectObjectsFromImage()和DetectCustomObjectsFromImage()函數,可以分別將參數‘Display_Object_Name’和‘Display_Percentage_Probability’設置爲True 或者 False。查看以下代碼:

detections = detector.detectObjectsFromImage(
    input_image=os.path.join(execution_path, 'myimages', 'image3.jpg'),
    output_image_path=os.path.join(execution_path, 'myimages',
                                   'image3new_nolabels.jpg'),
    minimum_percentage_probability=30,
    display_object_name=False,
    display_percentage_probability=False)  # 提取檢測到的物體

在上面的代碼中,我們指定不應同時顯示對象名稱和百分比概率。正如您在下面的結果中所看到的,檢測到的圖像中沒有顯示對象的名稱及其各自的百分比概率。

3.6 圖像輸入輸出類型

ImageAI支持3種輸入類型,即圖像文件的文件路徑(默認)、圖像數組和圖像文件流,以及2種輸出類型:圖像文件(默認)和數字數組。這意味着您現在可以在生產應用程序中執行對象檢測,例如在以上述任何格式返回文件的Web服務器和系統上。
要使用Numpy數組或文件流輸入執行對象檢測,只需在.detectObjectsFromImage() 函數或 .detectCustomObjectsFromImage() 函數中聲明輸入類型。請參見下面的示例。

detections = detector.detectObjectsFromImage(input_type="array", input_image=image_array , output_image_path=os.path.join(execution_path , "image.jpg")) # numpy數組輸入
detections = detector.detectObjectsFromImage(input_type="stream", input_image=image_stream , output_image_path=os.path.join(execution_path , "test2new.jpg")) # 文件流輸入

要使用numpy數組輸出執行對象檢測,只需聲明輸出類型。
在 .detectObjectsFromImage() 函數或 .detectCustomObjectsFromImage() 函數中。請參見下面的示例。

detected_image_array, detections = detector.detectObjectsFromImage(output_type="array", input_image="image.jpg" ) # numpy數組輸出

4 視頻目標檢測、跟蹤與分析

4.1 基礎視頻

由於視頻對象檢測是一項計算密集型任務,我們建議您使用安裝了NVIDIA GPU和GPU版本的TensorFlow的計算機來執行此實驗。執行視頻對象檢測CPU的速度將比使用NVIDIA GPU供電計算機的速度慢。您可以使用Google Colab進行此實驗,因爲它有NVIDIA K80圖形處理器可用。

共用目標檢測的模型。

下載對象檢測模型文件後,應將模型文件複製到.py文件所在的項目文件夾中。然後創建一個python文件併爲其命名;FirstVideoObjectDetection.py就是一個例子。然後將下面的代碼編寫到python文件中:

# coding: utf-8
from imageai.Detection import VideoObjectDetection
import os

execution_path = '..\..'

detector = VideoObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath(
    os.path.join(execution_path, 'models', 'Object Detection',
                 'resnet50_coco_best_v2.0.1.h5'))
detector.loadModel()

video_path = detector.detectObjectsFromVideo(
    input_file_path=os.path.join(execution_path, 'videos', 'traffic.mp4'),
    output_file_path=os.path.join(execution_path, 'videos',
                                  'traffic-detected'),
    frames_per_second=20,
    log_progress=True)
print(video_path)

標籤依舊是目標檢測中的那80個

4.2 自定義類型

有趣的是,ImageAI允許您對上面的一個或多個項目執行檢測。這意味着您可以自定義要在視頻中檢測到的對象類型。讓我們看看下面的代碼:

# coding: utf-8
from imageai.Detection import VideoObjectDetection
import os

execution_path = '..\..'

detector = VideoObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath(
    os.path.join(execution_path, 'models', 'Object Detection',
                 'resnet50_coco_best_v2.0.1.h5'))
detector.loadModel()

# 自定義
custom_objects = detector.CustomObjects(
    person=True, bicycle=True, motorcycle=True)
video_path = detector.detectCustomObjectsFromVideo(
    custom_objects=custom_objects,
    input_file_path=os.path.join(execution_path, 'videos', 'traffic.mp4'),
    output_file_path=os.path.join(execution_path, 'videos',
                                  'traffic_custom_detected'),
    frames_per_second=20,
    log_progress=True)
print(video_path)

在上面的代碼中,在加載模型之後(也可以在加載模型之前完成),我們定義了一個新變量“CUSTOM_Objects=Detector.CustomObjects()”,在該變量中,我們將其Person、Car和Motorccyle屬性設置爲True。這是告訴模型只檢測我們設置爲True的對象。然後,我們調用“Detector.DetectCustomObjectsFromVideo()”,這是一個允許我們執行自定義對象檢測的函數。然後,我們將“Custom_Objects”值設置爲我們定義的自定義對象變量。

4.3 攝像機/實時流視頻檢測。

ImageAI現在可以在支持攝像機輸入的情況下進行實時視頻檢測。使用OpenCV的VideoCapture()函數,您可以從設備攝像機、通過電纜或IP攝像機連接的攝像機加載實時視頻流,並將其解析爲ImageAI的DetectObjectsFromVideo()和DetectCustomObjectsFromVideo()函數。支持用於檢測視頻文件中的對象的所有功能也可用於檢測攝像機的實時視頻源中的對象。下面是從設備攝像頭檢測實時視頻源的示例。

# coding: utf-8
from imageai.Detection import VideoObjectDetection
import os
import cv2

execution_path = '..\..'

camera = cv2.VideoCapture()

detector = VideoObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath(
    os.path.join(execution_path, 'models', 'Object Detection',
                 'resnet50_coco_best_v2.0.1.h5'))
detector.loadModel()

video_path = detector.detectObjectsFromVideo(
    camera_input=camera,
    output_file_path=os.path.join(execution_path, 'videos',
                                  'traffic_detected'),
    frames_per_second=20,
    log_progress=True,
    minimum_percentage_probability=40)

上面的代碼與檢測視頻文件的代碼的不同之處在於,我們定義了OpenCVVideoCapture實例並將默認的設備攝像機加載到其中。然後,我們將定義的攝像機解析爲Camera_INPUT參數,該參數將替換用於視頻文件的INPUT_FILE_PATH。

4.4 視頻分析

ImageAI現在視頻對象檢測類中爲視頻文件輸入和攝像機輸入提供商業級視頻分析。此功能允許開發人員深入瞭解使用ImageAI處理的任何視頻。這種洞察力可以實時可視化,存儲在NoSQL數據庫中,以備將來查看或分析。

對於視頻分析,DetectObjectsFromVideo()和DetectCustomObjectsFromVideo()現在允許您聲明自己定義的函數,該函數將對檢測到的視頻的每一幀、秒和/或分鐘執行,以及在視頻檢測結束時執行的函數狀態。一旦說明了這些函數,它們將收到關於幀/秒/分鐘的索引、檢測到的對象(名稱、百分比概率和Box_Points)、檢測到的每個唯一對象的實例數以及在一秒/分鐘和整個視頻中檢測到的每個唯一對象的平均出現次數的原始但全面的分析數據。
要獲得視頻分析,您所需要做的就是指定一個函數,說明它將接收的相應參數,並在檢測函數中將該函數名解析爲per_frame_function、per_sec_function、per_minute_function和Video_complete_函數參數。下面是視頻分析功能的示例。

from imageai.Detection import VideoObjectDetection
import os
import cv2

execution_path = '..\..'


def forFrame(frame_number, output_array, output_count):
    print('For Frame ', frame_number)
    print('Output for each object : ', output_array)
    print('Output count for unique objects : ', output_count)
    print('------------END OF A FRAME --------------')


def forSeconds(second_number, output_arrays, count_arrays,
               average_output_count):
    print('Second : ', second_number)
    print('Array for the outputs of each frame ', output_arrays)
    print('Array for output count for unique objects in each frame : ',
          count_arrays)
    print('Output average count for unique objects in the last second: ',
          average_output_count)
    print('------------END OF A SECOND --------------')


def forMinute(minute_number, output_arrays, count_arrays,
              average_output_count):
    print("MINUTE : ", minute_number)
    print("Array for the outputs of each frame ", output_arrays)
    print("Array for output count for unique objects in each frame : ",
          count_arrays)
    print("Output average count for unique objects in the last minute: ",
          average_output_count)
    print("------------END OF A MINUTE --------------")


detector = VideoObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath(
    os.path.join(execution_path, 'models', 'Object Detection',
                 'resnet50_coco_best_v2.0.1.h5'))
detector.loadModel(detection_speed="fast")

video_path = detector.detectCustomObjectsFromVideo(
    input_file_path=os.path.join(execution_path, 'videos', 'traffic.mp4'),
    output_file_path=os.path.join(execution_path, 'videos',
                                  'traffic_detected_frame_second_minute'),
    frames_per_second=10,
    per_frame_function=forFrame,
    per_second_function=forSeconds,
    per_minute_function=forMinute,
    minimum_percentage_probability=30)


5 自定義模型培訓

ImageAI使用最先進的SqueezeNet、ResNet50、InceptionV3和DenseNet提供最簡單、最強大的方法來訓練自定義圖像預測模型,您可以將這些模型加載到imageai.Prediction.Custom.CustomImagePrediction類中。這使您可以在與任何類型的對象/人員相對應的任何一組圖像上訓練自己的模型。培訓過程生成一個JSON文件,該文件映射圖像數據集中的對象類型,並創建許多模型。然後,您將以最高的精度對模型進行峯值處理,並使用生成的模型和JSON文件執行自定義圖像預測。

由於模型培訓是一項計算密集型任務,我們強烈建議您使用裝有NVIDIA GPU和安裝了TensorFlow的GPU版本的計算機來執行此實驗。在CPU上執行模型培訓將花費我數小時或數天的時間。使用NVIDIA GPU支持的計算機系統,這將需要幾個小時。您可以使用Google Colab進行此實驗,因爲它有NVIDIA K80圖形處理器可用。

要訓練自定義預測模型,需要準備要用於訓練模型的圖像。您將按如下方式準備圖像:

  1. 創建一個數據集文件夾,其名稱爲您希望您的數據集被命名爲(例如,PETS)。
  2. 在DataSet文件夾中,按列名創建一個文件夾train 。
  3. 在DataSet文件夾中,創建名爲test的文件夾。
  4. 在Train文件夾中,爲要對模型進行預測的每個對象創建一個文件夾,併爲該文件夾指定一個與相應的對象名稱相對應的名稱(例如,狗、貓、松鼠、蛇)。
  5. 在測試文件夾中,爲要對模型進行預測的每個對象創建一個文件夾,併爲該文件夾指定一個與相應的對象名稱相對應的名稱(例如,狗、貓、松鼠、蛇)。
  6. 在Train文件夾中的每個文件夾中,將每個對象的圖像放在其各自的文件夾中。這些圖像是用來訓練模型的。
  7. 要生成在實際應用中性能良好的模型,我建議每個對象大約有500個或更多的圖像。每個物體有1000張圖像,真是太棒了。在測試文件夾中的每個文件夾中,將每個對象的大約100到200個圖像放在其各自的文件夾中。這些圖像是用來在模型訓練時對模型進行測試的圖像。
  8. 完成此操作後,圖像數據集文件夾的結構應如下所示:
    pets//train//dog//dog-train-images
    pets//train//cat//cat-train-images
    pets//train//squirrel//squirrel-train-images
    pets//train//snake//snake-train-images
    pets//test//dog//dog-test-images
    pets//test//cat//cat-test-images
    pets//test//squirrel//squirrel-test-images
    pets//test//snake//snake-test-images
  9. 然後,您的培訓代碼如下所示
from imageai.Prediction.Custom import ModelTraining
model_trainer = ModelTraining()
model_trainer.setModelTypeAsResNet()
model_trainer.setDataDirectory("train_test_root_folder")
model_trainer.trainModel(
    num_objects=4,
    num_experiments=100,
    enhance_data=True,
    batch_size=32,
    show_network_summary=True)

是的。只需5行代碼,您就可以在自定義數據集上訓練4種最先進的深入學習算法中的任何一種。現在讓我們來看看上面的代碼是如何工作的。

在上面的代碼中,我們開始了培訓過程。函數中的參數如下:

num_objects:這是爲了說明圖像數據集中對象類型的數量。
num_experiments:這是說明網絡將在所有訓練圖像上訓練的次數,這也稱爲“紀元”。
enhance_data(可選):用於說明我們是否希望網絡生成經過修改的培訓圖像副本,以獲得更好的性能。
batch_size:這是用來說明網絡將處理的圖像的數量。對圖像進行分批處理,直到每次執行的實驗都將圖像耗盡爲止。
show_network_summary:這是要說明網絡是否應該在控制檯中顯示培訓網絡的結構。

6 自定義圖像預測

ImageAI提供了4種不同的算法和模型類型,以便使用自定義模型執行自定義圖像預測。您將能夠使用ImageAI訓練的模型和相應的MODEL_CLASS JSON文件來預測您訓練模型所針對的自定義對象。在這個例子中,我們將使用爲20個實驗訓練的模型,IdenProf是一個由穿制服的專業人員組成的數據集,在測試數據集上達到了65.17%的準確率(您可以使用自己的訓練模型和生成的JSON文件)。此“類”主要用於使用您自己的自定義模型。在以下鏈接中下載模型的ResNet模型和JSON文件:
ResNet (Size = 90.4 mb) 
- IdenProf model_class.json file
太棒了!下載了這個模型文件和JSON文件之後,啓動一個新的python項目,然後將模型文件和JSON文件複製到您的python文件(.py文件)所在的項目文件夾中。下載下面的圖像,或在您的計算機上拍攝任何包括以下專業人員(主廚、醫生、工程師、農民、消防員、法官、機械師、飛行員、警察和服務員)的圖像,並將其複製到您的python項目的文件夾中。然後創建一個python文件併爲其命名;例如FirstCustomPrediction.py。然後將下面的代碼編寫到python文件中:

from imageai.Prediction.Custom import CustomImagePrediction
import os

execution_path = '..\..'

prediction = CustomImagePrediction()
prediction.setModelTypeAsResNet()
prediction.setModelPath(
    os.path.join(execution_path, 'Custom Image Prediction',
                 'resnet50_coco_best_v2.0.1.h5'))
prediction.setJsonPath(
    os.path.join(execution_path, 'Custom Image Prediction',
                 'model_class.json'))
prediction.loadModel(num_objects=10)

predictions, probabilities = prediction.predictImage(
    os.path.join(execution_path, 'myimages', '4.jpg'), result_count=5)

for eachPrediction, eachProbability in zip(predictions, probabilities):
    print(eachPrediction + ' : ' + eachProbability)

 

 

 

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