jamesbowman / openexrpython

OpenEXR bindings for Python
Other
95 stars 35 forks source link

How to add an alpha channel to .exr? #49

Closed JohnG0024 closed 2 years ago

JohnG0024 commented 2 years ago

Hello, I'm trying to add an alpha channel to .exr but can't get it to work. Would you be able to help with it?

import OpenEXR
import Imath
import array
import os
import numpy as np

def write_exr_alpha(dir,output_dir):
    z_file = OpenEXR.InputFile(dir)
    FLOAT = Imath.PixelType(Imath.PixelType.FLOAT)
    (z,_,_) = [array.array('f', z_file.channel(Chan, FLOAT)).tolist() for Chan in ("R", "G", "B") ]
    dw = z_file.header()['dataWindow']
    sz = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)
    # Write the three color channels to the output file
    os.makedirs(os.path.dirname(output_dir), exist_ok=True)
    #get alpha values
    As = np.ones(np.array(z).shape)
    pos = np.where(np.array(z) > 100)[0]
    As[pos]=0
    zs=array.array('f',z).tobytes()
    # (zs, zs, zs, Ass) = [ array.array('f', Chan).tobytes() for Chan in (z, z, z, As) ]
    out = OpenEXR.OutputFile(output_dir, OpenEXR.Header(sz[0], sz[1]))
    # write to .exr with alpha channel
    out.writePixels({'R' : zs, 'G' : zs, 'B' : zs ,'A': As}) 
jamesbowman commented 2 years ago

This is the new OpenEXR python project - please raise this issue there

https://github.com/sanguinariojoe/pip-openexr