使用Flask上传图片,使用cv2进行处理,并且展示到前端

该文章展示了一个使用Flask框架处理图片上传的示例。前端通过HTML表单提交图片,后端Python代码接收文件,生成唯一的文件名,保存原始图片并进行灰度转换处理。处理后的图片会再次保存,并在页面上显示原图和处理后的图。
摘要由CSDN通过智能技术生成

1 文件夹路径

2 前端代码

将文件保存为upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask上传图片演示</title>
</head>
<body>
    <h1>上传图片</h1>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file"/>
        <br>
        <input type="submit" value="上传" class="button-new" />
    </form>
    <img src={{o_img_path}} width="500" />
    <img src={{p_img_path}} width="500" />
</body>
</html>

3 后端

from flask import Flask, render_template, request
import os

app = Flask(__name__)
import datetime
import random
import numpy as np
import cv2  # 对图像进行处理
from PIL import Image  # 对图像进行处理


@app.route('/', methods=['POST', 'GET'])  # 添加路由
def upload():
    if request.method == 'POST':
        # 1 生成一个随机的文件名:唯一
        nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        randomNum = random.randint(0, 100)
        if randomNum <= 10:
            randomNum = str(0) + str(randomNum)
        uniqueNum = str(nowTime) + str(randomNum)

        # 2 获取图像
        f = request.files['file']  # 获取文件
        basepath = os.path.dirname(__file__) # 基础路径
        suffix = f.filename.split(".")[1]  # 后缀名1.jpg ->jpg

        # 3 保存原图像
        o_img_path = basepath + "/static/images/" + uniqueNum + "_o" + "." + suffix  # 原图像
        f.save(o_img_path)

        # 4 处理图像 yolov5 处理
        img = Image.open(f.stream)
        img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
        gray2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 灰度转换
        p_img_path = basepath + "/static/images/" + uniqueNum + "_p" + "." + suffix  # 处理后
        cv2.imencode("." + suffix, gray2)[1].tofile(p_img_path)

        return render_template('upload.html',
                               o_img_path="/static/images/" + uniqueNum + "_o" + "." + suffix,
                               p_img_path="/static/images/" + uniqueNum + "_p" + "." + suffix)
    return render_template('upload.html')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8987, debug=True)

4 效果

在这里插入图片描述

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
可以的,以下是代码和解释: 首先,需要安装yolov5和flask库。可以使用以下命令安装: ``` pip install yolov5 flask ``` 然后,创建一个名为app.py的文件,将以下代码复制到文件: ```python from flask import Flask, render_template, Response import cv2 from yolov5 import YOLOv5 app = Flask(__name__) # 初始化yolov5模型 yolo = YOLOv5(weights='yolov5s.pt') # 打开摄像头 cap = cv2.VideoCapture(0) def detect_objects(): while True: # 从摄像头读取一帧图像 ret, frame = cap.read() # 对图像进行目标检测 results = yolo.detect(frame) # 在图像上绘制检测结果 for result in results: x1, y1, x2, y2, class_id, confidence = result cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.putText(frame, f'{yolo.classes[class_id]} {confidence:.2f}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) # 将图像转换为JPEG格式并输出到前端网页 ret, jpeg = cv2.imencode('.jpg', frame) frame = jpeg.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app.route('/') def index(): return render_template('index.html') @app.route('/video_feed') def video_feed(): return Response(detect_objects(), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(debug=True) ``` 代码使用了yolov5进行目标检测,并使用flask将检测结果在前端网页上展示出来。 在运行代码之前,需要创建一个名为index.html的模板文件,将以下代码复制到文件: ```html <!DOCTYPE html> <html> <head> <title>Object Detection</title> </head> <body> <h1>Object Detection</h1> <img src="{{ url_for('video_feed') }}"> </body> </html> ``` 代码使用flask的模板引擎,将视频流展示在网页上。 最后,运行app.py文件,打开浏览器访问http://localhost:5000,即可看到目标检测的结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王小葱鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值