Flask框架下图像的base64编码接收和解码流程

一、Flask简介

Flask是一个轻量级的可定制框架,使用Python语言编写,较其他同类型框架更为灵活、轻便、安全且容易上手。它可以很好地结合MVC模式进行开发,开发人员分工合作,小型团队在短时间内就可以完成功能丰富的中小型网站或Web服务的实现。另外,Flask还有很强的定制性,用户可以根据自己的需求来添加相应的功能,在保持核心功能简单的同时实现功能的丰富与扩展,其强大的插件库可以让用户实现个性化的网站定制,开发出功能强大的网站。

二、Flask启动代码

Flask的安装也比较简单,百度上有很多教程,建立一个app_VD.py,代码如下:

python 复制代码
from flask import Flask
from flask_cors import CORS
from VideoDiagnose import vd_Process

#加载配置
app = Flask(__name__)
app.config.from_pyfile("config.py")
CORS(app)

app.register_blueprint(vd_Process, url_prefix="/")

#启动算法sever
if __name__ == '__main__':

    app.run(host=app.config['HOST'], port=app.config['PORT'], debug=app.config['DEBUG'])

其中, config.py为配置文件,内容参考代码段如下:

python 复制代码
PORT = '5585'
HOST = '0.0.0.0'
DEBUG = True

以上为Flask启动流程,直接使用python app_VD.py即可执行程序,执行后输出:

三、base64图像部分设计

3.1 json参数

通过postman以post的方式发送图像json文件,内容如下:

python 复制代码
{
    "algConfig": {
        "b_colordistortion": 1,
        "b_contrast": 1,
        "b_definition": 1,
        "b_noise": 1,
        "b_shade": 1,
        "b_signalloss": 1,
        "b_strip": 1,
        "b_highBrightness": 1,
        "b_lowBrightness": 1,
        "b_stationaryframe": 1,
        "f_Quality": 0.2
    },
    "images": [
        {
            "base64Data": "/9j//gARTGF2YzU4LjEzNC4xMDAA/9sAQwAIBAQEBAQFBQUFBQUGBgYGBgYGBgYGBgYGBwcHCAgIBwcHBgYHBwgICAgJCQkICAgICQkKCgoMDAsLDg4OEREU/90ABAAU/8QBogAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoLAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgsQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+hEAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/8AAEQgAtAFAAwEiAAIRAAMRAP/aAAwDAQACEQMRAD8A9VopaSgAopaSgBaKSlBoAOtFLSdaADFFLSYoAKSnUlABRiiigAxRRRQAlFGKKAClpKKAFoozRmgAoozRmgAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/Q9WopBS0AFFFFABRRRigBDQKXFHagAooooAKKM0CgAwaKWkNABRRiigApKWigAxSYpeaTmgAopcUYoASilxRigBKM0tFABmjNFFABmjNFIaAFzRmkooAXNGaSigBc0ZpKKAFzRmkxRigBc0ZpMUYoA//R9VpaKKACiijFABRRiigBDS0mKWgBKKWigBKKXFAoASjvS0UABpKXijFACUUvFFABSUYoxQAc0UtFACUUuKMUAJRS4oxQAlFLijFACUUuKMUAJRilxRQAYpKWigBKWk5oxQAtFJijFAC0UlGKAP/S9WopMUYoAWikxRigBaKTFLQAUUUUAFFFFABRRRmgAo70UUAApaSloAKbinUnFABikpaKAEpaDSUALRSUUALRRijFABRRijFABRRRigAooooAKKKKACiiigAooooAKKKKAP/T9WooooAKKM0maAFoo4ooAKKKKAAUopOaU0ABpKKKACiiigAoFFFAAaKMUUAApeKSigAooooAKWiigBKKWjigBKKXijigBKKXiigBKKWigAxRiiigBMUUtJQAUUUUAFFGKXFAH//U9WpM0tGaADFFGaKACg0Cl5oASgUc0UAFFFGaACijFGKACilxRQAlLRSUAHNLRSUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFLSCloASil4o4oAMUhpaKACikooAWikooA//1fVqWkooAWkpeaOaACijmjmgApKKOaADFLRRQAnNFLijFACZopcUYoASloxRQAhopaMUAJRS4oxQAlFLijFACUUuKMUAJRS4oxQAlFLijFACUUtFABRRSUALRSUtACUtJRQAtJS0UAJRS0lAH//W9Wo5oooAWikooAXmikooAKKKKAFpKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKMUUUAGKKKKAFopKKAFpKKXFAH//X9WoooxQAUUUUAApeaMUlABRRmlzQAlFLmjNACUUuaM0AJRS5ozQAlFLmjNACUUuaM0AJRS5ozQAlFLmjNACUUuaM0AJRS5ozQAlFLmjNACUUuaM0AJS8UZozQAlFLmjNACUUuaM0AJRS5ozQAUlLmkoA/9D1ajmilxQAUUUUAFJQaKACiiigAooooAKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWkoA/9H1fNGaSg0ALSUUUAFFFFABS8UlFAC8UUlFAC0UlFAC0UlFAC0UlFAC0UlFAC0UlFAC0UlFAC0UlFAC0UlFAC0UlFAC0UlFAC0UlFAC0UUlAC0UlFAC0ZpKKAFpKKXFAH//0vV+9HajvR2oAKQ0tIaACiiigAooooAKKKKACiiigAooooABS0CigAooooAKKKKACiiigAooooAKKKKACiiigBDRQaKACiiigANLSGlFABijFFFABiiiigBD1o60HrQKAP/Z"
        }
    ]
}

