Sunday, December 02, 2007

Python Imaging Library - not working with 16 bit images

Python Imaging Library works well with 8-bit images, however it has problem with 16-bit images. As an example I wrote a script that flops tiff images horizontally. One image is 8-bit and the second image is 16-bit:



#!/usr/bin/env python
'''
Convert tif images from Ludvig 2008.

This scripts take all tifs in input dir, and changes
tif files into tiff. Additionali it takes
right knee x-rays and flips them horizontally,
to have all x-ray in the same format.

'''
#from myUtil import *
import re
import os
import Image
import Tkinter, tkFileDialog, os.path
from scipy import *

def flip_horizontally(inDir,inFile,outFile=None):
imgpath=inDir+inFile
im = Image.open(imgpath)
out = im.transpose(Image.FLIP_LEFT_RIGHT)
if outFile is None: outFile=inFile
base=os.path.splitext(outFile)[0]
out.save(inDir+base+'_flopped.tiff')

def main():
inDir=myGetDir('./')
print inDir
files=os.listdir(inDir)
#change_file_ext(inDir,r'\.tif+$','.tiff')
for f in files:
if f.find('tiff')==-1: continue
if f.find('test')==-1: continue
print f
flip_horizontally(inDir,f,f)

def myGetDir(indir='./',putTitle='Select dir'):
"""Get one dir name"""
root = Tkinter.Tk()
root.withdraw()
dirr=tkFileDialog.askdirectory(initialdir=indir,
title=putTitle)
if len(dirr)==0: exit(1)
return dirr+'/'

if __name__ == '__main__':
main()

The result of the above code is:




It is clearly seen that flopping 16-bit image gives wrong results.

No comments:

Post a Comment