编码 - 解码base64图像

时间:2018-03-15 15:35:45

标签: python-3.x base64 python-imaging-library opencv-python

我有一个从OpenCV视频捕获对象获得的图像:

import cv2
import base64
from PIL import Image
import io
cap = cv2.VideoCapture(0)
# capture frame by frame
ret, frame = cap.read()

如何对图像进行编码和解码(即从原始像素转换为字节并返回原始像素)?

到目前为止,我一直在尝试以下方法:

encoded_string = base64.b64encode(frame)
decoded_string = base64.b64decode(encoded_string)
img = Image.open(io.BytesIO(decoded_string))
img.show()

这给了我一个错误:

File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2295, in open
    % (filename if filename else fp))
OSError: cannot identify image file <_io.BytesIO object at 0x7efddbb78e08>

1 个答案:

答案 0 :(得分:1)

使用base64编码和随后解码图像的正确方法结果如下:

import numpy as np
import cv2
import base64

cap = cv2.VideoCapture(0)
# capture frame by frame
ret, frame = cap.read()
# encode frame
encoded_string = base64.b64encode(frame)
# decode frame
decoded_string = base64.b64decode(encoded_string)
decoded_img = np.fromstring(decoded_string, dtype=np.uint8)
decoded_img = decoded_img.reshape(frame.shape)
# show decoded frame
cv2.imshow("decoded", decoded_img)