base64、opencv和PIL之间的互转

导入的库:

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

1、base64和PIL之间

1.1 base64转PIL

rj = request.get_json()   # 通过POST请求把base64的数据传过来
base64Image = rj['base64Image']
byte_date = base64.b64decode(base64Image)
try:
    imagede = Image.open(BytesIO(byte_date)).convert('RGB')  # 转成PIL
except Exception as e:
    print('Open Error! Try again!')
    raise e
image = np.array(imagede)   # 把PIL格式的图片转成numpy

1.2 PIL转base64

image_pil = Image.fromarray(image_np)  # image_np是numpy数据格式
output_buffer = BytesIO()
image_pil.save(output_buffer, format='JPEG')
byte_data = output_buffer.getvalue()
# 我这里需要转成str,要不然打包成json会报错
# json不能打包byte类型需要转成字符串类型才行
image_code = str(base64.b64encode(byte_data))[2:-1]

2、base64和opencv之间

2.1 base64转opencv

imgData = base64.b64decode(base64_data)
nparr = np.fromstring(imgData, np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

2.2 opencv转base64

image = cv2.imencode('.jpg', image_cv)[1]
image_code = str(base64.b64encode(image))[2:-1]

3、opencv和PIL

3.1 opencv转PIL

img = cv2.imread("plane.jpg")
cv2.imshow("OpenCV",img)
image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
image.show()
cv2.waitKey()

3.2 PIL转opencv

image = Image.open("plane.jpg")
image.show()
img = cv2.cvtColor(numpy.asarray(image),cv2.COLOR_RGB2BGR)
cv2.imshow("OpenCV",img)
cv2.waitKey()
发布了82 篇原创文章 · 获赞 126 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_31112205/article/details/103822997