{ "metadata": { "signature": "sha256:6b310bcb732d18175a527f30fe4fda8cef22b010afeb495478ec72735cad2d24" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Load image\n", "\n", "Image processing often works on gray scale images that were stored as PNG files. How do we import / export that\n", " file into {{{python}}}?\n", "\n", " * Here is a recipy to do this with Matplotlib using the {{{imread}}} function (your image is called {{{lena.png}}}). \n", "\n", "
\n",
"from pylab import imread, imshow, gray, mean\n",
"a = imread('lena.png')\n",
" # generates a RGB image, so do\n",
"aa=mean(a,2) # to get a 2-D array\n",
"imshow(aa)\n",
"gray()\n",
"
\n",
"\n",
"This permits to do some processing for further exporting such as for\n",
"[:Cookbook/Matplotlib/converting_a_matrix_to_a_raster_image: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.\n",
"\n",
"\n",
"* to write an image, do \n",
"\n",
"import Image\n",
"mode = 'L'\n",
"size= (256, 256)\n",
"imNew=Image.new(mode , size)\n",
"mat = numpy.random.uniform(size = size)\n",
"data = numpy.ravel(mat)\n",
"data = numpy.floor(data * 256)\n",
"\n",
"imNew.putdata(data)\n",
"imNew.save(\"rand.png\")\n",
"
\n",
"\n",
" * this kind of functions live also under {{{scipy.misc}}}, see for instance {{{scipy.misc.imsave}}} to create a color image:\n",
" \n",
"from scipy.misc import imsave\n",
"import numpy\n",
"a = numpy.zeros((4,4,3))\n",
"a[0,0,:] = [128, 0 , 255]\n",
"imsave('graybackground_with_a_greyish_blue_square_on_top.png',a)\n",
"
\n",
"\n",
"\n",
" * to define the range, use:\n",
"\n",
"from scipy.misc import toimage\n",
"import numpy\n",
"a = numpy.random.rand(25,50) #between 0. and 1.\n",
"toimage(a, cmin=0., cmax=2.).save('low_contrast_snow.png')\n",
"
\n",
"(adapted from http://telin.ugent.be/~slippens/drupal/scipy_unscaledimsave )\n",
"\n",
"\n",
" * there was another (more direct) method suggested by http://jehiah.cz/archive/creating-images-with-numpy"
]
}
],
"metadata": {}
}
]
}