Reputation: 11198
I'm sending an image from a grpc client as bytes.
In the client,
import cv2
img = cv2.imread('a.jpg')
img_encoded = cv2.imencode('.jpg', img)[1] # memory buffer, type returns <class 'numpy.ndarray'>
# encode as bytes object, so I can send
img_bytes = bytearray(img_encoded) # type bytes
How can I reverse the process to get the image as a numpy array in the server end?
I can use imdecode but how to reverse the bytearray function? img_bytes.decode()
fails with UnicodeDecodeError.
Upvotes: 1
Views: 3788
Reputation: 708
here it is:
import cv2
import numpy as np
img = cv2.imread('a.jpg')
img_encoded = cv2.imencode('.jpg', img)[1].tobytes() # bytes class
# 'repair' image from byte array
nparr = np.frombuffer(img_encoded, np.byte)
img2 = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
Upvotes: 1