pythonnumpyphotoshoppsd

Convert multi-channel numpy array to photoshop PSD file


I have a numpy array with 3 RGB channels and two alpha channels. (I am using python)

I want to convert it to a Photoshop .psd file, so I can later apply transformations in photoshop on the annotated alpha layers.

I guess it a very simple task but I haven't find any way to do it from the packages I found by googling it.

I guess it should be something in the lines of the following:

>> im.shape
(.., .., 4)

psd = PSD()
psd.add_layers_from_numpy(im, names=["R", "G", "B", "alpha-1", "alpha-2")
with open(of, 'wb') as f:
    psd.write(f)

If you know how to do this, please let me know. Thanks in advance!


Solution

  • I opened your PSD file in Photoshop and saved it as a TIFF. I then checked with tiffinfo and determined that your file is saved as RGB with 3 layers of "Extra samples":

    tiffinfo MULTIPLE_ALPHA.tif
    
    TIFF Directory at offset 0x8 (8)
      Subfile Type: (0 = 0x0)
      Image Width: 1000 Image Length: 1430
      Resolution: 72, 72 pixels/inch
      Bits/Sample: 8
      Compression Scheme: None
      Photometric Interpretation: RGB color                      <--- HERE
      Extra Samples: 3<unspecified, unspecified, unspecified>    <--- HERE
      Orientation: row 0 top, col 0 lhs
      Samples/Pixel: 6
      Rows/Strip: 1430
      Planar Configuration: single image plane
      Software: Adobe Photoshop 21.2 (Macintosh)
      DateTime: 2020:09:08 19:34:38
    

    You can load that into Python with:

    import tifffile
    import numpy as np
    
    # Load TIFF saved by Photoshop
    im = tifffile.imread('MULTIPLE_ALPHA.tif')
    
    # Check shape
    print(im.shape)           # prints (1430, 1000, 6)
    
    # Save with 'tifffile'
    tifffile.imwrite('saved.tif', im, photometric='RGB')
    

    And now check that Photoshop looks at and treats the tifffile image the same as your original:

    enter image description here

    You may want to experiment with the compress parameter. I noticed your file comes out as 8.5MB uncompressed, but as 2.4MB of lossless Zip-compressed data if I use:

    tifffile.imwrite('saved.tif', im, photometric='RGB', compress=1)
    

    Note that reading/writing with compression requires you to install imagecodecs:

    pip install imagecodecs
    

    Note that I am not suggesting it is impossible with a PSD-writer package, I am just saying I believe you can get what you want with a TIFF.

    Keywords: Image processing, Photoshop, PSD, TIFF, save multi-channel, multi-layer, multi-image, multiple alpha, tifffile, Python