Search code examples
pythonimage-processingpython-imaging-librarytiffsubtraction

Subtract 16 bit tiff image in python


I have two 16 bit tiff image, of which one is a background and I have to remove it from all the image. I use the following code, however I get the error saying

return image1._new(image1.im.chop_difference(image2.im))
ValueError: image has wrong mode

from PIL import Image, ImageChops
    im1 = Image.open("main.tif")
    im2 = Image.open("background.tif")
    
    diff = ImageChops.difference(im2, im1)
    diff.show()

when I check the mode using print(im1.mode) I get

I,16

I do not understand this error. Also, I don't know if Pillow is able to subtract 16 bit tiff images or not. I need help to resolve this error and get a subtracted image.

The two images are main: main image

background image: background


Solution

  • I think I would do it like this:

    #!/usr/bin/env python3
    
    from PIL import Image
    import numpy as np
    
    # Open both images and make into Numpy arrays of signed 32-bit integers
    main = np.array(Image.open('main.tif')).astype('int32')
    back = np.array(Image.open('background.tif')).astype('int32')
    
    # Calculate difference with saturation
    diff = np.clip(main - back, 0, main.max())
    
    # Revert to PIL Image and save
    Image.fromarray(diff.astype(np.uint16)).save('result.tif')
    

    If you stretch the contrast, you get:

    enter image description here