ImageAI (一) 使用Python快速简单实现图像内容预测 Image Prediction

简介
ImageAI是一个python的库,它能使开发人员用简单几行代码构建具有深度学习和计算机视觉功能的应用程序和系统。它是由Moses Olafenwa和John Olafenwa两位开发并维护。
具体git地址:https://github.com/OlafenwaMoses/ImageAI
今天首先介绍一下使用imageai的准备工作,安装以及简单的实现image prediction
(以下内容git中都有详细介绍)


准备工作

首先当然是python,imageai暂时只支持3.5.1或之后的版本,一般都是用3.6吧
还有以下这些:
Tensorflow>=1.4.0
Numpy >=1.13.1
SciPy >=0.19.1
OpenCV
Pillow
Matplotlib
h5py
Keras 2.x

pip3 install xxx


安装
做好准备工作后就是安装了,可以直接使用pip3安装 如下

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

当然也可以将[imageai-2.1.0-py3-none-any.whl](https://github.com/OlafenwaMoses/ImageAI/releases/download/2.1.0/imageai-2.1.0-py3-none-any.whl)下载之后安装 ``` pip3 install C:\User\MyUser\Downloads\imageai-2.1.0-py3-none-any.whl ```

Image Prediction
安装完之后进入正题,图像内容的预测。
ImageAI提供4种不同的算法和模型来进行图像预测,并在ImageNet-1000数据集上进行了训练。4种算法包括SqueezeNet,ResNet,InceptionV3和DenseNet。
这里也提供了四种模型训练好后的文件。

好了,选一个模型,将训练好后的内容下载下来就可以开始简单的图像预测啦!

prediction.py

from imageai.Prediction import ImagePrediction
import os
import time
#计时
start = time.time()
 
#当前路径 包含需要预测的图片,模型文件
execution_path = os.getcwd()
 
#创建预测类
prediction = ImagePrediction()
 
#设置预测模型 有以下四种
#SqueezeNet
#prediction.setModelTypeAsSqueezeNet()
#prediction.setModelPath(os.path.join(execution_path, "squeezenet_weights_tf_dim_ordering_tf_kernels.h5"))
 
#ResNet50
#prediction.setModelTypeAsInceptionV3()
#prediction.setModelPath(os.path.join(execution_path, "inception_v3_weights_tf_dim_ordering_tf_kernels.h5"))
 
#InceptionV3
#prediction.setModelTypeAsResNet()
#prediction.setModelPath(os.path.join(execution_path, "resnet50_weights_tf_dim_ordering_tf_kernels.h5"))
 
#DenseNet121
prediction.setModelTypeAsDenseNet()
prediction.setModelPath(os.path.join(execution_path, "DenseNet-BC-121-32.h5"))
 
prediction.loadModel()
 
#预测图片,以及结果预测输出数目
predictions, probabilities = prediction.predictImage(os.path.join(execution_path, "1.jpg"), result_count=5 )
 
#结束计时
end = time.time()
 
#输出结果
for eachPrediction, eachProbability in zip(predictions, probabilities):
    print(eachPrediction," : ", eachProbability)
 
print ("\ncost time:",end-start)

看着代码去掉注释 只用了大概十行作用就可以完成图像的预测了

先使用了git上提供的图片
car

我用四种模型都跑了一下 结果如下

---squeezenet_weights_tf_dim_ordering_tf_kernels.h5---
sports_car : 45.9977924823761
convertible : 38.13416361808777
grille : 7.812434434890747
minivan : 2.406269498169422
pickup : 2.211885526776314

cost time: 6.432089567184448

---inception_v3_weights_tf_dim_ordering_tf_kernels.h5---
convertible : 96.45639061927795
sports_car : 3.52620966732502
beach_wagon : 0.010831362305907533
car_wheel : 0.003940704118576832
pickup : 0.0006548482815560419

cost time: 15.786875247955322

---resnet50_weights_tf_dim_ordering_tf_kernels.h5---
convertible : 52.459555864334106
sports_car : 37.61284649372101
pickup : 3.1751200556755066
car_wheel : 1.817505806684494
minivan : 1.7487050965428352

cost time: 24.41988778114319

---DenseNet-BC-121-32.h5---
sports_car : 64.85629677772522
convertible : 13.065926730632782
beach_wagon : 8.915219455957413
car_wheel : 6.854388862848282
grille : 2.4432314559817314

cost time: 24.5520977973938

大概率都预测出了是跑车或是敞篷车。

我也随便挑了张照片 试了一试
二哈
结果

Siberian_husky : 87.60582208633423 西伯利亚雪橇犬(二哈)
Eskimo_dog : 12.393762916326523 爱斯基摩犬
malamute : 0.00020242005120962858 阿拉斯加雪橇犬
dogsled : 0.00015880526689215912
Norwegian_elkhound : 6.489584336577536e-06

cost time: 20.758772611618042

结果还是不错的 ヽ( ̄▽ ̄)ノ

除此之外,git上还介绍了多张图的预测,预测速度的改变,多线程操作等。这里就不解释了,改动并不是很大。
今天暂时就到这儿吧,imageai还有图片物体检测/分隔,视频中物体检测和跟踪等等以后再继续介绍啦

代码以及模型文件我都放在了网盘上,有需要可以自行下载
链接: https://pan.baidu.com/s/13hUoa_0d3tla5d2pTfD1OA 提取码: qne5

后续:
ImageAI (二) 使用Python快速简单实现物体检测 Object Detection
ImageAI (三) 使用Python快速简单实现视频中物体检测 Video Object Detection and Tracking

  • 8
    点赞
  • 112
    收藏
    觉得还不错? 一键收藏
  • 30
    评论
抱歉,作为AI语言模型,我无法生成实际代码。以下是YOLO v5的Python代码示例,供您参考: 1. 导入必要的库 ```python import torch import cv2 import numpy as np from PIL import Image from torchvision import transforms from models.experimental import attempt_load from utils.general import non_max_suppression, scale_coords from utils.plots import plot_one_box ``` 2. 定义函数 ```python def detect(image_path, weights_path, conf_thres=0.25, iou_thres=0.45, device='cpu'): # Load model model = attempt_load(weights_path, map_location=device) # Set model to evaluation mode model.eval() # Define transforms for input image transform = transforms.Compose([ transforms.Resize((640, 640)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # Load image img = Image.open(image_path) # Apply transforms img = transform(img).unsqueeze(0) # Move image to device img = img.to(device) # Make predictions with torch.no_grad(): # Get prediction pred = model(img) # Apply non-maximum suppression pred = non_max_suppression(pred, conf_thres, iou_thres) # Get image size img_size = img.shape[-2:] # Get prediction boxes and labels boxes = [] labels = [] scores = [] for i, det in enumerate(pred): # Rescale boxes from 640 to image size det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img_size).round() for *xyxy, conf, cls in reversed(det): label = model.names[int(cls)] score = float(conf) # Add box and label to lists boxes.append(xyxy) labels.append(label) scores.append(score) return boxes, labels, scores ``` 3. 运行检测 ```python if __name__ == '__main__': # Define device (GPU or CPU) device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') # Define paths to image and model weights image_path = 'path/to/image.jpg' weights_path = 'path/to/weights.pt' # Run detection boxes, labels, scores = detect(image_path, weights_path, device=device) # Load image img = cv2.imread(image_path) # Plot boxes on image for box, label, score in zip(boxes, labels, scores): plot_one_box(box, img, label=label, color=(0, 255, 0), line_thickness=2) # Show image cv2.imshow('Detection', img) cv2.waitKey(0) cv2.destroyAllWindows() ```
评论 30
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值