Search code examples
pythonvips

pyvips Image composite not working as expected


When trying to composite images with pyvips 2.1.5:

import pyvips

i1 = pyvips.Image.black(100, 100, bands=4) + (255, 0, 0, 128)
i2 = pyvips.Image.black(10, 10, bands=4) + (0, 255, 0, 128)
i1.composite(i2, 'over').write_to_file('output.png')

It outputs green sq. of size 10x10px instead of expected 100x100px alpha-mixed sq.

output.png

Also compositing of multiple image files (pyvips.Image.new_from_file) seems to work OK, but doing so with one of the generated image above fails due to:

pyvips.error.Error: unable to call composite
composite: images do not have same numbers of bands

even if all images' bands return 4.

Do I use it wrong? Thanks for your help!


Solution

  • Your black() + (1, 2, 3, 4) will make a four band image with interpretation set to multiband. This will be interpreted by composite as a monochrome image with three extra alpha channels (perhaps not the best guess).

    You need to set the interpretation to sRGB. You don't need to set the bands on black to 4, it'll be upbanded automatically by the RHS of the +.

    Try:

    import pyvips
    
    i1 = (pyvips.Image.black(100, 100) + (255, 0, 0, 128)).copy(interpretation="srgb")
    i2 = (pyvips.Image.black(10, 10) + (0, 255, 0, 128)).copy(interpretation="srgb")
    i1.composite(i2, 'over').write_to_file('output.png')
    

    To make:

    result image

    The same trick should fix your problem with compositing black with image files.