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?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Feb 12, 2016 at 13:07
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. Commented Feb 12, 2016 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. Commented Feb 12, 2016 at 13:33
  • 2
    have you tried github.com/mapbox/rasterio instead? Commented Feb 12, 2016 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 Commented Apr 9, 2017 at 5:04

2 Answers 2

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!

answered Mar 26, 2016 at 22:57
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.

answered Feb 22, 2021 at 21:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.