You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的requests库向Flask服务器POST两张OpenCV处理的图片

同一请求中向Flask服务器传输两张OpenCV图片的解决方案

你之前用列表传递两张图片原始数据失败,核心原因是raw格式的请求体没有边界标识,服务器无法区分两张图片的起始和结束位置。改用HTTP标准的multipart/form-data格式(也就是requests的files参数)就能解决问题,以下是完整实现代码:

客户端代码(发送两张图片)

import cv2
import requests
from requests.auth import HTTPBasicAuth

# 假设你已通过OpenCV获取到两张图片对象img1、img2
address = "http://你的Flask服务器地址/upload_two_images"
username = "你的用户名"
password = "你的密码"

# 将两张图片编码为JPEG格式
_, img1_encoded = cv2.imencode('.jpeg', img1)
_, img2_encoded = cv2.imencode('.jpeg', img2)

# 构造multipart/form-data格式的文件参数
files = {
    'image1': ('img1.jpg', img1_encoded.tobytes(), 'image/jpeg'),
    'image2': ('img2.jpg', img2_encoded.tobytes(), 'image/jpeg')
}

# 发送请求
response = requests.post(
    address,
    files=files,
    auth=HTTPBasicAuth(username, password)
)

# 处理响应
print(response.status_code)
print(response.json())  # 若服务器返回JSON格式响应

Flask服务器端代码(新增接收两张图片的路由)

from flask import Flask, request
import numpy as np
import cv2

app = Flask(__name__)

# 新增的接收双图路由
@app.route('/upload_two_images', methods=['POST'])
def upload_two_images():
    # 读取第一张图片
    img1_file = request.files.get('image1')
    if not img1_file:
        return {"error": "缺少image1参数"}, 400
    img1_data = img1_file.read()
    nparr1 = np.frombuffer(img1_data, np.uint8)
    img1 = cv2.imdecode(nparr1, cv2.IMREAD_COLOR)

    # 读取第二张图片
    img2_file = request.files.get('image2')
    if not img2_file:
        return {"error": "缺少image2参数"}, 400
    img2_data = img2_file.read()
    nparr2 = np.frombuffer(img2_data, np.uint8)
    img2 = cv2.imdecode(nparr2, cv2.IMREAD_COLOR)

    # 此处执行依赖两张图片的业务操作
    # 示例:result = your_process_function(img1, img2)

    return {"message": "双图接收成功", "img1_shape": img1.shape, "img2_shape": img2.shape}

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

关键说明

  1. 客户端用files参数替代原data参数,每个图片对应唯一键名(如image1、image2),服务器通过键名区分不同图片。
  2. 用tobytes()替代过时的tostring()处理编码后的图片数据,兼容性更强。
  3. 服务器端通过request.files.get()获取对应文件,读取二进制数据后解码为OpenCV图像对象。

内容的提问来源于stack exchange,提问作者danroggy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 18:03:19