Reputation: 1123
I have an image that is obtained from an OpenCV video capture object as such:
import cv2
import base64
from PIL import Image
import io
cap = cv2.VideoCapture(0)
# capture frame by frame
ret, frame = cap.read()
How can I encode and decode the image (i.e. go from raw pixels to bytes and back to raw pixels)?
So far I have been trying the following:
encoded_string = base64.b64encode(frame)
decoded_string = base64.b64decode(encoded_string)
img = Image.open(io.BytesIO(decoded_string))
img.show()
This is giving me an error:
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>
Upvotes: 1
Views: 3390
Reputation: 1123
The correct way of encoding and subsequently decoding an image with base64 turns out to be as follows:
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)
Upvotes: 1