1

I'm trying to find a way to convert a matplotlib figure to a numpy array without any white spaces or borders.

I found out that if I use the code below, I'll get something pretty close, but the numpy array "data" would still have some white borders. The white border (white changes as I scale the window) is saved as part of the numpy array but I only want the content.

Is there any way to get rid of this white area?

white borders

fig = plt.figure(frameon=False)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
ax.set_ylim(height, 0)
ax.set_xlim(0, width)
ax.axis('off')
fig.add_axes(ax)

ax.imshow(myimage) # Plus lots of other things

plt.show() # fig.canvas.draw() also works the same
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
plt.close()

A similar question has been asked here previously but the author's own work-around with PIL doesn't fit what I need.

1
  • You could try using the figsize argument of plt.figure() to specify a figure size that has the same aspect ratio as your image. But this seems like an indirect method to accomplish what you want, and I don't know if it will perfectly eliminate the margins. Commented May 13, 2018 at 2:27

1 Answer 1

2

I guess subplots_adjust is the key here. Seems to work with a toy example but it would be great it you could provide minimal working code to see if it works in your use case.

import numpy as np
import matplotlib as mpl
# mpl.use('Agg')
import matplotlib.pyplot as plt

img = np.ones((100, 200))
img[25:75, 50:150] = 0

fig = plt.figure()
ax = fig.gca()

ax.imshow(img)
ax.axis('tight')

plt.subplots_adjust(0,0,1,1,0,0)

plt.show()

data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
w, h = fig.canvas.get_width_height()
data = data.reshape((h, w, 3))

plt.close()
Sign up to request clarification or add additional context in comments.

1 Comment

plt.subplots_adjust(0,0,1,1,0,0) This is what one needs to do

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.