def blend_im_mask_to_exr(exr_filename, im_mask, clip_min=-1, clip_max=1): exrfile = exr.InputFile(exr_filename) #print(exrfile.header()) dw = exrfile.header()['dataWindow'] isize = (dw.max.y - dw.min.y + 1, dw.max.x - dw.min.x + 1) channels = ['R', 'G', 'B'] channelData = dict() for c in channels: C = exrfile.channel(c, Imath.PixelType(Imath.PixelType.FLOAT)) C_arr = np.fromstring(C, dtype=np.float32) #C_arr = np.reshape(C_arr, isize) C_arr = np.clip(C_arr, a_min=clip_min, a_max=clip_max) channelData[c] = array.array( 'f', C_arr.astype(np.float32).flatten().tostring()) # alpha channel with im_mask data channelData['A'] = array.array( 'f', im_mask.astype(np.float32).flatten().tostring()) os.remove(exr_filename) new_header = exr.Header(args.reso, args.reso) new_header['channel'] = { 'R': Imath.Channel(Imath.PixelType(exr.FLOAT)), 'G': Imath.Channel(Imath.PixelType(exr.FLOAT)), 'B': Imath.Channel(Imath.PixelType(exr.FLOAT)), 'A': Imath.Channel(Imath.PixelType(exr.FLOAT)) } exr_out = exr.OutputFile(exr_filename.replace('0001', ''), new_header) exr_out.writePixels(channelData) return
def write_openexr_image(filename, image): """Save image in OpenEXR file format from numpy array.""" height = len(image) width = len(image[0]) channels = len(image[0][0]) # Default header only has RGB channels hdr = OpenEXR.Header(width, height) if channels == 4: data_r = image[:, :, 0].tobytes() data_g = image[:, :, 1].tobytes() data_b = image[:, :, 2].tobytes() data_a = image[:, :, 3].tobytes() image_data = {"R": data_r, "G": data_g, "B": data_b, "A": data_a} # Add alpha channel to header alpha_channel = {"A": Imath.Channel(Imath.PixelType(OpenEXR.FLOAT))} hdr["channels"].update(alpha_channel) elif channels == 3: data_r = image[:, :, 0].tobytes() data_g = image[:, :, 1].tobytes() data_b = image[:, :, 2].tobytes() image_data = {"R": data_r, "G": data_g, "B": data_b} else: raise RuntimeError("Invalid number of channels of starmap image.") file_handler = OpenEXR.OutputFile(str(filename), hdr) file_handler.writePixels(image_data) file_handler.close()
def save_exr(img, filename): c, h, w = img.shape if c == 1: img = img.reshape(w * h) Gs = array.array('f', img).tostring() out = OpenEXR.OutputFile(filename, OpenEXR.Header(w, h)) out.writePixels({'G': Gs}) else: data = np.array(img).reshape(c, w * h) Rs = array.array('f', data[0, :]).tostring() Gs = array.array('f', data[1, :]).tostring() Bs = array.array('f', data[2, :]).tostring() out = OpenEXR.OutputFile(filename, OpenEXR.Header(w, h)) out.writePixels({'R': Rs, 'G': Gs, 'B': Bs})
def test_multipart_out(self): if not hasattr(OpenEXR, 'MultiPartOutputFile'): return data = [ array('f', [0.7] * (100 * 100)).tobytes(), array('f', [0.1] * (100 * 100)).tobytes() ] headers = [] for i in range(2): h = OpenEXR.Header(100, 100) h['channels'] = { 'Z': Imath.Channel(Imath.PixelType(Imath.PixelType.FLOAT)) } # Multipart headers require a name h['name'] = 'image_{0:02d}'.format(i).encode( encoding='ascii' ) # Header strings must be ASCII (Should probably support unicode...) print(type(h['name'])) headers.append(h) x = OpenEXR.MultiPartOutputFile('out-multipart.exr', headers) for i in range(2): pixels = {'Z': data[i]} x.writePixels(i, pixels) x.close()
def saveEXR_grey_np(img, filename): img = img.astype(numpy.float32) # comment this out if we have problems d = len(img.shape) if d >= 3: w, h, _ = img.shape else: w, h = img.shape assert d == 3 or d == 4 or d == 2 # get the channels if d == 2: intensity = numpy.array(img[:, :]).data else: red = numpy.array(img[:, :, 0]) green = numpy.array(img[:, :, 1]) blue = numpy.array(img[:, :, 2]) itentensity_temp = (red + green + blue) / 3 intensity = itentensity_temp.data intensity = intensity.tobytes() # Write the three color channels to the output file out = OpenEXR.OutputFile(filename, OpenEXR.Header(h, w)) dict = {'R': intensity, 'G': intensity, 'B': intensity} out.writePixels(dict)
def createLandAlbedoMap(band_num, landAlbedoRasterFile, out_exr_file): band_start = const.get_value("NO_BAND_WIDTH_MODE_BAND_START") band_end = const.get_value("NO_BAND_WIDTH_MODE_BAND_END") wavelengths = np.linspace(band_start, band_end, band_num + 1) import gdal dataset = gdal.Open(landAlbedoRasterFile) imgXsize = dataset.RasterXSize imgYSize = dataset.RasterYSize band_dict = dict() half_chan = Imath.Channel(Imath.PixelType(Imath.PixelType.FLOAT)) chaneldict = dict() for i in range(0, band_num): start = wavelengths[i] end = wavelengths[i + 1] band_name = "%.2f" % start + "-" + "%.2fnm" % end band = dataset.GetRasterBand(i+1) singleband = band.ReadAsArray(0, 0, imgXsize, imgYSize) singleband = np.fliplr(singleband) singleband = np.reshape(singleband, (imgXsize * imgYSize)) radiance_str = array.array('f', singleband).tostring() # generate arr band_dict[band_name] = radiance_str chaneldict[band_name] = half_chan header = OpenEXR.Header(imgXsize, imgYSize) header["channels"] = chaneldict out = OpenEXR.OutputFile(out_exr_file, header) out.writePixels(band_dict)
def imwrite(img, filename, normalize=False): directory = os.path.dirname(filename) if directory != '' and not os.path.exists(directory): os.makedirs(directory) if isinstance(img, torch.Tensor): img = img.cpu().data.numpy() if normalize: img_rng = np.max(img) - np.min(img) if img_rng > 0: img = (img - np.min(img)) / img_rng if len(img.shape) == 2: img = img.reshape((img.shape[0], img.shape[1], 1)) if img.shape[2] == 1: img = np.tile(img, (1, 1, 3)) if filename[-4:] == '.exr': img_r = img[:, :, 0] img_g = img[:, :, 1] img_b = img[:, :, 2] pixels_r = img_r.astype(np.float16).tostring() pixels_g = img_g.astype(np.float16).tostring() pixels_b = img_b.astype(np.float16).tostring() HEADER = OpenEXR.Header(img.shape[1], img.shape[0]) half_chan = Imath.Channel(Imath.PixelType(Imath.PixelType.HALF)) HEADER['channels'] = dict([(c, half_chan) for c in "RGB"]) exr = OpenEXR.OutputFile(filename, HEADER) exr.writePixels({'R': pixels_r, 'G': pixels_g, 'B': pixels_b}) exr.close() else: img = np.power(np.clip(img, 0.0, 1.0), 1.0 / 2.2) img = (img * 255.0).astype('uint8') skimage.io.imsave(filename, img)
def xtest_multiView(self): h = OpenEXR.Header(640, 480) for views in [[], ['single'], ['left', 'right'], list("abcdefghijklmnopqrstuvwxyz")]: h['multiView'] = views x = OpenEXR.OutputFile("out0.exr", h) x.close() self.assertEqual(OpenEXR.InputFile('out0.exr').header()['multiView'], views)
def test_put_img_together_exr(self): for chunks in [1, 5, 7, 11, 13, 31, 57, 100]: res_y = 0 self.bt.collected_file_names = {} for i in range(1, chunks + 1): # Subtask numbers start from 1. y = randrange(1, 100) res_y += y file1 = self.temp_file_name('chunk{}.exr'.format(i)) exr = OpenEXR.OutputFile(file1, OpenEXR.Header(self.bt.res_x, y)) data = array.array('f', [1.0] * (self.bt.res_x * y)).tostring() exr.writePixels({ 'R': data, 'G': data, 'B': data, 'F': data, 'A': data }) exr.close() self.bt.collected_file_names[i] = file1 self.bt.res_y = res_y self.bt._put_image_together() self.assertTrue(path.isfile(self.bt.output_file)) img = Image.open(self.bt.output_file) img_x, img_y = img.size img.close() self.assertTrue(self.bt.res_x == img_x and res_y == img_y) self.bt.restart() assert self.bt.preview_updater.chunks == {} assert self.bt.preview_updater.perfectly_placed_subtasks == 0 assert self.bt.preview_updater.perfect_match_area_y == 0
def test_one(self): oexr = OpenEXR.InputFile("GoldenGate.exr") #for k,v in sorted(oexr.header().items()): # print "%20s: %s" % (k, v) first_header = oexr.header() default_size = len(oexr.channel('R')) half_size = len( oexr.channel('R', Imath.PixelType(Imath.PixelType.HALF))) float_size = len( oexr.channel('R', Imath.PixelType(Imath.PixelType.FLOAT))) uint_size = len( oexr.channel('R', Imath.PixelType(Imath.PixelType.UINT))) self.assertTrue(default_size in [half_size, float_size, uint_size]) self.assertTrue(float_size == uint_size) self.assertTrue((float_size / 2) == half_size) self.assertTrue( len( oexr.channel( 'R', pixel_type=self.FLOAT, scanLine1=10, scanLine2=10)) == (4 * (first_header['dataWindow'].max.x + 1))) data = b" " * (4 * 100 * 100) h = OpenEXR.Header(100, 100) x = OpenEXR.OutputFile("out.exr", h) x.writePixels({'R': data, 'G': data, 'B': data}) x.close()
def test_code_loopback(self): """ Verify timeCode and keyCode field transit """ data = b" " * (4 * 100 * 100) h = OpenEXR.Header(100, 100) timecodes = [ Imath.TimeCode(1, 2, 3, 4, 0, 0, 0, 0, 0, 0), Imath.TimeCode(1, 2, 3, 4, 1, 0, 0, 0, 0, 0), Imath.TimeCode(1, 2, 3, 4, 0, 1, 0, 0, 0, 0), Imath.TimeCode(1, 2, 3, 4, 0, 0, 1, 0, 0, 0), Imath.TimeCode(1, 2, 3, 4, 0, 0, 0, 1, 0, 0), Imath.TimeCode(1, 2, 3, 4, 0, 0, 0, 0, 1, 0), Imath.TimeCode(1, 2, 3, 4, 0, 0, 0, 0, 0, 1), Imath.TimeCode(1, 2, 3, 4, 1, 1, 1, 1, 1, 1), ] keycode = Imath.KeyCode(1, 2, 3, 4, 5, 6, 60) for timecode in timecodes: h['keyCode'] = keycode h['timeCode'] = timecode x = OpenEXR.OutputFile("out2.exr", h) x.writePixels({'R': data, 'G': data, 'B': data}) x.close() h = OpenEXR.InputFile("out2.exr").header() self.assertEqual(h['keyCode'], keycode) self.assertEqual(h['timeCode'], timecode)
def test_put_img_together_exr_to_exr(self): self.bt.output_format = "EXR" self.bt.output_file += ".EXR" for chunks in [1, 5, 7, 11, 13, 31, 57]: res_y = 0 self.bt.collected_file_names = {} for i in range(1, chunks + 1): # Subtask numbers start from 1. y = randrange(1, 100) res_y += y file1 = self.temp_file_name('chunk{}.exr'.format(i)) exr = OpenEXR.OutputFile(file1, OpenEXR.Header(self.bt.res_x, y)) data = array.array('f', [1.0] * (self.bt.res_x * y)).tostring() exr.writePixels({ 'R': data, 'G': data, 'B': data, 'F': data, 'A': data }) exr.close() self.bt.collected_file_names[i] = file1 self.bt.res_y = res_y self.bt._put_image_together() self.assertTrue(path.isfile(self.bt.output_file)) img = load_img(self.bt.output_file) img_x, img_y = img.get_size() self.assertEqual(self.bt.res_x, img_x) self.assertEqual(self.bt.res_y, img_y) img.close()
def save_rgb(image, filePath, comp=OexrCompression.ZIP): '''Saves the rgb (image) in OpenEXR format. Expects a 3-chan uint32 image.''' if len(image.shape) != 3: raise Exception("Incorrect dimensions!") h, w, c = image.shape # expects Numpy convention (row, col) -> (height, width) if c != 3: raise Exception("Incorrect number of channels!") if image.dtype != "uint32": raise Exception("Incorrect type!, expected uint32") try: header = oe.Header(w, h) header["channels"] = { "R": im.Channel(im.PixelType(oe.UINT)), "G": im.Channel(im.PixelType(oe.UINT)), "B": im.Channel(im.PixelType(oe.UINT)) } header['compression'] = im.Compression(comp) of = oe.OutputFile(filePath, header) r_data = image[:, :, 0].tostring() g_data = image[:, :, 1].tostring() b_data = image[:, :, 2].tostring() of.writePixels({"R": r_data, "G": g_data, "B": b_data}) of.close() except: raise
def exr2ctl2arr(im, im_rows, im_columns, ctl_transforms): #creating OpenEXR file pixels = im.astype(numpy.float16).tostring() HEADER = OpenEXR.Header(im_rows, im_columns) half_chan = Imath.Channel(Imath.PixelType(Imath.PixelType.HALF)) HEADER['channels'] = dict([(c, half_chan) for c in "RGB"]) exr = OpenEXR.OutputFile("exr_in.exr", HEADER) exr.writePixels({'R': pixels, 'G': pixels, 'B': pixels}) exr.close() # #calling CTL Render function call_ctl_min = colour.utilities.ctl_render("./exr_in.exr", "./exr_out.exr", ctl_transforms) #opening newly formed OpenEXR file with transformed applied im = OpenEXR.InputFile('exr_out.exr') (r,g,b) = im.channels("RGB") dw = im.header()['dataWindow'] size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1) #reshaping and reformating image channels to put into new array red = numpy.reshape(numpy.fromstring(r, dtype=numpy.float16), (size[0], size[1])) green = numpy.reshape(numpy.fromstring(g, dtype=numpy.float16), (size[0], size[1])) blue = numpy.reshape(numpy.fromstring(b, dtype=numpy.float16), (size[0], size[1])) image = numpy.stack((blue, green, red), axis=-1) test = numpy.array(2**16) cv2.imwrite('cv1.tif', test) return image
def save_depth(image, filePath, comp=OexrCompression.ZIP): ''' Saves the zBuffer (image) in OpenEXR format. Expects a 1-chann float32 image. ''' if len(image.shape) != 2: raise Exception("Incorrect dimensions!") if image.dtype != "float32": raise Exception("Incorrect type!, expected float32") try: h, w = image.shape header = oe.Header(w, h) header["channels"] = {"Z": im.Channel(im.PixelType(oe.FLOAT))} header['compression'] = im.Compression(comp) of = oe.OutputFile(filePath, header) image_data = image.tostring() of.writePixels({"Z": image_data}) of.close() except: raise
def test_header_bytes(self): ctype = Imath.Channel(Imath.PixelType(Imath.PixelType.HALF)) target = 'test_exr.exr' data = {} chans = {} channels = list('RGBA') for c in channels: chan = c.upper() data[chan] = b'X' * (10 * 5 * 2) chans[chan] = ctype header = OpenEXR.Header(10, 5) header['channels'] = chans header['foo1'] = b'bar' header['foo2'] = 'bar'.encode('ascii') header['foo3'] = 'bar'.encode('utf-8') file_ = OpenEXR.OutputFile(target, header) file_.writePixels(data) file_.close() # Read them back and confirm they are all b'bar' infile = OpenEXR.InputFile(target) h = infile.header() infile.close() self.assertEqual(h["foo1"], b'bar') self.assertEqual(h["foo2"], b'bar') self.assertEqual(h["foo3"], b'bar')
def write_exr(filename, values, channel_names): """Writes the values in a multi-channel ndarray into an EXR file. Args: filename: The filename of the output file values: A numpy ndarray with shape [height, width, channels] channel_names: A list of strings with length = channels Raises: TypeError: If the numpy array has an unsupported type. ValueError: If the length of the array and the length of the channel names list do not match. """ if values.shape[-1] != len(channel_names): raise ValueError( 'Number of channels in values does not match channel names (%d, %d)' % (values.shape[-1], len(channel_names))) header = OpenEXR.Header(values.shape[1], values.shape[0]) try: exr_channel_type = Imath.PixelType(_np_to_exr[values.dtype.type]) except KeyError: raise TypeError('Unsupported numpy type: %s' % str(values.dtype)) header['channels'] = { n: Imath.Channel(exr_channel_type) for n in channel_names } channel_data = [values[..., i] for i in range(values.shape[-1])] exr = OpenEXR.OutputFile(filename, header) exr.writePixels( dict((n, d.tobytes()) for n, d in zip(channel_names, channel_data))) exr.close()
def write_exr(data, path): ''' data를 exr파일로 저장 Args: path: 경로 + 파일 이름.exr data: 3차원 이미지 데이터 ''' assert data.ndim == 3, "exr 파일 write하려는데 차원 수가 다름" + str(data.shape) if not os.path.isdir(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) h, w, c = data.shape if c == 3: channel_list = ['B', 'G', 'R'] else: channel_list = ['B'] header = OpenEXR.Header(w, h) header['compression'] = Imath.Compression( Imath.Compression.PIZ_COMPRESSION) # header['channels'] = {c: pixel_type#Imath.Channel(Imath.PixelType.FLOAT) # for c in channel_list} out = OpenEXR.OutputFile(path, header) ch_data = { ch: data[:, :, index].astype(np.float32).tostring() for index, ch in enumerate(channel_list) } out.writePixels(ch_data)
def save_exr(fname, r=None, g=None, b=None, comments=''): """saves exr file. Copied from freemovr_engine.exr""" r = np.array(r) assert r.ndim == 2 g = np.array(g) assert g.ndim == 2 assert g.shape == r.shape b = np.array(b) assert b.ndim == 2 assert b.shape == r.shape header = OpenEXR.Header(r.shape[1], r.shape[0]) header['channels'] = { 'R': Imath.Channel(FREEMOVR_EXR_PIXEL_TYPE), 'G': Imath.Channel(FREEMOVR_EXR_PIXEL_TYPE), 'B': Imath.Channel(FREEMOVR_EXR_PIXEL_TYPE), } header['comments'] = comments out = OpenEXR.OutputFile(fname, header) data = { 'R': r.astype(np.float32).tostring(), 'G': g.astype(np.float32).tostring(), 'B': b.astype(np.float32).tostring() } out.writePixels(data) out.close()
def writeEXR(image, name): R = image[:, :, 0].reshape(-1) G = image[:, :, 1].reshape(-1) B = image[:, :, 2].reshape(-1) (Rs, Gs, Bs) = [array.array('f', Chan).tobytes() for Chan in (R, G, B)] out = OpenEXR.OutputFile(name, OpenEXR.Header(image.shape[1], image.shape[0])) out.writePixels({'R': Rs, 'G': Gs, 'B': Bs})
def save_exr_from_numpy(filename, image_as_array): """ saves an exr image (depth image) form a numpy array""" width = image_as_array.shape[1] height = image_as_array.shape[0] data = image_as_array.tostring() exr = OpenEXR.OutputFile(filename, OpenEXR.Header(width, height)) exr.writePixels({'R': data, 'G': data, 'B': data}) exr.close()
def saveEXRfromMatrix(file, data, size): output = OpenEXR.OutputFile(file, OpenEXR.Header(*size)) data = np.moveaxis(data, -1, 0) output.writePixels({ "R": data[0].tostring(), "G": data[1].tostring(), "B": data[2].tostring(), # "A": data[3].tostring() })
def writeexr(path, image): """Write image to path as an EXR file""" header = OpenEXR.Header(image.shape[1], image.shape[0]) out = OpenEXR.OutputFile(path, header) out.writePixels({ 'R': image[:, :, 0].tostring(), 'G': image[:, :, 1].tostring(), 'B': image[:, :, 2].tostring() })
def create_envmap_fun(input, output): band_start = const.get_value("NO_BAND_WIDTH_MODE_BAND_START") band_end = const.get_value("NO_BAND_WIDTH_MODE_BAND_END") band_num = const.get_value("NO_BAND_WIDTH_MODE_BAND_NUM") resolution_width = const.get_value("env_map_resolution") resolution_height = int(resolution_width / 2) # golden = OpenEXR.InputFile(out_file) # b1 = golden.channel("400.0-404.0nm") # print OpenEXR.InputFile(out_file).header() # # sys.exit(0) # read data f = open(input, 'r') theta_phi = [] band_data = [] for line in f: arr = line.split(" ") theta = float(line[0]) phi = float(line[1]) theta_phi.append([theta, phi]) if len(arr[2:]) != band_num: log("band number does not equal.") sys.exit(0) band_data.append(list(map(lambda x: float(x), arr[2:]))) # band_data = map(list, zip(*band_data)) # [[band1_p1,band1_p2,...],[band2_p1,band2_p2,...]] wavelengths = np.linspace(band_start, band_end, band_num + 1) radiance_map = np.zeros((resolution_height, resolution_width, band_num)) factor_y = 180 / resolution_height # lat for each pixel factor_x = 2 * 180 / resolution_width # lon for each pixel for i in range(0, resolution_height / 2): c_theta = i * factor_y for j in range(0, resolution_width): c_phi = (j + 0.5) * factor_x nearest_pos = get_nearest_theta_phi(c_theta, c_phi, theta_phi) radiance_map[i, j, :] = band_data[nearest_pos] # write this into exr file band_dict = dict() half_chan = Imath.Channel(Imath.PixelType(Imath.PixelType.FLOAT)) chaneldict = dict() for i in range(0, band_num): start = wavelengths[i] end = wavelengths[i + 1] band_name = "%.2f" % start + "-" + "%.2fnm" % end singleband = radiance_map[:, :, i] singleband = np.reshape(singleband, (resolution_width * resolution_height)) radiance_str = array.array('f', singleband).tostring() # generate arr band_dict[band_name] = radiance_str chaneldict[band_name] = half_chan header = OpenEXR.Header(resolution_width, resolution_height) header["channels"] = chaneldict out = OpenEXR.OutputFile(output, header) out.writePixels(band_dict)
def test_fileobject(self): f = io.StringIO() (w, h) = (640, 480) data = array.array('f', [0 for x in range(w * h)]).tostring() hdr = OpenEXR.Header(w, h) x = OpenEXR.OutputFile(f, hdr) x.writePixels({'R': data, 'G': data, 'B': data}) x.close() f.seek(0) self.assertEqual(hdr, OpenEXR.InputFile(f).header())
def writeexr(I, path): """EXR write helper. Requires OpenEXR.""" import OpenEXR import Imath h, w = I.shape[:2] head = OpenEXR.Header(w, h) head["compression"] = Imath.Compression(Imath.Compression.DWAB_COMPRESSION) of = OpenEXR.OutputFile(path, head) R, G, B = [I[:,:,c].tobytes() for c in [0,1,2]] of.writePixels({'R': R, 'G': G, 'B': B})
def test_write_buffer_object(self): (w, h) = (640, 480) a = array('f', [(i % w) / float(w) for i in range(w * h)]) data = bytearray(a.tobytes()) hdr = OpenEXR.Header(w, h) x = OpenEXR.OutputFile("out3.exr", hdr) x.writePixels({'R': data, 'G': data, 'B': data}) x.close() r = self.load_red("out3.exr") self.assertTrue(r == data)
def writeEXR(rgb, filenameEXR): size = rgb.shape header = OpenEXR.Header(size[0], size[1]) rgbYX = np.swapaxes(rgb, 0, 1) #(y,x,c) -> (x,y,c) header['channels'] = { c: Imath.Channel(Imath.PixelType(Imath.PixelType.FLOAT)) for c in "RGB" } #shouldn't we check the type of rgb's elements? exr = OpenEXR.OutputFile(filenameEXR, header) exr.writePixels(rgb2rgbdict(rgbYX)) exr.close()
def write_exr(out_file, data): exr = OpenEXR.OutputFile(out_file, OpenEXR.Header(data.shape[1], data.shape[0])) red = data[:, :, 0] green = data[:, :, 1] blue = data[:, :, 2] exr.writePixels({ 'R': red.tostring(), 'G': green.tostring(), 'B': blue.tostring() })
def save_masked_depth(depth, mask, comp_id, out_paths): comp_id = os.path.splitext(comp_id)[0] depth_array = np.asarray(depth).astype(np.float32) mask_array = np.asarray(mask).copy() mask_array[mask_array > 0] = 1 mask_array = np.ones_like(mask_array) - mask_array depth_data = depth_array * mask_array.astype(np.float32) exr = OpenEXR.OutputFile( os.path.join(out_paths['depth'], comp_id + '.exr'), OpenEXR.Header(depth.size[0], depth.size[1])) exr.writePixels({'R': depth_data, 'G': depth_data, 'B': depth_data})