3.2 接收部分代码

也就是base64部分的json数据接收和图像解析代码,解析文件为VideoDiagnose.py,代码内容如下:

python 复制代码
import os
import cv2
import requests
import base64
import json
import threading
import numpy as np
import time
import datetime
from flask import Blueprint
from flask import request
from flask import current_app as app
import queue

vd_Process = Blueprint('vd_Process', __name__)
device = torch.device('cpu')

def image_to_base64(filepath):

    """将 JPG 文件转换为 Base64 编码字符串"""
    with open(filepath, "rb") as image_file:
        # 读取文件内容到字节串
        encoded_string = base64.b64encode(image_file.read())
        # 将字节串解码为 UTF-8 字符串
        return encoded_string.decode('utf-8')

def base64_to_image(base64_string):

    # Base64 字符串解码为字节
    img_data = base64.b64decode(base64_string)
    # 将字节转换为 NumPy 数组
    nparr = np.frombuffer(img_data, np.uint8)
    # 解码图像
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    # cv2.imshow("img",img)
    # cv2.waitKey(0)

    return img

def vqd_detect(json_data):

    images_Array = []
    try:#检测参数是否正确
        b_colordistortion = json_data["algConfig"]['b_colordistortion']#1
        b_contrast = json_data["algConfig"]['b_contrast']#2
        b_definition = json_data["algConfig"]['b_definition']#3
        b_noise = json_data["algConfig"]['b_noise']#4
        b_shade = json_data["algConfig"]['b_shade']#5
        b_signalloss = json_data["algConfig"]['b_signalloss']#6
        b_strip = json_data["algConfig"]['b_strip']#7
        b_highBrightness = json_data["algConfig"]['b_highBrightness']#8
        b_lowBrightness =  json_data["algConfig"]['b_lowBrightness']#9
        b_stationaryframe = json_data["algConfig"]['b_stationaryframe']#10
        f_Quality = json_data["algConfig"]['f_Quality']

        images = json_data['images']
        for image_data in images:
            base64_data = image_data["base64Data"]
            if len(base64_data) > 2000:
                images_Array.append(base64_data)

    except Exception as e:
        return "Json_Params_Error",{}

    if len(images_Array) == 0 or len(images_Array) > 3:
        return "No_images_Error",{}

    decodeImageArray = []
    try:#图像转换,变成CV图像
        for image_data in images_Array:
            cvImage = base64_to_image(image_data)
            decodeImageArray.append(cvImage)
    except Exception as e:
        return "Image_Params_Error",{}

    out_Result = {}
    out_Result["b_normal"] = 0#0
    #out_Result["n_normal"] = 1.0
    out_Result["b_colordistortion"] = 0#1
    out_Result["n_colordistortion"] = 1.0
    out_Result["b_contrast"] = 0#2
    out_Result["n_contrast"] = 1.0
    out_Result["b_definition"] = 0#3
    out_Result["n_definition"] = 1.0
    out_Result["b_noise"] = 0#4
    out_Result["n_noise"] = 1.0
    out_Result["b_shade"] = 0#5
    out_Result["n_shade"] = 1.0
    out_Result["b_signalloss"] = 0#6
    out_Result["n_signalloss"] = 1.0
    out_Result["b_strip"] = 0#7
    out_Result["n_strip"] = 1.0
    out_Result["b_highBrightness"] = 0#8
    out_Result["n_highBrightness"] = 1.0
    out_Result["b_lowBrightness"] = 0#9
    out_Result["n_lowBrightness"] = 1.0
    out_Result["b_stationaryframe"] = 0#10
    out_Result["n_stationaryframe"] = 1.0

    cvResizeImage = cv2.resize(decodeImageArray[len(decodeImageArray) - 1], [480, 270])
    gray_image = cv2.cvtColor(cvResizeImage, cv2.COLOR_BGR2GRAY)
    cv2.imshow("image", cvResizeImage)
    cv2.imshow("cut", cvResizeImage)
    cv2.waitKey(0)

    return "success",out_Result

