Sunday, January 25, 2009

Python: Python Imaging Library - 16 bit images

The problem described in the previews post about 16-bit images in python can be overcome by converting image into numpy array, operating in numpy array, and finally converting array into image and saving it:

def flip_horizontally2(inDir,inFile,outFile=None):
''' Open 16-bit or 8-bit image, flop it horizontally,
and save it
.'''
imgpath=inDir+inFile
im = Image.open(imgpath)
print im.mode,im.size[1], im.size[0]

#convert image into array according to im.mode
if im.mode in ("L",):
a = fromstring(im.tostring(), uint8)
elif im.mode in ("I;16",):
a = fromstring(im.tostring(), uint16)

a.shape = im.size[1], im.size[0]
a=fliplr(a) #flip horizontally

#convert array into image according to a.dtype
if a.dtype == uint8: mode = "L"
elif a.dtype == uint16: mode = "I;16"
else:
raise ValueError, "unsupported image mode"
out=Image.fromstring(mode, (a.shape[1],
a.shape[0]), a.tostring())

#save image
if outFile is None: outFile=inFile
base=os.path.splitext(outFile)[0]
out.save(inDir+base+'_flopped2.tiff')


Using this function instead of the one used before produces correct results.

No comments:

Post a Comment