Hopefully, this should get you started. I think that what you tried, by sending the unadorned bytes from the Numpy array probably won't work because the receiver will not know the width, height and number of channels in the image, so I used pickle
to store that.
#!/usr/bin/env python3
import cv2
import numpy as np
import base64
import json
import pickle
from PIL import Image
def im2json(im):
"""Convert a Numpy array to JSON string"""
imdata = pickle.dumps(im)
jstr = json.dumps({"image": base64.b64encode(imdata).decode('ascii')})
return jstr
def json2im(jstr):
"""Convert a JSON string back to a Numpy array"""
load = json.loads(jstr)
imdata = base64.b64decode(load['image'])
im = pickle.loads(imdata)
return im
# Create solid red image
red = np.full((480, 640, 3), [0, 0, 255], dtype=np.uint8)
# Make image into JSON string
jstr = im2json(red)
# Extract image from JSON string, and convert from OpenCV to PIL reversing BGR to RGB on the way
OpenCVim = json2im(jstr)
PILimage = Image.fromarray(OpenCVim[...,::-1])
PILimage.show()
As you haven't answered my question in the comments about why you want do things this way, it may not be optimal - sending uncompressed, base64-encoded images across a network (presumably) is not very efficient. You might consider JPEG, or PNG encoded data to save network bandwidth, for example.
You could also use cPickle instead.
Note that some folks disapprove of pickle
and also the method above uses a lot of network bandwidth. An alternative might be to JPEG compress the image before sending and decompress on the receiving end straight into a PIL Image. Note that this is lossy.
Or change the .JPG
extension in the code to .PNG
which is loss-less but may be slower and will not work for images with floating point data or 16-bit data (although the latter could be accommodated).
You could also look at TIFF, but again, it depends on the nature of your data, the network bandwidth, the flexibility you need, your CPU's encoding/decoding performance...
#!/usr/bin/env python3
import cv2
import numpy as np
import base64
import json
from io import BytesIO
from PIL import Image
def im2json(im):
_, imdata = cv2.imencode('.JPG',im)
jstr = json.dumps({"image": base64.b64encode(imdata).decode('ascii')})
return jstr
def json2im(jstr):
load = json.loads(jstr)
imdata = base64.b64decode(load['image'])
im = Image.open(BytesIO(imdata))
return im
# Create solid red image
red = np.full((480, 640, 3), [0, 0, 255], dtype=np.uint8)
# Make image into JSON string
jstr = im2json(red)
# Extract image from JSON string into PIL Image
PILimage = json2im(jstr)
PILimage.show()