code

from flask import Flask
import os
import cv2
import json
import base64
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources=r'/*')

class MyEncoder(json.JSONEncoder):

    def default(self, obj):
        """
        只要检查到了是bytes类型的数据就把它转为str类型
        :param obj:
        :return:
        """
        if isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        return json.JSONEncoder.default(self, obj)

@app.route('/Vehicle_data')
def index():
    image_names = os.listdir('./test_result/')
    image_names = sorted(image_names)
    result = []
    for index, path in enumerate(image_names):
        per_res = {}
        data = path.split('.')[0]
        # img_file = open(r'./test_result/' + path, 'rb')  # 二进制打开图片文件
        # img_b64encode = base64.b64encode(img_file.read())  # base64编码
        img = cv2.imread('./test_result/'+path)
        img_b64encode = base64.b64encode(cv2.imencode('.jpg', img)[1].tobytes())
        per_res['id'] = index
        per_res['data'] = data
        per_res['name'] = '大厦右侧'
        per_res['img'] = img_b64encode
        per_res['reason'] = '占用'

        result.append(per_res)
    return json.dumps(result, cls=MyEncoder, ensure_ascii=False)

说明

  1. base64编码的数据是二进制的,解决方案是将其转换成string
  2. json.dumps有中文字符时,会将其编码成ascii,加上ensure_ascii=False就能解决