千家信息网

用Tensorflow和FastAPI构建图像分类API

发表于:2025-12-02 作者:千家信息网编辑
千家信息网最后更新 2025年12月02日,用Tensorflow和FastAPI构建图像分类API,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。让我们从一个简单的
千家信息网最后更新 2025年12月02日用Tensorflow和FastAPI构建图像分类API

用Tensorflow和FastAPI构建图像分类API,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

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

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

from fastapi import FastAPIapp = 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 model    model = 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.0        result = 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 uvicornfrom 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)

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对的支持。

图像 函数 分类 支持 对象 文件 方法 模型 帮助 训练 不同 普通 清楚 事件 代码 像素 内容 参数 大小 对此 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 深圳软件开发公司哪家强些 数据库查询怎么改列标题 网络安全维护防范 安庆安卓软件开发公司哪家好 正元管线数据库建立 阿里云服务器内网有啥用 厦门市海豹网络技术有限公司 ibm服务器有3c认证吗 db2数据库重启注意事项 人脸识别说数据库没有怎么办 学网络技术等基础 苹果查找未连接服务器 gta 服务器手动刷新 网络数据库是网络教育资源吗 山东常见软件开发市场报价 南京助力智慧工地软件开发 聚英教育软件开发 杭州net软件开发哪家可靠 学生网络安全宣传作品大赛 万方智搜的合作数据库 校园网网络技术方案的摘要 服务器安全防护哪家好服务 我为网络安全代言板报 手机怎么进传奇服务器 电力公司网络安全组职责 怎么访问阿里云数据库 计算机网络技术应聘职位 爱逸族网络技术股份有限公司 手机连接服务器异常 做一个官网买哪种服务器
0