1

I am plotting figure as:

plt.imshow(image, cmap='gray', interpolation='none')
plt.imshow(masked_contour, cmap='cool', interpolation='none', alpha=0.7)
plt.show()

The figure shows in greyscale with a blue contour inside it.

Now I want to get this figure as a numpy array (also not as a masked array). One way can be, save the plot as an image, then read it from there. Is there any better approach?

Dr.PB
  • 959
  • 1
  • 13
  • 34
  • You could try to check this following [link](https://stackoverflow.com/questions/7821518/matplotlib-save-plot-to-numpy-array). It might help – Soothy Jun 13 '21 at 06:24
  • @soothy Thanks for the comment. The link works, but the problem is that it takes the image's input as a small-windowed image. If I try to make it a full-windowed image as mentioned here: [link](https://stackoverflow.com/a/32428266/4464045). However, it still saves as in small-windowed image. – Dr.PB Jun 13 '21 at 07:27
  • I got it. Thanks. – Dr.PB Jun 13 '21 at 07:30

1 Answers1

1
fig = plt.figure(figsize=(20, 20)) # this is imp for sizing
# plot
plt.imshow(image, cmap='gray', interpolation='none')
plt.imshow(masked_contour, cmap='cool', interpolation='none', alpha=0.7)
# get image as np.array
canvas = plt.gca().figure.canvas
canvas.draw()
data = np.frombuffer(canvas.tostring_rgb(), dtype=np.uint8)
image = data.reshape(canvas.get_width_height()[::-1] + (3,))
# (Optional) show image
plt.imshow(image)
plt.show()
Dr.PB
  • 959
  • 1
  • 13
  • 34