I am facing an issue with Base64 Encoder/Decoder I don't understand. I am transfering an image opened by :
image = open(IMAGE_PATH, "rb").read()
payload = {"image": image,
"filename": os.path.basename(IMAGE_PATH),
"extension": file_extension
r = requests.post(KERAS_REST_API_URL, files=payload).json()
once transfered, the image is opened by the REST API by :
image = Image.open(io.BytesIO(image))
image = np.asarray(image)
and then passed to Base64 Encoder => Everything is fine. See below the resul at the Base64 Encoder function
[[29477 29480 29443 ... 29465 29463 29473]
[29473 29469 29440 ... 29481 29460 29441]
[29434 29436 29452 ... 29459 29474 29444]
...
[29455 29437 29440 ... 29439 29433 29481]
[29451 29456 29441 ... 29469 29450 29452]
[29472 29455 29440 ... 29433 29453 29459]]
[INFO] Image Shape : (768, 1024)
[INFO] Channel : 1
[INFO] Image Shape : (768, 1024)
[INFO] Image Shape Encode : (768, 1024)
[INFO] Image Shape Encode/Decode : (786432,)
Instead of transfering an image by "open(IMAGE_PATH, "rb").read()", I would like to transfert a Numpy Array as my image will also be dicom image.
So, I open the image file with the following commands :
image = np.asarray(Image.open(IMAGE_PATH))
and payload becoms :
payload = {"image": json.dumps(image, cls=NumpyArrayEncoder),
"filename": os.path.basename(IMAGE_PATH),
"extension": file_extension
}
requests.post line is unchanged.
In the REST API, the line that reads the image becomes :
image = request.files["image"].read()
image = json.loads(image)
image = np.asarray(image)
and then passed to Base64 Encoder without any modification of the code. I get the following result
[[29477 29480 29443 ... 29465 29463 29473]
[29473 29469 29440 ... 29481 29460 29441]
[29434 29436 29452 ... 29459 29474 29444]
...
[29455 29437 29440 ... 29439 29433 29481]
[29451 29456 29441 ... 29469 29450 29452]
[29472 29455 29440 ... 29433 29453 29459]]
[INFO] Image Shape : (768, 1024)
[INFO] Channel : 1
[INFO] Image Shape : (768, 1024)
[INFO] Image Shape Encode : (768, 1024)
[INFO] Image Shape Encode/Decode : (1572864,)
Finally, the issue I have is when I decode the data, the shape doesn't match anymore with the expected shape (2 times higher).
Do you have any hint to solve this issue ?
Thank you
def base64_encode_image(a):
# base64 encode the input NumPy array
print("[INFO] Image Shape Encode : " + str(a.shape))
a = base64.b64encode(a).decode("utf-8")
a = bytes(a, encoding="utf-8")
a = np.frombuffer(base64.decodebytes(a), dtype='int32')
print("[INFO] Image Shape Encode/Decode : " + str(a.shape))
return base64.b64encode(a).decode("utf-8")
def base64_decode_image(a, dtype, shape):
if sys.version_info.major == 3:
print("[INFO] Python 3")
a = bytes(a, encoding="utf-8")
# convert the string to a NumPy array using the supplied data
# type and target shape
a = np.frombuffer(base64.decodestring(a), dtype=dtype)
print("[INFO] Image Shape Decode : " + str(a.shape))
a = a.reshape(shape)
# return the decoded image
return a