1

我有一个从 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>
4

1 回答 1

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)
于 2018-03-16T10:53:56.877 回答