6

For example, I plot a figure using matplotlib as follows:

plt.figure(figsize=(10,10))
plt.imshow(output_fig, zorder=0,cmap="gray")
plt.scatter(x,y,color='k')

if I use:

plt.savefig(figname,fotmat=figtype)

I will save it as a figure file. However, I want so save it to a matrix, or numpy array, such that each element saves the scale value of each pixel of the figure. How can I do this? I find solutions saving the RGB values. But I hope to save a greyscale figure. Thank you all for helping me!

pfc
  • 1,831
  • 4
  • 27
  • 50
  • Possible duplicate of [Is there a way to convert pyplot.imshow() object to numpy array?](http://stackoverflow.com/questions/14869321/is-there-a-way-to-convert-pyplot-imshow-object-to-numpy-array) – umutto Apr 12 '17 at 07:58
  • @umutto Not exactly the same. I'm looking forward to a solution for greyscale figure, not RGB figure. Thank you anyway. – pfc Apr 12 '17 at 08:21

1 Answers1

8

Once you have a ploted data (self contained example bellow):

import numpy as np
import matplotlib.pyplot as plt
from skimage import data, color

img = data.camera()

x = np.random.rand(100) * img.shape[1]
y = np.random.rand(100) * img.shape[0]

fig = plt.figure(figsize=(10,10))
plt.imshow(img,cmap="gray")
plt.scatter(x, y, color='k')
plt.ylim([img.shape[0], 0])
plt.xlim([0, img.shape[1]])

The underlying data can be recovered as array by using fig.canvas (the matplotlib's canvas). First trigger its drawing:

fig.canvas.draw()

Get the data as array:

width, height = fig.get_size_inches() * fig.get_dpi()
mplimage = np.fromstring(fig.canvas.tostring_rgb(), dtype='uint8').reshape(height, width, 3)

If you want your array to be the same shape as the original image you will have to play with figsize and dpi properties of plt.figure().

Last, matplotlib returns an RGB image, if you want it grayscale:

gray_image = color.rgb2gray(mplimage)
Imanol Luengo
  • 15,366
  • 2
  • 49
  • 67