Is there a way to render the contents of a particular Axes object to an image, as a Numpy array? I know you can do this with the entire figure, but I want to get the image of a particular Axes.
The Axes I'm trying to render contains an image (drawn with imshow), with some lines plotted on top. Ideally, the rendered ndarray would contain just these elements, and no tick marks, borders, etc.
Update:
I forgot to mention that I'm looking for a solution that doesn't require saving an image file.
I've written the following example that almost achieves this, except it doesn't preserve image resolution. Any hints as to what I may be doing wrong would be greatly appreciated:
import matplotlib.pylab as plt
import numpy as np
def main():
"""Test for extracting pixel data from an Axes.
This creates an image I, imshow()'s it to one Axes, then copies the pixel
data out of that Axes to a numpy array I_copy, and imshow()'s the I_copy to
another Axes.
Problem: The two Axes *look* identical, but I does not equal I_copy.
"""
fig, axes_pair = plt.subplots(1, 2)
reds, greens = np.meshgrid(np.arange(0, 255), np.arange(0, 122))
blues = np.zeros_like(reds)
image = np.concatenate([x[..., np.newaxis] for x in (reds, greens, blues)],
axis=2)
image = np.asarray(image, dtype=np.uint8)
axes_pair[0].imshow(image)
fig.canvas.draw()
trans = axes_pair[0].figure.dpi_scale_trans.inverted()
bbox = axes_pair[0].bbox.transformed(trans)
bbox_contents = fig.canvas.copy_from_bbox(axes_pair[0].bbox)
left, bottom, right, top = bbox_contents.get_extents()
image_copy = np.fromstring(bbox_contents.to_string(),
dtype=np.uint8,
sep="")
image_copy = image_copy.reshape([top - bottom, right - left, 4])
image_copy = image_copy[..., :3] # chop off alpha channel
axes_pair[1].imshow(image_copy)
print("Are the images perfectly equal? {}".format(np.all(image == image_copy)))
plt.show()
if __name__ == '__main__':
main()