imageAI使用教程(正在編輯中)

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

相關文件可見百度雲盤

鏈接:https://pan.baidu.com/s/18waiZ8wVcNbA97F8mcTS-g 
提取碼:tuk4 

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, 'test-images', 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, predictions):
                    print(prediction, " : ", percentage_probability)


predictionThread = PredictionThread()
predictionThread.start()

結果(選擇了ResNet):

convertible  :  convertible
toilet_tissue  :  toilet_tissue
bustard  :  bustard

3 目標檢測
4 視頻目標檢測、跟蹤與分析
5 自定義模型培訓
6 自定義圖像預測
7 文件
8 基於ImageAI的項目
9 AI實踐建議

 

 

 

 

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