Search code examples
python-3.xpython-imaging-librarylayergimp

Python - Multiple images to multilayered .xcf


I have three PIL images of the same size in RAM (no disk here). They represent different frequencies (details, shadow, mask).

Is it possible to overlay these images into a .xcf file to further process them by hand in gimp? If so, can the opacity of the layers be controlled before saving the image?

I'm ideally looking for a python solution.


Solution

  • Not certain what GIMP expects, but this might get you started as a multi-layer TIFF with varying opacities:

    #!/usr/bin/env python3
    
    import numpy as np
    from PIL import Image
    
    w, h = 400, 400
    
    # Our layers to write to output file
    layers = []
    
    # Make layer 0 - 400x400 RGBA with red square, A=64
    im = np.full((w,h,4), [0,0,0,64], np.uint8)
    im[10:110, 10:110, :3] = [255,0,0]
    layers.append(Image.fromarray(im))
    
    # Make layer 1 - 400x400 RGBA with green square, A=128
    im = np.full((w,h,4), [0,0,0,128], np.uint8)
    im[20:120, 20:120, :3] = [0,255,0]
    layers.append(Image.fromarray(im))
    
    # Make layer 2 - 400x400 RGBA with blue square, A=192
    im = np.full((w,h,4), [0,0,0,192], np.uint8)
    im[30:130, 30:130, :3] = [0,0,255]
    layers.append(Image.fromarray(im))
    
    # Save as multi-layer TIFF with PIL
    layers[0].save('result.tif', save_all=True, append_images=layers[1:], compression='tiff_lzw')
    

    The Preview app on macOS displays it like this - hopefully you can see the red at least is more transparent, or less vibrant:

    enter image description here

    tiffinfo perceives it like this:

    TIFF Directory at offset 0x9740 (260c)
      Image Width: 400 Image Length: 400
      Bits/Sample: 8
      Compression Scheme: LZW
      Photometric Interpretation: RGB color
      Extra Samples: 1<unassoc-alpha>
      Samples/Pixel: 4
      Rows/Strip: 40
      Planar Configuration: single image plane
    TIFF Directory at offset 0x20096 (4e80)
      Image Width: 400 Image Length: 400
      Bits/Sample: 8
      Compression Scheme: LZW
      Photometric Interpretation: RGB color
      Extra Samples: 1<unassoc-alpha>
      Samples/Pixel: 4
      Rows/Strip: 40
      Planar Configuration: single image plane
    TIFF Directory at offset 0x30506 (772a)
      Image Width: 400 Image Length: 400
      Bits/Sample: 8
      Compression Scheme: LZW
      Photometric Interpretation: RGB color
      Extra Samples: 1<unassoc-alpha>
      Samples/Pixel: 4
      Rows/Strip: 40
      Planar Configuration: single image plane