2

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.

JGrey
  • 31
  • 3
  • please check `cv2.getBuildInformation()` to see, if your cv2 actually *has* exr support builtin (which is rather unlikely) also: https://github.com/opencv/opencv/issues/16115 – berak Jun 24 '22 at 07:42
  • Did you get an error? Was any file created at all, or nothing? Did you check the shape and `dtype` of all your Numpy arrays? Did you run the debugger? – Mark Setchell Jun 24 '22 at 09:38
  • @MarkSetchell I didn't get any error, there were .exr files written for both methods using the code posted but neither has alpha channel. All shape match and dtype are all float32. – JGrey Jun 24 '22 at 14:13
  • @berak The issue was completed according to that thread, that's why I tried using OpenCV. – JGrey Jun 24 '22 at 14:15
  • Please share a link to a sample image that exhibits this problem. Thank you. – Mark Setchell Jun 24 '22 at 14:39
  • @MarkSetchell Added sample https://drive.google.com/file/d/16NybPR3xeVCHKwymyYUbKf-oB45zrY4Q/view?usp=sharing – JGrey Jun 24 '22 at 14:51
  • That image works fine with OpenCV for me. Try making your code really, really simple. Load the image, convert to RGBA `result = cv2.cvtColor(im, cv2.COLOR_BGR2BGRA)`, save in current directory under new name, check result with `exiftool` – Mark Setchell Jun 24 '22 at 15:05
  • @MarkSetchell If you load and convert to RGBA then save it to .exr then read it in Photoshop or Blender to check, the new .exr still doesn't have any alpha information. – JGrey Jun 25 '22 at 04:35

0 Answers0