使用keras内置的模型进行图片预测实例
作者:lucky404 发布时间:2021-12-27 17:54:29
keras 模块里面为我们提供了一个预训练好的模型,也就是开箱即可使用的图像识别模型
趁着国庆假期有时间我们就来看看这个预训练模型如何使用吧
可用的模型有哪些?
根据官方文档目前可用的模型大概有如下几个
1、VGG16
2、VGG19
3、ResNet50
4、InceptionResNetV2
5、InceptionV3
它们都被集成到了keras.applications 中
模型文件从哪来
当我们使用了这几个模型时,keras就会去自动下载这些已经训练好的模型保存到我们本机上面
模型文件会被下载到 ~/.keras/models/并在载入模型时自动载入
各个模型的信息:
如何使用预训练模型
使用大致分为三个步骤
1、导入所需模块
2、找一张你想预测的图像将图像转为矩阵
3、将图像矩阵放到模型中进行预测
关于图像矩阵的大小
VGG16,VGG19,ResNet50 默认输入尺寸是224x224
InceptionV3, InceptionResNetV2 模型的默认输入尺寸是299x299
代码demo
假设我现在有一张图片
我需要使用预训练模型来识别它
那我们就按照上面的步骤
第一步导入模块
from keras.applications import VGG16
from keras.applications import VGG19
from keras.applications import ResNet50
from keras.applications import InceptionV3
from keras.applications import InceptionResNetV2
第二步将图像转为矩阵
这里我们需要使用 keras.preprocessing.image 里面 img_to_array 来帮我们转
image = cv2.imread(img)
image = cv2.resize(image, self.dim)
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
第三步 将图像矩阵丢到模型中进行预测
predict = model.predict(preprocess)
decode_predict = decode_predictions(predict)
完整代码如下
1、配置文件
2、获取配置文件的模块
3、图像预测模块
配置文件
[image]
image_path=/home/fantasy/Pictures/cat.jpg
[model]
model=vgg16
[weights]
weight=imagenet
获取配置文件的模块
import configparser
cf = configparser.ConfigParser()
cf.read("configs.cnf")
def getOption(section, key):
return cf.get(section, key)
图像预测模块以及主要实现
# keras 提供了一些预训练模型,也就是开箱即用的 已经训练好的模型
# 我们可以使用这些预训练模型来进行图像识别,目前的预训练模型大概可以识别2.2w种类型的东西
# 可用的模型:
# VGG16
# VGG19
# ResNet50
# InceptionResNetV2
# InceptionV3
# 这些模型被集成到 keras.applications 中
# 当我们使用了这些内置的预训练模型时,模型文件会被下载到 ~/.keras/models/并在载入模型时自动载入
# VGG16,VGG19,ResNet50 默认输入尺寸是224x224
# InceptionV3, InceptionResNetV2 模型的默认输入尺寸是299x299
# 使用内置的预训练模型的步骤
# step1 导入需要的模型
# step2 将需要识别的图像数据转换为矩阵(矩阵的大小需要根据模型的不同而定)
# step3 将图像矩阵丢到模型里面进行预测
# -------------------------------------------------------
# step1
import cv2
import numpy as np
from getConfig import getOption
from keras.applications import VGG16
from keras.applications import VGG19
from keras.applications import ResNet50
from keras.applications import InceptionV3
from keras.applications import InceptionResNetV2
from keras.applications import imagenet_utils
from keras.applications.imagenet_utils import decode_predictions
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.inception_v3 import preprocess_input
class ImageTools(object):
"""
使用keras预训练模型进行图像识别
"""
def __init__(self, img, model, w):
self.image = img
self.model = model
self.weight = w
# step2
def image2matrix(self, img):
"""
将图像转为矩阵
"""
image = cv2.imread(img)
image = cv2.resize(image, self.dim)
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
return image
@property
def dim(self):
"""
图像矩阵的维度
"""
if self.model in ["inceptionv3", "inceptionresnetv2"]:
shape = (299, 299)
else:
shape = (224, 224)
return shape
@property
def Model(self):
"""
模型
"""
models = {
"vgg16": VGG16,
"vgg19": VGG19,
"resnet50": ResNet50,
"inceptionv3": InceptionV3,
"inceptionresnetv2": InceptionResNetV2
}
return models[self.model]
# step3
def prediction(self):
"""
预测
"""
model = self.Model(weights=self.weight)
if self.model in ["inceptionv3", "inceptionresnetv2"]:
preprocess = preprocess_input(self.image2matrix(self.image))
else:
preprocess = imagenet_utils.preprocess_input(self.image2matrix(self.image))
predict = model.predict(preprocess)
decode_predict = decode_predictions(predict)
for (item, (imgId, imgLabel, proba)) in enumerate(decode_predict[0]):
print("{}, {}, {:.2f}%".format(item + 1, imgLabel, proba * 100))
if __name__ == "__main__":
image = getOption("image", "image_path")
model = getOption("model", "model")
weight = getOption("weights", "weight")
tools = ImageTools(image, model, weight)
tools.prediction()
运行起来时会将模型文件下载到本机,因此第一次运行会比较久(有可能出现的情况就是下载不了,被墙了)
我们来看看使用VGG16的模型预测输出的效果如何
最后如果大家需要使用其他模型时修改 配置文件的model 即可
来源:https://blog.csdn.net/lucky404/article/details/82931322
猜你喜欢
- 你的SQL Server最近是否运行不正常?不,我指的不是我们肯定会遇到的通常的数据库和操作系统问题。我的意思是,你是否经历过服务器的反应迟
- 用下列代码即可:<%On error resume nextSet session=Creat
- 事件的概念事件:指的是文档或者浏览器窗口中发生的一些特定交互瞬间。我们可以通过 * (或者处理程序)来预定事件,以便事件发生的时候执行相应的
- 本文实例讲述了Python实现调用另一个路径下py文件中的函数方法。分享给大家供大家参考,具体如下:针对这个问题,网上有很多的解决方式。其实
- 测试sql: 代码如下:SET STATISTICS IO ON SET STATISTICS TIME ON SELECT COUNT(1
- 本文实例为大家分享了js实现QQ邮箱邮件拖拽删除的具体代码,供大家参考,具体内容如下步骤分析:根据数据结构生成HTML结构全选和单选功能的实
- asp生成wbmp代码如下: <%@ Language=VBScript %><%Funct
- 操作步骤导入框架,import unitest测试类必须继承类:.class 类名(unittest.TestCase):在类中所有定义te
- 上文: 《IE7的web标准之道——1:前言(兼目录)》IE历来被web标准的拥护者所诟病,而当FireFox横空出世以后,更多的网页制作者
- tomorrow是我最近在用的一个爬虫利器,该模块属于第三方的一个模块,使用起来非常的方便,只需要用其中的threads方法作为装饰器去修饰
- asp函数实现把数字格式化为每3个数字时以逗号间隔的数字见下:<%Function Comma(str)If No
- 浏览器对于CSS的支持问题落后于CSS的发展,以占有市场绝对份额的Internet Explorer来说,直到其前不久发布的第8个版本才刚刚
- 这篇文章主要介绍了python如果快速判断数字奇数偶数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋
- 在上一篇《服务器XMLHTTP(Server XMLHTTP in ASP)基础》中我介绍了一下ServerX
- 1.连接测试连接是否成功:import redisr = redis.Redis(host='192.168.136.102'
- 面临的问题在我设计一个分析系统中,我们公司的目标是能够处理来自数百万个端点的大量POST请求。web 网络处理程序将收到一个JSON文档,其
- li {list-style-image: url(images/disc.gif);}li的这个样式定义是将列表项目使用图片来代替显示的小
- 逆向最大匹配方法有正即有负,正向最大匹配算法大家可以参阅https://www.jb51.net/article/127404.htm逆向最
- 表单递交合法性检测-只接受数字。如下代码加入HTML的<head>区:<SCRIPT LANGUAGE=&quo
- 想要利用Python来操作word文档可以使用docx模块.安装: pip install python-docxfrom docx imp