python post传入web端遇到的问题~base64与pil、numpy与base64之间进行互相转换及后续问题

文章目录

    • base64与pil、numpy与base64之间进行互相转换
    • 报错1:TypeError: Object of type 'bytes' is not JSON serializable
    • 报错2:error“: “Unsupported Media Type“

base64与pil、numpy与base64之间进行互相转换

import base64
import numpy as np
import cv2
from PIL import Image
from io import BytesIO
def base64_pil(base64_str):
    image = base64.b64decode(base64_str)
    image = BytesIO(image)
    image = Image.open(image)
    return image
def pil_base64(image):
    img_buffer = BytesIO()
    image.save(img_buffer, format='JPEG')
    byte_data = img_buffer.getvalue()
    base64_str = base64.b64encode(byte_data)
    return base64_str
def base64_numpy(base64_str):
    img_data = base64.b64decode(base64_str)
    np_data = np.fromstring(img_data,np.uint8)
    img_np = cv2.imdecode(np_data,cv2.IMREAD_COLOR)
    return img_np
def image_to_base64(img):
    """
    param   :ndarray image
    function:ndarray img ->PIL ->bytes
    return  :str base64
    """
    image = Image.fromarray(img)
    output_buffer = BytesIO()
    image.save(output_buffer, format='JPEG')
    byte_data = output_buffer.getvalue()
    base64_str = base64.b64encode(byte_data) 
    return base64
def opendir_to_ndarray(img_dir)
    with open(img_dir, 'rb') as f:
        img_file = f.read()
    im = img_file
    data = np.frombuffer(im, dtype='uint8')
    im = cv2.imdecode(data, 1)  # BGR mode, but need RGB mode

    im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)

报错1:TypeError: Object of type ‘bytes’ is not JSON serializable

与web端交互的json是个字典的值为str类型的数据,图片在经过numpy处理后变为ndarray格式,首先按照方法image_to_base64(img)转为base64,然后再转为str才能作为json中字典的值上传web端,
操作为:

str(base64.b64encode(base64), encoding='utf-8')

报错2:error“: “Unsupported Media Type“

在与服务端交互时,上传的信息报错

1、报错版本:

r = requests.post(url=url, data=data)

2、原因:
需要设置内容类型标头

3、修正版本:

requests.post(url=url, data=data, headers={"content-type": "application/json"})

你可能感兴趣的:(上班,Error,python)