0

I am using matplotlib to generate matrices I can train on. I need to get to the raw figure data. Saving and reading the .png works fine, but my code runs 10x longer. Another stack overflow asked a similar question and the solution was to grab the canvas, but that related logic generated a numpy error. Here is my mwe.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import IdentityTransform


px = 1/plt.rcParams['figure.dpi']  # pixel in inches
fig, ax = plt.subplots(figsize=(384*px, 128*px))
i = 756
plt.text(70, 95, "value {:04d}".format(i), color="black", fontsize=30, transform=IdentityTransform())
plt.axis('off')
plt.savefig("xrtv.png")     # I dont want to do this ...
rtv = plt.imread("xrtv.png")  # or this, but I want access to what imread returns.

gray = lambda rgb: np.dot(rgb[..., :3], [0.299, 0.587, 0.114])
gray = gray(rtv)
1
  • This answer provide a solution using fig.canvas.tostring_rgb(). In addition you could use plt.ioff() so nothing will be plotted until plt.show() has been called which can speed up your code. Commented Feb 6, 2023 at 16:00

1 Answer 1

0

Disabling rendering was a good hint. Consider using a memory buffer to I/O rather than playing with strings. Here is a full example:

import numpy as np
import io
import matplotlib.pyplot as plt
from PIL import Image

# disable rendering and dump to buffer
plt.ioff()
fig,ax = plt.subplots()
ax.plot(np.sin(np.arange(100)))
buf = io.BytesIO()
fig.savefig(buf,format='RGBA')

# plot from buffer 
shape = (int(fig.bbox.bounds[-1]),int(fig.bbox.bounds[-2]),-1)
img_array = np.frombuffer(buf.getvalue(),dtype=np.uint8).reshape(shape)
Image.fromarray(img_array)

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.