python opencv base64和cv2之间互转+tensor

import numpy as np
import cv2
from albumentations.pytorch import ToTensorV2
import albumentations as alb
import base64

def base64_to_image(base64_code):
    # base64解码
    img_data = base64.b64decode(base64_code)
    # 转换为np数组
    img_array = np.fromstring(img_data, np.uint8)
    # 转换成opencv可用格式
    img = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)
    image = np.array(img)
    transform = alb.Compose(
        [
            alb.Resize(height, width),
            # alb.ImageCompression(95, p=.3),
            # alb.ToGray(always_apply=True),
            alb.Normalize(),
            # alb.Sharpen(),
            ToTensorV2(),
        ]
    )
    image = transform(image=image)["image"].unsqueeze(0)
    return image
def image_to_base64(image_path):
    with open(image_path, "rb") as f:
        # b64encode是编码,b64decode是解码
        base64_data = base64.b64encode(f.read())
        return base64_data

你可能感兴趣的:(python,python,opencv,计算机视觉)