Python进阶-部署Flask项目(以TensorFlow图像识别项目WSGI方式启动为例)

本文主要是介绍Python进阶-部署Flask项目(以TensorFlow图像识别项目WSGI方式启动为例),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文详细介绍了如何通过WSGI方式部署一个基于TensorFlow图像识别的Flask项目。首先简要介绍了Flask框架的基本概念及其特点,其次详细阐述了Flask项目的部署流程,涵盖了服务器环境配置、Flask应用的创建与测试、WSGI服务器的安装与配置等内容。本文旨在帮助读者掌握Flask项目的部署方法,解决在部署过程中可能遇到的问题,确保项目能够稳定高效地运行。

一、Flask简介

Flask是一个轻量级的Web应用框架,由Python语言编写。它是基于Werkzeug WSGI工具包和Jinja2模板引擎的,并且采用BSD许可证。Flask的设计哲学是“微核”,也就是说其核心保持简洁,功能通过扩展实现。这使得Flask非常灵活,能够满足从小型单一页面应用到大型复杂项目的不同需求。

Flask的主要特点包括:

  1. 轻量级和灵活:Flask仅提供核心功能,开发者可以根据需要引入各种扩展。
  2. 易于学习和使用:Flask的API设计非常简洁明了,即使是初学者也能快速上手。
  3. 强大的扩展能力:Flask的生态系统中有许多可用的扩展,可以轻松添加数据库、表单验证、用户认证等功能。
  4. 社区支持:Flask拥有活跃的社区,大量的教程和文档可以帮助开发者解决问题。

二、Flask项目部署流程

1. 准备工作

在开始部署Flask项目之前,需要完成以下准备工作:

① 服务器安装Anaconda

Anaconda是一个用于科学计算的Python发行版,支持多种数据科学包的快速安装。它还包含了Conda,这是一种包管理器和环境管理器,能够轻松创建和管理不同的Python环境。

首先,下载并安装Anaconda。可以从Anaconda官网下载适用于Windows的安装包。安装过程非常简单,按照提示进行即可。

② Anaconda创建Python环境

安装完成后,使用Conda创建一个新的Python环境。这可以帮助你隔离项目的依赖,确保环境的一致性。打开终端(或命令提示符),输入以下命令创建一个名为opencv的环境,并指定Python版本:

conda create -n opencv python=3.8

创建完成后,激活这个环境:

conda activate opencv

在这里插入图片描述

③ Anaconda环境安装相关包

在激活的环境中,安装Flask、Flask-CORS、TensorFlow、scikit-learn和OpenCV等必要的包:

conda install flask flask-cors tensorflow scikit-learn opencv

这些包包含了构建和运行Flask应用及其依赖的所有工具。

2. 创建Flask应用

在本地编写并测试Flask应用代码。以下是一个简单的Flask应用示例,它使用TensorFlow的MobileNetV2模型进行图像分类和相似度计算:

from flask import Flask, request, jsonify
from flask_cors import CORS
import numpy as np
import cv2
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
from sklearn.metrics.pairwise import cosine_similarityapp = Flask(__name__)
CORS(app)# 加载预训练的MobileNetV2模型
model = MobileNetV2(weights='imagenet', include_top=True)def classify_image(img):img = cv2.resize(img, (224, 224))  # MobileNetV2的输入尺寸为224x224x = image.img_to_array(img)x = np.expand_dims(x, axis=0)x = preprocess_input(x)preds = model.predict(x)return decode_predictions(preds, top=1)[0][0][1], model.predict(x)  # 返回类别名称和特征向量def calculate_similarity(feature1, feature2):return cosine_similarity(feature1, feature2)[0][0]@app.route('/compare', methods=['POST'])
def compare_images():file1 = request.files['image1']file2 = request.files['image2']npimg1 = np.frombuffer(file1.read(), np.uint8)npimg2 = np.frombuffer(file2.read(), np.uint8)img1 = cv2.imdecode(npimg1, cv2.IMREAD_COLOR)img2 = cv2.imdecode(npimg2, cv2.IMREAD_COLOR)# 分类和特征提取class1, feature1 = classify_image(img1)class2, feature2 = classify_image(img2)if class1 != class2:similarity = 0.0risk_level = "低"intervention = "否"else:similarity = calculate_similarity(feature1, feature2)risk_level = "高" if similarity > 0.8 else "中" if similarity > 0.5 else "低"intervention = "是" if similarity > 0.8 else "否"return jsonify({'similarity': f'{similarity * 100:.2f}%','risk_level': risk_level,'intervention': intervention,'class1': class1,'class2': class2})if __name__ == '__main__':app.run(debug=True)

