5

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?

4
  • Are these GeoTiffs or just regular tif images? If the latter you might be better off asking this question on StackOverflow as it has no clear GIS relation. – Kersten Feb 12 '16 at 13:32
  • 2
    Are you sure that the input images are single band images? Test with red.getbands() etc to see if the result has length 1. – Detlev Feb 12 '16 at 13:33
  • 2
    have you tried github.com/mapbox/rasterio instead? – bugmenot123 Feb 12 '16 at 14:00
  • 1
    Does it need to be in Python, or do GDAL tools work? gdal_merge.py -separate -o RGB.tif -co PHOTOMETRIC=RGB red.tif green.tif blue.tif – Alec Bennett Apr 9 '17 at 5:04
4

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!

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.