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!

2

1 Answer 1

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)
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.