I need to merge the RGB bands of three TIFF images. I'm trying to use a PIL library (Python Imaging Library), but this execution error happens:
Traceback (most recent call last): File "merge.py", line 7, in Imagem = Image.merge("RGB", (red, green, blue)) File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2367, in merge raise ValueError("mode mismatch") ValueError: mode mismatch
The output must to be a new TIFF image with three bands. This is my code:
import Image
red = Image.open("red.TIF")
blue = Image.open("blue.TIF")
green = Image.open("green.TIF")
out = Image.merge("RGB", (red, green, blue))
out.save("img-out.TIF")
Can anyone help me?
2 Answers 2
You need to convert each channel into a luminosity channel. So instead of this:
red = Image.open("red.TIF")
you need to do this:
red = Image.open("red.TIF").convert('L')
rinse and repeat for G and B and you're done!
You're getting "ValueError: mode mismatch" because your input TIF images probably contain floating point data. ie each pixel represents a 16bit or 32bit float value as opposed to an 8bit integer representing values between 0-255.
AFAIK PIL only supports merging 8bit/channel images. So as others have said using a convert will "fix" your error but what you're actually doing is down-sampling your data from 16/32bit to 8bit.
So it depends on what you want to do with the merged image, if it's just for visualization etc then convert should be fine. If you're using the output image to compute values etc then I'd advise against this and work out a better way using separate images.
red.getbands()
etc to see if the result has length 1.