1 测试脚本
import requests
import base64
import json
import time
import sys
import numpy as np
import cv2
from PIL import Image
from utils.plots import colors
import os
from tqdm import tqdm
from glob import glob
def pic_post(img,filename):
postdata = {}
postdata["input"] = str(img, encoding='utf-8')
values_json = json.dumps(postdata, ensure_ascii=False)
st = time.time()
try:
r = requests.post(' http://0.0.0.0:5000/predict', data=values_json)
et = time.time()
print(f"request_ok_time:{round(et - st, 2)}s")
except Exception as e:
et = time.time()
print(f"exception request_exception_time:{round(et - st, 2)}s")
print(f"报错:{e}")
else:
print(r.json())
results = r.json()['results']
if __name__ == '__main__':
file_path = sys.argv[1]
file_path = [file_path] if os.path.isfile(file_path) else glob(f"{file_path}/*")
for i,file in enumerate(tqdm(file_path)):
with open(file, "rb") as f:
img_read = f.read()
base64_data = base64.b64encode(img_read)
pic_post(base64_data,os.path.basename(file))
接收base64 的处理(相同图片)
1 np.frombuffer
处理
data = json.loads(request.get_data(as_text=True))
image = data['input']
if 'input' not in data:
return 'input字段不存在', 500
decode_img = base64.b64decode(image)
img_array = np.frombuffer(decode_img, np.uint8)
img0 = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
处理时间 0.2s
2 BytesIO
方式,由于后续的处理需要的都是BGR 格式,所以这儿需要把array 的顺序调换一下
data = json.loads(request.get_data(as_text=True))
image = data['input']
if 'input' not in data:
return 'input字段不存在', 500
decode_img = base64.b64decode(image)
image_data = BytesIO(decode_img)
image = Image.open(image_data)
img0 = np.array(image).astype(np.uint8)[:, :, ::-1]
处理时间 0.35s-0.4s
另外发一张对比图,上面是在linux上对比了Pillow和opencv,其他没做对比,如果是jpg图篇,用TurboJpeg 速度最快