Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib produces a black image from an array full of ones [duplicate]

Intro

I am doing some tests with matplotlib.pyplot. When I tried to save artificial images, I encoutered a strange behavior. Here is the very simple function I created to save images :

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

def save_image(array, name):

    array = array*255.
    fig = plt.figure()
    plt.imsave(name, array.astype('uint8'), cmap=matplotlib.cm.gray)
    plt.close(fig)

return 0

The problem

When I try to create an image with an array full of zeros, I get a dark image, as expected :

zeros_array = np.zeros((200,200), dtype='float')
save_image(zeros_array, 'Dark.jpg')

Dark.jpg

However, when I try to create an image with an array full of ones, I still get a dark image :

ones_array = np.ones((200,200), dtype='float')
save_image(ones_array, 'White.jpg')

White.jpg

Interestingly enough, when I create a mixed_array, with squares of different intensities, the regions full of ones now appear as white :

mixed_array = np.ones((200,200), dtype='float')
mixed_array[:100,:100] = 0.25
mixed_array[100:,100:] = 0.75
save_image(mixed_array, 'Mixed.jpg')

Mixed.jpg

Question :

Does anyone know why matplotlib refuses to save a full white image but has no problem with white regions in an image?

I am probably missing something very obvious or fundamental but I cannot see what.

like image 419
Julep Avatar asked Mar 11 '23 17:03

Julep


1 Answers

I think you want to set the vmin and vmax when you call imsave. If you don't, it will be automatically determined from the array. From the docs:

vmin/vmax: [ None | scalar]

vmin and vmax set the color scaling for the image by fixing the values that map to the colormap color limits. If either vmin or vmax is None, that limit is determined from the arr min/max value.

So, try changing your function to:

def save_image(array, name):

    array = array*255.
    fig = plt.figure()
    plt.imsave(name, array.astype('uint8'), cmap=matplotlib.cm.gray, vmin=0, vmax=255)
    plt.close(fig)
like image 100
tmdavison Avatar answered Apr 27 '23 00:04

tmdavison