@vd_Process.route('/vd_Process', methods=['POST'])
def handel_VD_Process():

    timestamp = time.time()
    format_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(timestamp))
    print(format_time)

    try:
        json_data = request.json
    except Exception as e:
        headers = {"Content-Type": "application/json"}
        json_send_data = {
            "data": {
                "status": "Json_GET_Error",
                "executeTime": format_time,
                "result": {}
            }
        }
        return json_send_data, 200, headers

    status,out_Result = vqd_detect(json_data)

    headers = {"Content-Type": "application/json"}
    json_send_data = {
        "data": {
            "status": status,
            "executeTime": format_time,
            "result": out_Result
        }
    }
    return json_send_data, 200, headers

if __name__ == '__main__':

    print()

四、运行结果

Flask执行后的状态得到一张灰白图像。 postman输出的结果如下内容所示:

python 复制代码
{
    "data": {
        "executeTime": "2024-07-03 20:06:30",
        "result": {
            "b_colordistortion": 0,
            "b_contrast": 0,
            "b_definition": 0,
            "b_highBrightness": 0,
            "b_lowBrightness": 0,
            "b_noise": 0,
            "b_normal": 0,
            "b_shade": 0,
            "b_signalloss": 0,
            "b_stationaryframe": 0,
            "b_strip": 0,
            "n_colordistortion": 1.0,
            "n_contrast": 1.0,
            "n_definition": 1.0,
            "n_highBrightness": 1.0,
            "n_lowBrightness": 1.0,
            "n_noise": 1.0,
            "n_shade": 1.0,
            "n_signalloss": 1.0,
            "n_stationaryframe": 1.0,
            "n_strip": 1.0
        },
        "status": "success"
    }
}
相关推荐
Captain823Jack27 分钟前
nlp新词发现——浅析 TF·IDF
人工智能·python·深度学习·神经网络·算法·自然语言处理
资源补给站1 小时前
大恒相机开发(2)—Python软触发调用采集图像
开发语言·python·数码相机
Captain823Jack1 小时前
w04_nlp大模型训练·中文分词
人工智能·python·深度学习·神经网络·算法·自然语言处理·中文分词
刘大辉在路上1 小时前
突发!!!GitLab停止为中国大陆、港澳地区提供服务,60天内需迁移账号否则将被删除
git·后端·gitlab·版本管理·源代码管理
PieroPc1 小时前
Python 自动化 打开网站 填表登陆 例子
运维·python·自动化
VinciYan2 小时前
基于Jenkins+Docker的自动化部署实践——整合Git与Python脚本实现远程部署
python·ubuntu·docker·自动化·jenkins·.net·运维开发
测试老哥2 小时前
外包干了两年,技术退步明显。。。。
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展
終不似少年遊*2 小时前
美国加州房价数据分析01
人工智能·python·机器学习·数据挖掘·数据分析·回归算法
如若1233 小时前
对文件内的文件名生成目录,方便查阅
java·前端·python
追逐时光者3 小时前
免费、简单、直观的数据库设计工具和 SQL 生成器
后端·mysql