Scipy is a (set of) open source Python modules for scientific/mathematical/engineering stuff. I (try to) use it instead of Matlab or its open source clone Octave because I don't like Matlab's scripting language and prefer Python's programming features.

If you want to store a 2D array (aka matrix) to an image file, the default behaviour of Scipy's imsave() function is to rescale the matrix to a 0-255 range (like Matlab's imagesc() function). For example:

>>> import scipy
>>> a = 200 * scipy.ones((8,8))
>>> a[0:4,0:4] = 80
>>> print a
[[ 80  80  80  80 200 200 200 200]
 [ 80  80  80  80 200 200 200 200]
 [ 80  80  80  80 200 200 200 200]
 [ 80  80  80  80 200 200 200 200]
 [200 200 200 200 200 200 200 200]
 [200 200 200 200 200 200 200 200]
 [200 200 200 200 200 200 200 200]
 [200 200 200 200 200 200 200 200]]
>>> scipy.imsave("tmp.png",a)

An enlarged version of the image tmp.png we just generated would look like

the image values are rescaled to the 0-255 range

As you can see the dynamic range of the pixel values is rescaled to 0-255 before saving: the values 80 become totally black (value 0) and the values 200 become totally white (value 255). Sometimes this is what you want, sometimes it is not.

To prevent the rescaling of the dynamic range (or impose your own rescaling), you can use the following workaround:

>>> # long version:
>>> im = scipy.toimage(a, cmin=0, cmax=255)
>>> im.save("tmp.png")
>>> # in short:
>>> scipy.toimage(a, cmin=0, cmax=255).save("tmp.png")

In the first step we transform the array a to a PIL image, while imposing our own value range with the arguments cmin and cmax. The second step is just saving the PIL image to a file. The result is:

the original pixel values

We are not doing anything special here. It's just based on Scipy's implementation of imsave() (in the file pilutils.py):

def imsave(name, arr):
    """Save an array to an image file.
    """
    im = toimage(arr)
    im.save(name)
    return