Skip to content

[Solved][Python] How to Remove with borders when drawing in matplotlib package

matplotlib is a famous python plot package and most of user used it to process the image.

But when I using matploblib package to plot a image, I do not like the white border of my plot image.

For example, I want to show test.png picture.

test.png


I use matplotlib to read it and plot.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

image = mpimg.imread('test.png')
plt.imshow(image)
plt.show()



Output:

There are more white borders on the top, bottom, left and right of the picture. To be honest, this will affect the display effect.


How to Remove White Border?

Here is a method found on stackoverflow, I think the effect is pretty good.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

image = mpimg.imread('test.png')
plt.axis('off')

fig = plt.imshow(image, interpolation='nearest')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)

plt.savefig('test_output.png',
            bbox_inches='tight',
            pad_inches=0,
            format='png',
            dpi=300)



Output:

But this method is to save the picture. When I use plt.show(), the picture still has a white border.

For example:

image = Image.open('test_output.png')
image.show()



References

Leave a ReplyCancel reply

Exit mobile version