[python]http传输图片

服务端:

#coding:utf-8
from flask import request, Flask
import time
import os
from PIL import Image
from io import StringIO
import matplotlib.pyplot as plt
import cv2
import numpy as np
from io import BytesIO
import json
import base64

app = Flask(__name__)

@app.route("/", methods=['POST'])
def get_frame():
    start_time = time.time()
    upload_file = request.get_data()
    req = json.loads(upload_file)
    #old_file_name = upload_file.filename
    
    if upload_file:
        name = req['name']
        print(name)
        img_str = req['image'] #得到unicode的字符串
        img_decode_ = img_str.encode('ascii') #从unicode变成ascii编码
        img_decode = base64.b64decode(img_decode_) #解base64编码,得图片的二进制
        img_np_ = np.frombuffer(img_decode, np.uint8)
        img = cv2.imdecode(img_np_, cv2.COLOR_RGB2BGR) #转为opencv格式
        cv2.imshow('frame', img)
        
        cv2.waitKey()
        return 'success'
    else:
        return 'failed'


if __name__ == "__main__":
    app.run("127.0.0.1", port=6060)

客户端:

#coding:utf-8
import requests
import json
import numpy as np
import cv2
import base64
import matplotlib.pyplot as plt
from PIL import Image

def getByte(path):
    with open(path, 'rb') as f:
        img_byte = base64.b64encode(f.read()) #二进制读取后变base64编码
    img_str = img_byte.decode('ascii') #转成python的unicode
    return img_str 
    
img_str = getByte('zyc_0.jpg')

requestsss={'name':'张山', 'image':img_str}
req = json.dumps(requestsss) #字典数据结构变json(所有程序语言都认识的字符串)

res=requests.post('http://127.0.0.1:6060/', data=req)
print(res.text)
发布了8 篇原创文章 · 获赞 1 · 访问量 3395
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览