Sunday, January 25, 2009

Python: an image to an array and an array to an image

Converting 8-bit gray-scale level images to numpy array, and generating a 8-bit gray-scale level image from array.
import Image, numpy, scipy
def image2array(im):
newArr = numpy.fromstring(im.tostring(),numpy.uint8)
newArr = numpy.reshape(newArr,im.size)
return newArr
def array2image(a):
#a=a/a.max()*255.0 #optional.
im=Image.Image()
im=Image.fromarray(numpy.uint8(a))
return im
def example():
Img=Image.open('some.tiff')
arr=image2array(Img)
#
# some operations on array
#
Img2=array2image(arr)
Img2.save('some2.png')
view raw example.py hosted with ❤ by GitHub