源代码可以从https://github.com/aniketmaurya/tensorflow-web-app-starter-pack来获得

让我们从一个简单的helloworld示例开始

首先,我们导入FastAPI类并创建一个对象应用程序,该类有一些有用的参数,比如我们可以传递swaggerui的标题和描述。

from fastapi import FastAPI
app = FastAPI(title='Hello world')

我们定义一个函数并用@app.get,这意味着我们的API/index支持GET方法。这里定义的函数是异步的,FastAPI通过为普通的def函数创建线程池来自动处理异步和不使用异步方法,并且它为异步函数使用异步事件循环。

@app.get('/index')
async def hello_world():return "hello world"

图像识别API

我们创建一个API来对图像进行分类,并将其命名为predict/image。我们使用Tensorflow来创建图像分类模型。

Tensorflow图像分类教程:https://aniketmaurya.ml/blog/tensorflow/deep%20learning/2019/05/12/image-classification-with-tf2.html

我们创建了一个函数load_model,它将返回一个带有预训练权重的MobileNet CNN模型,即它已经被训练为对1000个不同类别的图像进行分类。

import tensorflow as tfdef load_model():model = tf.keras.applications.MobileNetV2(weights="imagenet")print("Model loaded")return modelmodel = load_model()

我们定义了一个predict函数,它将接受图像并返回预测。我们将图像大小调整为224x224,并将像素值规格化为[-1,1]。

from tensorflow.keras.applications.imagenet_utils
import decode_predictions

decode_predictions用于解码预测对象的类名。这里我们将返回前2个概率最高的类。

def predict(image: Image.Image):image = np.asarray(image.resize((224, 224)))[..., :3]image = np.expand_dims(image, 0)image = image / 127.5 - 1.0result = decode_predictions(model.predict(image), 2)[0]response = []for i, res in enumerate(result):resp = {}resp["class"] = res[1]resp["confidence"] = f"{res[2]*100:0.2f} %"response.append(resp)return response

现在我们创建一个支持文件上传的API/predict/image。我们将过滤文件扩展名以仅支持jpg、jpeg和png格式的图像。

我们将使用Pillow加载上传的图像。

def read_imagefile(file) -> Image.Image:image = Image.open(BytesIO(file))return image@app.post("/predict/image")
async def predict_api(file: UploadFile = File(...)):extension = file.filename.split(".")[-1] in ("jpg", "jpeg", "png")if not extension:return "Image must be jpg or png format!"image = read_imagefile(await file.read())prediction = predict(image)return prediction

最终代码

import uvicorn
from fastapi import FastAPI, File, UploadFilefrom application.components import predict, read_imagefileapp = FastAPI()@app.post("/predict/image")
async def predict_api(file: UploadFile = File(...)):extension = file.filename.split(".")[-1] in ("jpg", "jpeg", "png")if not extension:return "Image must be jpg or png format!"image = read_imagefile(await file.read())prediction = predict(image)return prediction@app.post("/api/covid-symptom-check")
def check_risk(symptom: Symptom):return symptom_check.get_risk_level(symptom)if __name__ == "__main__":uvicorn.run(app, debug=True)

FastAPI文档是了解框架核心概念的最佳资料:https://fastapi.tiangolo.com/

希望你喜欢这篇文章。

参考链接:https://towardsdatascience.com/image-classification-api-with-tensorflow-and-fastapi-fc85dc6d39e8

☆ END ☆

如果看到这里,说明你喜欢这篇文章,请转发、点赞。微信搜索「uncle_pn」,欢迎添加小编微信「 mthler」,每日朋友圈更新一篇高质量博文。

扫描二维码添加小编↓

