Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Save MatPlotLib Figure as PNG Byte Array With Decimal Formatting

I have some data I’m visualizing with a MatPlotLib figure. I want to be able to convert the figure into a byte array that is formatted with PNG decimal values.
https://www.w3.org/TR/PNG-Structure.html

fig = plt.figure(figsize=(16,16))
ax = fig.add_subplot(projection='3d')
ax.voxels(space, facecolors = rgb_input)
plt.axis('off')
fig.patch.set_alpha(0.25)
ax.patch.set_alpha(0.25)

I know how to save it as a PNG and convert that into a byte array, but I want to be able to make the byte array directly.

I’ve tried using this to get the byte array directly, but it doesn’t return PNG decimal values:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

buf = io.BytesIO()
plt.savefig(buf, format = 'png')
buf.seek(0)
data = buf.read()

EDIT: Upon further research, I’ve found that the data value is formatted as an ASCII byte array. Is there a way to convert it into a decimal byte array?

>Solution :

PNG images are binary files usually represented in ASCII or hexadecimal, to convert the byte array into a decimal representation, you can simply do that with Python’s built-in functions.

import io
import matplotlib.pyplot as plt
import numpy as np

space = np.random.rand(5,5,5) > 0.5
rgb_input = np.random.rand(5,5,5,3)

fig = plt.figure(figsize=(16,16))
ax = fig.add_subplot(projection='3d')
ax.voxels(space, facecolors = rgb_input)
plt.axis('off')
fig.patch.set_alpha(0.25)
ax.patch.set_alpha(0.25)

buf = io.BytesIO()
plt.savefig(buf, format = 'png')
buf.seek(0)
data = buf.read()

decimal_values = [byte for byte in data]
print(decimal_values)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading