Python中cv2.imread()与base64编码、PIL格式互相转换

Python中cv2.imread()与base64编码、PIL格式互相转换

Base64编码

图片的base64编码指将一副图片数据编码成一串字符串,使用该字符串代替图像地址。

Base64主要在post请求时用的比较多。

可能根据实际应用存在cv2、base64、PIL直接的相互转换。

所以本文提供cv2.imread()读取的图像与base64格式、PIL互转。

在pil转base64的时候,网上各种资料的方法感觉都很复杂。这里是通过PIL转cv2,再从cv2转base64的方式实现的。

import base64
import numpy as np
import cv2
from PIL import Image
from io import BytesIO
import time


# cv2转base64
def cv2_to_base64(img):
    img = cv2.imencode('.jpg', img)[1]
    image_code = str(base64.b64encode(img))[2:-1]

    return image_code


# base64转cv2
def base64_to_cv2(base64_code):
    img_data = base64.b64decode(base64_code)
    img_array = np.fromstring(img_data, np.uint8)
    img = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)

    return img


# base64转PIL
def base64_to_pil(base64_str):
    image = base64.b64decode(base64_str)
    image = BytesIO(image)
    image = Image.open(image)

    return image


# PIL转base64
def pil_to_base64(image):
    img = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
    base64_str = cv2_to_base64(img)

    return base64_str


# PIL转cv2
def pil_to_cv2(image):
    img = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)

    return img


# cv2转PIL
def cv2_to_pil(img):
    image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

    return image


if __name__ == '__main__':
    cv2_img = cv2.imread('./test.jpg')
    start_time =time.time()
    code = cv2_to_base64(cv2_img)
    print(code)

    img = base64_to_cv2(code)
    cv2.imwrite('test.jpg', img)


你可能感兴趣的:(python,python,arduino)