在确保代码在本地运行正常。

3、本地运行Flask服务器

在本地Anaconda中启动opencv环境的终端,运行以下命令启动Flask服务器:

python app.py

在这里插入图片描述
服务器启动后,将会监听在本地的5000端口。

① 页面前端代码实现

创建一个HTML文件(test.html),实现图片上传和结果展示功能,全部代码如下:

<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>图片对比</title><style>body {font-family: Arial, sans-serif;display: flex;flex-direction: column;align-items: center;margin: 0;padding: 20px;}.container {display: flex;justify-content: space-between;width: 80%;margin-bottom: 20px;}.image-box {width: 45%;border: 2px dashed #ccc;padding: 10px;text-align: center;position: relative;}.image-box img {max-width: 100%;max-height: 200px;display: none;}.image-box input {display: none;}.upload-btn {cursor: pointer;color: #007BFF;text-decoration: underline;}.loading-bar {width: 80%;height: 20px;background-color: #f3f3f3;border: 1px solid #ccc;margin-top: 10px;display: none;position: relative;}.loading-bar div {width: 0;height: 100%;background-color: #4caf50;position: absolute;animation: loading 5s linear forwards;}@keyframes loading {to {width: 100%;}}.result {display: none;margin-top: 20px;}</style>
</head>
<body><h1>图片对比</h1><div class="container"><div class="image-box" id="box1"><label for="upload1" class="upload-btn">上传图片</label><input type="file" id="upload1" accept="image/*"><img id="image1" alt="左边文本抓取图片"></div><div class="image-box" id="box2"><label for="upload2" class="upload-btn">上传图片</label><input type="file" id="upload2" accept="image/*"><img id="image2" alt="右边文本数据库图片"></div></div><button id="compare-btn">人工智能对比</button><div class="loading-bar" id="loading-bar"><div></div></div><div class="result" id="result"><p>相似百分比: <span id="similarity">0%</span></p><p>相似度: <span id="risk-level"></span></p><p>相同个体推测: <span id="intervention"></span></p><p>1种类: <span id="class1">-</span></p><p>2种类: <span id="class2">-</span></p></div><script>document.getElementById('upload1').addEventListener('change', function(event) {loadImage(event.target.files[0], 'image1', 'box1');});document.getElementById('upload2').addEventListener('change', function(event) {loadImage(event.target.files[0], 'image2', 'box2');});function loadImage(file, imgId, boxId) {const reader = new FileReader();reader.onload = function(e) {const img = document.getElementById(imgId);img.src = e.target.result;img.style.display = 'block';document.querySelector(`#${boxId} .upload-btn`).style.display = 'none';}reader.readAsDataURL(file);}document.getElementById('compare-btn').addEventListener('click', function() {const loadingBar = document.getElementById('loading-bar');const result = document.getElementById('result');const image1 = document.getElementById('upload1').files[0];const image2 = document.getElementById('upload2').files[0];if (!image1 || !image2) {alert('请上传两张图片进行对比');return;}const formData = new FormData();formData.append('image1', image1);formData.append('image2', image2);loadingBar.style.display = 'block';result.style.display = 'none';fetch('http://localhost:5000/compare', {method: 'POST',body: formData}).then(response => response.json()).then(data => {loadingBar.style.display = 'none';result.style.display = 'block';document.getElementById('similarity').innerText = data.similarity;document.getElementById('risk-level').innerText = data.risk_level;document.getElementById('intervention').innerText = data.intervention;document.getElementById('class1').innerText = data.class1;document.getElementById('class2').innerText = data.class2;}).catch(error => {loadingBar.style.display = 'none';alert('对比过程中发生错误,请重试');console.error('Error:', error);});});</script>
</body>
</html>

② 运行网页

双击运行,刚刚创建的test.html文件,效果如图:
在这里插入图片描述
上传左右图片,比较两只相同品种的狗的相似度:
在这里插入图片描述

可以看到系统识别出了两只狗的种类相同,相似比也高达75.2%,但因为没有达到我们设置的80%的阈值,所以判断非同一个体。当然,这里的80%非常牵强,实际操作中难免误差较大。由于本文算法使用的是MobileNetV2预训练模型,并没有根据实际应用场景大量训练和调参,所以如果投入应用,仍需重新训练并根据实际效果定义阈值。

确认本地运行正常,接下来就可以进行部署了。

4. 安装Waitress服务器

Waitress是一个Python WSGI服务器,适用于在生产环境中部署Flask应用。它简单易用,适合部署中小型应用。使用pip安装Waitress:

pip install waitress

在这里插入图片描述

5. 修改代码以使用Waitress

将Flask应用代码保存为 compare.py,并确保在本地测试通过。然后创建一个批处理文件 start.cmd,内容如下:

@echo off
python -m waitress --listen=*:8000 compare:app
pause

确保 compare.py 文件中的Flask应用对象名为 app,例如:

from flask import Flask, request, jsonify
from flask_cors import CORS
import numpy as np
import cv2
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
from sklearn.metrics.pairwise import cosine_similarityapp = Flask(__name__)
CORS(app)# 加载预训练的MobileNetV2模型
model = MobileNetV2(weights='imagenet', include_top=True)def classify_image(img):img = cv2.resize(img, (224, 224))  # MobileNetV2的输入尺寸为224x224x = image.img_to_array(img)x = np.expand_dims(x, axis=0)x = preprocess_input(x)preds = model.predict(x)return decode_predictions(preds, top=1)[0][0][1], model.predict(x)  # 返回类别名称和特征向量def calculate_similarity(feature1, feature2):return cosine_similarity(feature1, feature2)[0][0]@app.route('/compare', methods=['POST'])
def compare_images():file1 = request.files['image1']file2 = request.files['image2']npimg1 = np.frombuffer(file1.read(), np.uint8)npimg2 = np.frombuffer(file2.read(), np.uint8)img1 = cv2.imdecode(npimg1, cv2.IMREAD_COLOR)img2 = cv2.imdecode(npimg2, cv2.IMREAD_COLOR)# 分类和特征提取class1, feature1 = classify_image(img1)class2, feature2 = classify_image(img2)if class1 != class2:similarity = 0.0risk_level = "低"intervention = "否"else:similarity = calculate_similarity(feature1, feature2)risk_level = "高" if similarity > 0.8 else "中" if similarity > 0.5 else "低"intervention = "是" if similarity > 0.8 else "否"return jsonify({'similarity': f'{similarity * 100:.2f}%','risk_level': risk_level,'intervention': intervention,'class1': class1,'class2': class2})

6. 运行启动

配置WSGI启动:

python -m waitress --listen=*:5000 compare:app

在这里插入图片描述

你可以通过访问 http://localhost:5000 来测试你的应用。

然后给5000端口配置安全组/防火墙,实现通过公网访问。


三、Flask项目部署总结

本文详细介绍了如何通过WSGI方式部署一个基于TensorFlow图像识别的Flask项目。从安装和配置Anaconda环境,到编写和测试Flask应用,再到安装和配置WSGI服务器,我们覆盖了部署过程中的每一个步骤。这些步骤帮助确保你的Flask应用能够稳定高效地运行,并且在生产环境中易于维护和扩展。

通过遵循这些步骤,你可以确保你的Flask应用在各种环境中都能够正常运行,避免了在部署过程中可能遇到的许多常见问题。同时,这种方式也为你提供了一种标准化的部署流程,使得以后部署新的Flask项目变得更加简单和高效。希望本文对你的Flask开发和部署之旅有所帮助。

这篇关于Python进阶-部署Flask项目(以TensorFlow图像识别项目WSGI方式启动为例)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1046603

相关文章

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

python常用的正则表达式及作用

《python常用的正则表达式及作用》正则表达式是处理字符串的强大工具,Python通过re模块提供正则表达式支持,本文给大家介绍python常用的正则表达式及作用详解,感兴趣的朋友跟随小编一起看看吧... 目录python常用正则表达式及作用基本匹配模式常用正则表达式示例常用量词边界匹配分组和捕获常用re

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文

python删除xml中的w:ascii属性的步骤

《python删除xml中的w:ascii属性的步骤》使用xml.etree.ElementTree删除WordXML中w:ascii属性,需注册命名空间并定位rFonts元素,通过del操作删除属... 可以使用python的XML.etree.ElementTree模块通过以下步骤删除XML中的w:as

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图

深度解析Python装饰器常见用法与进阶技巧

《深度解析Python装饰器常见用法与进阶技巧》Python装饰器(Decorator)是提升代码可读性与复用性的强大工具,本文将深入解析Python装饰器的原理,常见用法,进阶技巧与最佳实践,希望可... 目录装饰器的基本原理函数装饰器的常见用法带参数的装饰器类装饰器与方法装饰器装饰器的嵌套与组合进阶技巧

如何在Spring Boot项目中集成MQTT协议

《如何在SpringBoot项目中集成MQTT协议》本文介绍在SpringBoot中集成MQTT的步骤,包括安装Broker、添加EclipsePaho依赖、配置连接参数、实现消息发布订阅、测试接口... 目录1. 准备工作2. 引入依赖3. 配置MQTT连接4. 创建MQTT配置类5. 实现消息发布与订阅