12
import numpy as np
import sys
import matplotlib as mpl
import matplotlib.pyplot as plt

i use the following code to save an image

fig, ax = plt.subplots(frameon=False)
ax.axis                 ('off')
ax.imshow               (array[:,:,0,0,0])
fig.savefig             ("file.png", bbox_inches='tight')

However, what I get is enter image description here and this obviously still has a white border. How do I get rid of it?


The array.shape is: (256, 256, 1, 1, 3)

refle
  • 587
  • 3
  • 6
  • 19

2 Answers2

18

Look at my example it may help you:

import numpy as np
import matplotlib.pyplot as plt

def save_image(data, filename):
    sizes = np.shape(data)     
    fig = plt.figure()
    fig.set_size_inches(1. * sizes[0] / sizes[1], 1, forward = False)
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)
    ax.imshow(data)
    plt.savefig(filename, dpi = sizes[0], cmap='hot') 
    plt.close()

data = np.random.randint(0, 100, (256, 256))
save_image(data, '1.png')

enter image description here

Serenity
  • 35,289
  • 20
  • 120
  • 115
5

Little modification to above answer:

def save_image(data, filename):
    fig = plt.figure(figsize=(1, 1))
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)
    ax.imshow(data, cmap="gray")
    fig.savefig(filename, dpi=data.shape[0]) 
    plt.close(fig)
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
refle
  • 587
  • 3
  • 6
  • 19