I'm trying to produce an image from an array using imshow
, and export it to file without having any whitespace added.
In the case in which the data has equal width and height I managed to achieve this by following this answer:
import numpy as np
import matplotlib.pyplot as plt
def borderless_imshow_save(data, outputname, size=(1, 1), dpi=80):
fig = plt.figure()
fig.set_size_inches(size)
ax = plt.Axes(fig, [0, 0, 1, 1])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(data);
plt.savefig(outputname, dpi=dpi)
data = np.random.randn(40, 40)
borderless_imshow_save(data, 'test.png', dpi=100)
This works perfectly.
However, I actually need to do this for data that is rectangular, that is, something like np.random.randn(40, 100)
.
In this case, the code above does not work, as again whitespace is produced in the final image.
I tried playing with the size
parameter and the arguments of plt.Axes
but without success.
What's the best way to achieve this?
Note that imsave
actually works here with something like
plt.imsave('test.png', np.random.randn(40, 100))
the problem with this is that with imsave
I do not have access to same amount of options I have with imshow
.