1

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>
Community
  • 1
  • 1
valentin
  • 1,103
  • 2
  • 16
  • 36
  • Did you see this solution? https://stackoverflow.com/questions/33311153/python-extracting-and-saving-video-frames – ghovat Mar 15 '18 at 15:39
  • @ghovat the solution you are referring me to does not appear to be related. I am trying to figure out how to encode and decode an image which is different than trying to save an image to file. – valentin Mar 15 '18 at 15:47
  • https://stackoverflow.com/a/33522724/5008845 – Miki Mar 16 '18 at 00:53
  • @Miki thank you for pointing this out, very helpful! – valentin Mar 16 '18 at 10:33

1 Answers1

1

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)
valentin
  • 1,103
  • 2
  • 16
  • 36