1

I know some some people have asked this problem before, but the solutions they provided seems do not work to mine. I just give the links below and maybe they are helpful for you.

Matplotlib plots: removing axis, legends and white spaces

How to set the margins for a matplotlib figure?

As described in the problem title, I use following code to handle this problem.

plt.imshow(img)
plt.axis('off')
plt.savefig('seg_missi5.png', bbox_inches='tight')
plt.show()

And I want the saved image with no white spaces and the same size with the original one.

I have tried using print img.shape to see the size of img, it shows (342, 548, 3), which is the same as the original one, but the saved image, it don't. It's size if 438 x 675, which is bigger and has white spaces.

Community
  • 1
  • 1
ct.Liu
  • 139
  • 2
  • 9

2 Answers2

2

Arguably, matplotlib might not be the best tool to achieve this (although it's certainly possible). I propose the Python Image Library as a substitute. Using this library, you can save your image like this:

from PIL import Image

im = Image.fromarray(np.uint8(img))
im.save('outfile.png', "PNG")
David Zwicker
  • 23,581
  • 6
  • 62
  • 77
1

You can try using pad_inches=0

plt.savefig('seg_missi5.png', bbox_inches='tight', pad_inches=0) 

Default size is 0.1. You can get more information from http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig

kimal
  • 682
  • 6
  • 5