Differences between revisions 10 and 11

Deletions are marked like this. Additions are marked like this.
Line 32: Line 32:
import numpy
Line 36: Line 37:

 * to define the range, use:{{{#!python
from scipy.misc import toimage
import numpy
a = numpy.random.rand(25,50) #between 0. and 1.
toimage(a, cmin=0., cmax=2.).save('low_contrast_snow.png')

}}} (adapted from http://telin.ugent.be/~slippens/drupal/scipy_unscaledimsave )

Image processing often works on gray scale images that were stored as PNG files. How do we import / export that file into python?

  • Here is a recipy to do this with Matplotlib using the imread function (your image is called lena.png).

       1 from pylab import imread, imshow, gray, mean
       2 a = imread('lena.png')
       3 #generates a RGB image, so do
       4 aa=mean(a,2) # to get a 2-D array
       5 imshow(aa)
       6 gray()
    

This permits to do some processing for further exporting such as for converting a matrix to a raster image. In the newest version of pylab (check that your pylab.matplotlib.__version__ is superior to '0.98.0') you get directly a 2D numpy array if the image is grayscale.

  • to write an image, do

       1 import Image
       2 mode = 'L'
       3 size= (256, 256)
       4 imNew=Image.new(mode , size)
       5 mat = numpy.random.uniform(size = size)
       6 data = numpy.ravel(mat)
       7 data = numpy.floor(data * 256)
       8 
       9 imNew.putdata(data)
      10 imNew.save("rand.png")
    
  • this kind of functions live also under scipy.misc, see for instance scipy.misc.imsave to create a color image:

       1 from scipy.misc import imsave
       2 import numpy
       3 a = numpy.zeros((4,4,3))
       4 a[0,0,:] = [128, 0 , 255]
       5 imsave('graybackground_with_a_greyish_blue_square_on_top.png',a)
    
  • to define the range, use:

       1 from scipy.misc import toimage
       2 import numpy
       3 a = numpy.random.rand(25,50) #between 0. and 1.
       4 toimage(a, cmin=0., cmax=2.).save('low_contrast_snow.png')
    

    (adapted from http://telin.ugent.be/~slippens/drupal/scipy_unscaledimsave )

  • there was another (more direct) method suggested by http://jehiah.cz/archive/creating-images-with-numpy


CategoryCookbookMatplotlib

Cookbook/Matplotlib/LoadImage (last edited 2008-12-08 10:12:28 by LaurentPerrinet)