Add alpha channel to an .exr file in python

411 views Asked by At

I'm trying to add an alpha channel to an .exr file(RGB) using OpenEXR python library or OpenCV, couldn't figure out how. Here's where I am.

import OpenEXR,Imath,array,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)
    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()
    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}) 

and OpenCV

import os,cv2
import numpy as np

def write_exr_alpha(dir,output_dir):
    os.makedirs(os.path.dirname(output_dir), exist_ok=True)
    image=cv2.imread(dir,cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)
    normal_b, normal_g, normal_r = cv2.split(image)
    As = np.ones(normal_b.shape, dtype=normal_b.dtype)
    pos = np.where(np.array(image[:,:,0]) > 100)
    for i in range(0,len(pos)):
        As[pos[0][i]][pos[1][i]]=0
    image_out = cv2.merge((normal_r, normal_g, normal_b, As))
    cv2.imwrite(output_dir,image_out)

Edit: A test sample.

0

There are 0 answers