用Tensorflow+FastAPI构建图像分类API相关推荐

  1. FastAPI 构建 API 服务,究竟有多快?

    FastAPI 干啥的? FastAPI 是用来构建 API 服务的一个高性能框架. 为什么选择 FastAPI ? FastAPI 是一个现代.高性能 web 框架,用于构建 APIs,基于 Pyt ...

  2. python商城开发_使用FastAPI 构建的商城项目API

    使用FastAPI 构建的商城项目API 学习FastAPI 构建项目目录 构建项目接口 环境 项目文件结构 文件结构是仿照Flask项目目录构建的,官方推荐的模版对我而言太大. . |_FastDe ...

  3. 实操指南:用谷歌AutoML构建图像分类模型

    2020-03-16 12:31:00 全文共2710字,预计学习时长8分钟 如何用谷歌AutoML创建单标签分类模型? 今天我们将使用一个来自generated.photos的AI生成的人脸数据集, ...

  4. 深度学习(五十六)tensorflow项目构建流程

    tensorflow项目构建流程 博客:http://blog.csdn.net/hjimce 微博:黄锦池-hjimce   qq:1393852684 一.构建路线 个人感觉对于任何一个深度学习库 ...

  5. Keras正式从TensorFlow分离:结束API混乱与耗时编译

    以后在本地运行 Keras Bazel 测试将不再花费几小时,只需要几分钟. 对于深度学习领域的从业者而言,Keras 肯定不陌生,它是深度学习的主流框架之一.2015 年 3 月 27 日,谷歌软件 ...

  6. TensorFlow 2 Object Detection API 教程: 安装

    TensorFlow 2 Object Detection API 教程: 安装 本教程针对的是TensorFlow 2.4,它是TensorFlow 2.x的最新稳定版本. 这是一个循序渐进的教程/ ...

  7. 分布式 TensorFlow:Distribution Strategy API 丨Google 开发者大会 2018

    Google 开发者大会 (Google Developer Days,简称 GDD) 是展示 Google 最新开发者产品和平台的全球盛会,旨在帮助你快速开发优质应用,发展和留住活跃用户群,充分利用 ...

  8. 需要更换手机了:由 TensorFlow Lite 构建无人驾驶微型汽车

    今天在 Tensorflow公号看到推文Pixelopolis:由 TensorFlow Lite 构建无人驾驶微型汽车 ,作者介绍了他们在今年Google I/O大会上展示的TensorFlot L ...

  9. 用 Flask 来写个轻博客 (36) — 使用 Flask-RESTful 来构建 RESTful API 之五

    Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 PUT 请求 DELETE 请求 测试 对一条已经存在的 posts ...

最新文章

  1. CPU值满resmgr:cpu quantum造成的Oracle等待事件解决办法
  2. linux程序重读分区表,重读分区表, 求教~~, 系统是 Cent6.5,
  3. oracle循环插入数据用于测试
  4. 为何大部分人成不了技术专家?
  5. C++|STL学习笔记-map的基本操作(插入,删除,遍历,大到小输出)【仿大佬写法】
  6. Think in AngularJS :对比 jQuery 和 AngularJS 的不同思维模式
  7. log4j.xml示例_log4j.xml示例配置
  8. Python Frozenset()
  9. 东南大学毕业论文latex模板
  10. es 修改拼音分词器源码实现汉字/拼音/简拼混合搜索时同音字不匹配
  11. 计算机主板图解内存插槽,图解电脑主板上的常见部件 -电脑资料
  12. 给SLAM小车添加 手柄遥控 功能 罗技F710和PS4 手柄
  13. Kaggle数据集Telco-Customer-Churn.csv特征相关性分析(用LabelEncoder编码)
  14. 程序设计基础java_Java程序设计基础
  15. win10系统的qq无网络连接网络连接到服务器,Win10能上qq打不开网页_Win10能上qq不能上网怎么办?-192路由网...
  16. 假程序员启示录:房价
  17. Windows 10蓝牙只能发送文件到手机而无法从手机接收文件
  18. 【并发编程神器】,Worker Thread模式
  19. 《淘宝网开店 拍摄 修图 设计 装修 实战150招》一一2.15圆形构图
  20. 不需要下载7-zip 解压 7z.001 7z.002 7z.003

热门文章

  1. 剑破冰山:Oracle开发艺术(目录)
  2. openjudge 1.7.6 合法C标识符
  3. 一个功能强大的画图板(三)
  4. tfs_client php,TFS 源码分析 写文件操作 Client端
  5. Ubuntu 13.10 安装stardict词典(星际译王)
  6. 本地部署easyMock
  7. vue-vue2脚手架14-插槽(slot)
  8. DeviceXPlorer OPC Server支持哪些设备?本文已列举出来了
  9. onie支持pice硬盘
  10. Mysql MHA搭建