ImageAI 是一个 Python 库,可以用于图像预测、自定义图像预测、物体检测、视频检测、视频对象跟踪以及图像预测训练。其主要优点在于能够通过几行简单的代码构建包含深度学习和计算机视觉功能的应用程序和系统。
ImageAI 使用 TensorFlow 深度学习框架,因此使用 ImageAI 前需要先安装 TensorFlow。你可以通过命令行运行以下命令来安装 ImageAI:
bash
pip3 install https://github.com/OlafenwaMoses/ImageAI/releases/download/2.0.1/imageai-2.0.1-py3-none-any.whl
下面的示例展示了如何使用预训练的模型来识别图像中的内容。只需下载预训练模型并稍作配置即可使用。
```python from imageai.Prediction import ImagePrediction
imgpath = "img/104.jpg" prediction = ImagePrediction() prediction.setModelTypeAsResNet() prediction.setModelPath("models/resnet50weightstfdimorderingtfkernels.h5") prediction.loadModel()
predictions, probabilities = prediction.predictImage(imgpath, result_count=5) for eachPrediction, eachProbability in zip(predictions, probabilities): print(eachPrediction, ":", eachProbability) ```
运行结果如下:
tiger_cat : 39.83352482318878
Egyptian_cat : 25.985831022262573
tabby : 19.167549908161163
Persian_cat : 1.6571426764130592
plastic_bag : 1.1700211092829704
这段代码展示了如何使用预训练模型进行图像识别,代码量很小且易于理解和操作。
除了使用预训练模型,你还可以使用自己训练的模型进行图像识别。这里提供了一个使用之前训练好的交通标志分类模型的示例。
```python from future import printfunction import sys import copy import shutil import cv2 import os import time import win32ui import numpy as np from PIL import Image import tensorflow as tf from Buildmodel import Build_model
config1 = tf.ConfigProto() config1.gpuoptions.allowgrowth = True tf.Session(config=config1)
classesnamelist = ["green", "left", "red", "right", "stop", "straight"] model = Buildmodel(config).buildmodel() model.load_weights('checkpoints/MobileNet/MobileNet.h5')
def openpic(): dlg = win32ui.CreateFileDialog(1) dlg.SetOFNInitialDir("dataset") dlg.DoModal() filename = dlg.GetPathName() return filename
while True: filename = openpic() img = cv2.imread(filename, cv2.IMREADUNCHANGED) testimg = tf.keras.preprocessing.image.loadimg(filename, targetsize=(224, 224, 3)) testimg = tf.keras.preprocessing.image.imgtoarray(testimg) testimg = testimg / 255 testimg = np.expanddims(testimg, 0) pred = model.predict(testimg) print('预测结果:', end='') print(pred) cv2.putText(img, classesnamelist[pred.argmax()], (10, 50), cv2.FONTHERSHEYSIMPLEX, 1.0, (255, 255, 0), 2) cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() ```
运行结果如图所示:
更多详细信息可以参考 ImageAI 文档。