将base64转换为cv2.numpy数组,然后再转换回base64

时间:2019-02-08 14:38:45

标签: python numpy base64 cv2

我正在设置一个Flask服务器,我通过base64格式向其发送图像。我想在该图像上执行cv2.warpPerspective函数。将结果numpy数组转换回用于在html页面中呈现的base64。我能够更改透视图,但将结果numpy数组转换为base64是不正确的,并且无法在html页面中呈现。

def change_perspective(data):
    points = []
    print("type of data",type(data))
    data_decoded = data.decode("utf-8") 
    print("type of data_decoded",type(data_decoded))
    json_data =data_decoded.replace("'", "\"")
    data = json.loads(json_data)
    coordinates =data["Coordinates"]
    for c in coordinates:
        x=c['x']
        y=c['y']
        points.append([x,y])
    image_b64=data["image_base64"].split(",")[1]
    print("base 64 image data",type(image_b64))
    nparr = np.fromstring(base64.b64decode(image_b64), np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    print('points',points)
    pts1 = np.float32(points)
    pts2 = np.float32([[0,0],[300,0],[0,500],[300,500]])
    M = cv2.getPerspectiveTransform(pts1,pts2)
    dst = cv2.warpPerspective(img,M,(300,500))
    print("Succeeeded")
    return dst


@app.route('/')
def hello_world():
    return render_template('perspective_front.html')


@app.route('/perspective', methods=['POST'])
def perspective():
    # print("Request Data",request.data)
    # print("request.data",request.data)
    print("type of request.data",type(request.data))
    warped_image = change_perspective(request.data)
    warped_image_bytes = warped_image.tobytes()
    # print("cv2.imencode('.jpg', warped_image)",cv2.imencode('.jpg', warped_image))
    warped_image_b64=  base64.b64encode(warped_image_bytes).decode('utf-8')
    return render_template('perspective_result.html', img_data="data:image/jpeg;base64,"+warped_image_b64)

从numpy数组到base64的转换是否错误?

渲染方式是错误的? 预先感谢

0 个答案:

没有答案