def ImageBufMakeConstant(xres, yres, chans=3, format=oiio.UINT8, value=(0,0,0), xoffset=0, yoffset=0, orientation=1, inputSpec=None) : ''' Create a new Image Buffer ''' # Copy an existing input spec # Mostly to ensure that metadata makes it through if inputSpec: spec = inputSpec spec.width = xres spec.height = yres spec.nchannels = chans spec.set_format( format ) # Or create a new ImageSpec else: spec = ImageSpec (xres,yres,chans,format) spec.x = xoffset spec.y = yoffset b = ImageBuf (spec) b.orientation = orientation oiio.ImageBufAlgo.fill(b, value) return b
def ImageBufMakeConstant(xres, yres, chans=3, format=oiio.UINT8, value=(0, 0, 0), xoffset=0, yoffset=0, orientation=1, inputSpec=None): ''' Create a new Image Buffer ''' # Copy an existing input spec # Mostly to ensure that metadata makes it through if inputSpec: spec = inputSpec spec.width = xres spec.height = yres spec.nchannels = chans spec.set_format(format) # Or create a new ImageSpec else: spec = ImageSpec(xres, yres, chans, format) spec.x = xoffset spec.y = yoffset b = ImageBuf(spec) b.orientation = orientation oiio.ImageBufAlgo.fill(b, value) return b
def make_constimage(xres, yres, chans=3, format=oiio.UINT8, value=(0, 0, 0), xoffset=0, yoffset=0): spec = ImageSpec(xres, yres, chans, format) spec.x = xoffset spec.y = yoffset b = ImageBuf(spec) oiio.ImageBufAlgo.fill(b, value) return b
def make_constimage (xres, yres, chans=3, format=oiio.UINT8, value=(0,0,0), xoffset=0, yoffset=0) : spec = ImageSpec (xres,yres,chans,format) spec.x = xoffset spec.y = yoffset b = ImageBuf (spec) oiio.ImageBufAlgo.fill (b, value) return b
def write_image(cls, file: Path, pixels: np.array): output = ImageOutput.create(file.as_posix()) if not output: LOGGER.error('Error creating oiio image output:\n%s', oiio.geterror()) return if len(pixels.shape) < 3: LOGGER.error( 'Can not create image with Pixel data in this shape. Expecting 3 or 4 channels(RGB, RGBA).' ) return h, w, c = pixels.shape spec = ImageSpec(w, h, c, cls.get_numpy_oiio_img_format(pixels)) result = output.open(file.as_posix(), spec) if result: try: output.write_image(pixels) except Exception as e: LOGGER.error('Could not write Image: %s', e) else: LOGGER.error('Could not open image file for writing: %s: %s', file.name, output.geterror()) output.close()
def resizeHDR(scrBuffer, width, height): srcSpec = scrBuffer.spec() resizedBuffer = ImageBuf( ImageSpec(width, height, srcSpec.nchannels, srcSpec.format)) ImageBufAlgo.resize(resizedBuffer, scrBuffer, filtername=resizeFilter) threadResult.put(resizedBuffer) return resizedBuffer
def write_image(image, path, bit_depth='float32'): """ Writes given image using *OpenImageIO*. Parameters ---------- image : array_like Image data. path : unicode Image path. bit_depth : unicode, optional **{'float32', 'uint8', 'uint16', 'float16'}**, Image bit_depth. Returns ------- bool Definition success. Examples -------- >>> import os >>> path = os.path.join('tests', 'resources', 'CMSTestPattern.exr') >>> image = read_image_as_array(path) # doctest: +SKIP >>> path = os.path.join('tests', 'resources', 'CMSTestPattern.png') >>> write_image(image, path, 'uint8') # doctest: +SKIP True """ if is_openimageio_installed(raise_exception=True): from OpenImageIO import ImageOutput, ImageOutputOpenMode, ImageSpec bit_depth_specification = BIT_DEPTH_MAPPING.get(bit_depth) bit_depth = bit_depth_specification.openimageio image = np.asarray(image) image *= bit_depth_specification.domain if bit_depth_specification.clip: image = np.clip(image, 0, bit_depth_specification.domain) image = image.astype(bit_depth_specification.numpy) if image.ndim == 2: height, width = image.shape channels = 1 else: height, width, channels = image.shape specification = ImageSpec(width, height, channels, bit_depth) image_output = ImageOutput.create(path) image_output.open(path, specification, ImageOutputOpenMode.Create) image_output.write_image(bit_depth, image.tostring()) image_output.close() return True
def writeTexture(scrBuffer, outFile): global errorFlag try: config = ImageSpec() # config.attribute("maketx:highlightcomp", 1) config.attribute("maketx:filtername", "lanczos3") # config.attribute("maketx:opaquedetect", 1) config.attribute("maketx:oiio options", 1) scrBuffer.set_write_tiles(tileSize, tileSize) ImageBufAlgo.make_texture(oiio.MakeTxTexture, scrBuffer, outFile, config) errorFlag = 0 except Exception as e: errorFlag = 1 tqdm.write( prefix + Fore.RED + "Error on conversion. Maybe wrong/corrupt texture file or resolution too high." )
def np_to_imagebuf(cls, img_pixels: np.array): """ Load a numpy array 8/32bit to oiio ImageBuf """ if len(img_pixels.shape) < 3: LOGGER.error( 'Can not create image with pixel data in this shape. Expecting 4 channels(RGBA).' ) return h, w, c = img_pixels.shape img_spec = ImageSpec(w, h, c, cls.get_numpy_oiio_img_format(img_pixels)) img_buf = ImageBuf(img_spec) img_buf.set_pixels(img_spec.roi_full, img_pixels) return img_buf
def OIIOImageBufferFromOpenCVImageBuffer(opencvImageBuffer): (height, width, channels) = opencvImageBuffer.shape npChanneltype = opencvImageBuffer.dtype #print( "OIIOImageBufferFromOpenCVImageBuffer", width, height, channels, npChanneltype ) npToArrayBitDepth = { np.dtype('uint8') : 'B', np.dtype('uint16') : 'H', np.dtype('uint32') : 'I', np.dtype('float32') : 'f', np.dtype('float64') : 'd', } npToOIIOBitDepth = { np.dtype('uint8') : oiio.BASETYPE.UINT8, np.dtype('uint16') : oiio.BASETYPE.UINT16, np.dtype('uint32') : oiio.BASETYPE.UINT32, np.dtype('float32') : oiio.BASETYPE.FLOAT, np.dtype('float64') : oiio.BASETYPE.DOUBLE, } # Support this when oiio more directly integrates with numpy # np.dtype('float16') : oiio.BASETYPE.HALF, if (npChanneltype in npToArrayBitDepth and npChanneltype in npToOIIOBitDepth): arrayChannelType = npToArrayBitDepth[npChanneltype] oiioChanneltype = npToOIIOBitDepth[npChanneltype] else: print( "opencv to oiio - Using fallback bit depth" ) arrayChannelType = 'f' oiioChanneltype = oiio.BASETYPE.FLOAT spec = ImageSpec(width, height, channels, oiioChanneltype) oiioImageBuffer = ImageBuf(spec) roi = oiio.ROI(0, width, 0, height, 0, 1, 0, channels) conversion = oiioImageBuffer.set_pixels( roi, array.array(arrayChannelType, opencvImageBuffer.flatten()) ) if not conversion: print( "opencv to oiio - Error converting the OpenCV buffer to an OpenImageIO buffer" ) oiioImageBuffer = None return oiioImageBuffer
def main(): options, args = parseOptions() tile_x = options.tile_x tile_y = options.tile_y frame = options.frame output = options.output filemask = options.filemask tile_files = [] tiles_lost = [] for i in xrange(0, (tile_x * tile_y)): filepath = filemask % (i, frame) if not os.path.exists(filepath): tiles_lost += [filepath] continue tile_files += [filepath] if len(tile_files) != (tile_x * tile_y): raise Exception("Tile not found: %s" % tiles_lost) #TODO: merge metadata from tiles spec = ImageBuf(str(tile_files[0])).spec() spec_e = ImageSpec(spec.full_width, spec.full_height, spec.nchannels, spec.format) extended = ImageBuf(spec_e) for filename in tile_files: img = ImageBuf(filename) ImageBufAlgo.paste(extended, img.xbegin, img.ybegin, img.zbegin, 0, img, nthreads=4) extended.write(output)
print ("[", end="") for c in range(spec.nchannels) : print (fmt.format(p[c]), end=" ") print ("] ", end="") print ("") ###################################################################### # main test starts here try: # Some handy images to work with gridname = os.path.join(OIIO_TESTSUITE_IMAGEDIR, "grid.tif") grid = ImageBuf (gridname) checker = ImageBuf(ImageSpec(256, 256, 3, oiio.UINT8)) ImageBufAlgo.checker (checker, 8, 8, 8, (0,0,0), (1,1,1)) gray128 = make_constimage (128, 128, 3, oiio.HALF, (0.5,0.5,0.5)) gray64 = make_constimage (64, 64, 3, oiio.HALF, (0.5,0.5,0.5)) tahoetiny = ImageBuf(OIIO_TESTSUITE_ROOT+"/oiiotool/src/tahoe-tiny.tif") # black # b = ImageBuf (ImageSpec(320,240,3,oiio.UINT8)) b = ImageBufAlgo.zero (roi=oiio.ROI(0,320,0,240,0,1,0,3)) write (b, "black.tif", oiio.UINT8) # fill (including use of ROI) b = ImageBuf (ImageSpec(256,256,3,oiio.UINT8)); ImageBufAlgo.fill (b, (1,0.5,0.5)) ImageBufAlgo.fill (b, (0,1,0), oiio.ROI(100,180,100,180)) write (b, "filled.tif", oiio.UINT8)
def write_image(image, path, bit_depth='float32', attributes=None): """ Writes given image using *OpenImageIO*. Parameters ---------- image : array_like Image data. path : unicode Image path. bit_depth : unicode, optional **{'float32', 'uint8', 'uint16', 'float16'}**, Image bit_depth. attributes : array_like, optional An array of :class:`colour.io.ImageAttribute_Specification` class instances used to set attributes of the image. Returns ------- bool Definition success. Examples -------- Basic image writing: >>> import os >>> path = os.path.join('tests', 'resources', 'CMSTestPattern.exr') >>> image = read_image(path) # doctest: +SKIP >>> path = os.path.join('tests', 'resources', 'CMSTestPattern.tif') >>> write_image(image, path) # doctest: +SKIP True Advanced image writing while setting attributes: >>> compression = ImageAttribute_Specification('Compression', 'none') >>> write_image(image, path, 'uint8', [compression]) # doctest: +SKIP True """ if is_openimageio_installed(raise_exception=True): from OpenImageIO import ImageOutput, ImageOutputOpenMode, ImageSpec path = str(path) if attributes is None: attributes = [] bit_depth_specification = BIT_DEPTH_MAPPING[bit_depth] bit_depth = bit_depth_specification.openimageio image = as_float_array(image) image *= bit_depth_specification.domain if bit_depth_specification.clip: image = np.clip(image, 0, bit_depth_specification.domain) image = image.astype(bit_depth_specification.numpy) if image.ndim == 2: height, width = image.shape channels = 1 else: height, width, channels = image.shape specification = ImageSpec(width, height, channels, bit_depth) for attribute in attributes: name = str(attribute.name) value = (str(attribute.value) if isinstance( attribute.value, string_types) else attribute.value) type_ = attribute.type_ if attribute.type_ is None: specification.attribute(name, value) else: specification.attribute(name, type_, value) image_output = ImageOutput.create(path) image_output.open(path, specification, ImageOutputOpenMode.Create) image_output.write_image(bit_depth, image.tostring()) image_output.close() return True
def write(image, filename, format=oiio.UNKNOWN): if not image.has_error: image.set_write_format(format) image.write(filename) if image.has_error: print "Error writing", filename, ":", image.geterror() ###################################################################### # main test starts here try: # Some handy images to work with gridname = "../../../../../oiio-images/grid.tif" grid = ImageBuf(gridname) checker = ImageBuf(ImageSpec(256, 256, 3, oiio.UINT8)) ImageBufAlgo.checker(checker, 8, 8, 8, (0, 0, 0), (1, 1, 1)) gray128 = make_constimage(128, 128, 3, oiio.HALF, (0.5, 0.5, 0.5)) gray64 = make_constimage(64, 64, 3, oiio.HALF, (0.5, 0.5, 0.5)) # black b = ImageBuf(ImageSpec(320, 240, 3, oiio.UINT8)) ImageBufAlgo.zero(b) write(b, "black.tif") # fill (including use of ROI) b = ImageBuf(ImageSpec(256, 256, 3, oiio.UINT8)) ImageBufAlgo.fill(b, (1, 0.5, 0.5)) ImageBufAlgo.fill(b, (0, 1, 0), oiio.ROI(100, 180, 100, 180)) write(b, "filled.tif")
def write_image_OpenImageIO( image: ArrayLike, path: str, bit_depth: Literal[ "uint8", "uint16", "float16", "float32", "float64", "float128" ] = "float32", attributes: Optional[Sequence] = None, ) -> Boolean: # noqa: D405,D407,D410,D411 """ Write given image at given path using *OpenImageIO*. Parameters ---------- image Image data. path Image path. bit_depth Bit depth to write the image at, the bit depth conversion behaviour is ruled directly by *OpenImageIO*. attributes An array of :class:`colour.io.ImageAttribute_Specification` class instances used to set attributes of the image. Returns ------- :class:`bool` Definition success. Examples -------- Basic image writing: >>> import os >>> import colour >>> path = os.path.join(colour.__path__[0], 'io', 'tests', 'resources', ... 'CMS_Test_Pattern.exr') >>> image = read_image(path) # doctest: +SKIP >>> path = os.path.join(colour.__path__[0], 'io', 'tests', 'resources', ... 'CMSTestPattern.tif') >>> write_image_OpenImageIO(image, path) # doctest: +SKIP True Advanced image writing while setting attributes: >>> compression = ImageAttribute_Specification('Compression', 'none') >>> write_image_OpenImageIO(image, path, 'uint8', [compression]) ... # doctest: +SKIP True Writing an "ACES" compliant "EXR" file: >>> if is_openimageio_installed(): # doctest: +SKIP ... from OpenImageIO import TypeDesc ... chromaticities = ( ... 0.7347, 0.2653, 0.0, 1.0, 0.0001, -0.077, 0.32168, 0.33767) ... attributes = [ ... ImageAttribute_Specification('acesImageContainerFlag', True), ... ImageAttribute_Specification( ... 'chromaticities', chromaticities, TypeDesc('float[8]')), ... ImageAttribute_Specification('compression', 'none')] ... write_image_OpenImageIO(image, path, attributes=attributes) """ from OpenImageIO import ImageOutput, ImageSpec image = as_float_array(image) path = str(path) attributes = cast(List, optional(attributes, [])) bit_depth_specification = MAPPING_BIT_DEPTH[bit_depth] if bit_depth_specification.numpy in [np.uint8, np.uint16]: mininum, maximum = np.iinfo(np.uint8).min, np.iinfo(np.uint8).max image = np.clip(image * maximum, mininum, maximum) image = as_int_array(image, bit_depth_specification.numpy) image = image.astype(bit_depth_specification.numpy) if image.ndim == 2: height, width = image.shape channels = 1 else: height, width, channels = image.shape specification = ImageSpec( width, height, channels, bit_depth_specification.openimageio ) for attribute in attributes: name = str(attribute.name) value = ( str(attribute.value) if isinstance(attribute.value, str) else attribute.value ) type_ = attribute.type_ if attribute.type_ is None: specification.attribute(name, value) else: specification.attribute(name, type_, value) image_output = ImageOutput.create(path) image_output.open(path, specification) image_output.write_image(image) image_output.close() return True
def loadImageBuffer(imagePath, outputGamut=None): ''' Load an image buffer. Manage raw formats if OIIO can't load them directly ''' global temp_dirs # Raw camera files require special handling imageExtension = os.path.splitext(imagePath)[-1][1:].lower() if imageExtension in rawExtensions: # Either OIIO can read the data directly if oiioSupportsRaw(): print("\tUsing OIIO ImageInput to read raw file") # Convert gamut number to text gamuts = { 0: "raw", 1: "sRGB", 2: "Adobe", 3: "Wide", 4: "ProPhoto", 5: "XYZ", 6: "ACES", } outputGamutText = "sRGB" if outputGamut in gamuts: outputGamutText = gamuts[outputGamut] # Spec will be used to configure the file read spec = ImageSpec() spec.attribute("raw:ColorSpace", outputGamutText) spec.attribute("raw:use_camera_wb", 1) spec.attribute("raw:auto_bright", 0) spec.attribute("raw:use_camera_matrix", 0) spec.attribute("raw:adjust_maximum_thr", 0.0) # Read the image using the adjusted spec imageBuffer = oiio.ImageBuf() imageBuffer.reset(imagePath, 0, 0, spec) # Or we need to use dcraw to help the process along else: print("\tUsing dcraw to convert raw, then OIIO to read temp file") # Create a new temp dir for each image so there's no chance # of a name collision temp_dir = tempfile.mkdtemp() temp_dirs.append(temp_dir) imageName = os.path.split(imagePath)[-1] temp_file = os.path.join(temp_dir, "%s_temp.tiff" % imageName) if outputGamut is None: outputGamut = 1 cmd = "dcraw" args = [] #args += ['-v'] args += ['-w', '-o', str(outputGamut), '-4', '-T', '-W', '-c'] args += [imagePath] cmdargs = [cmd] cmdargs.extend(args) #print( "\tTemp_file : %s" % temp_file ) print("\tCommand : %s" % " ".join(cmdargs)) with open(temp_file, "w") as temp_handle: process = sp.Popen(cmdargs, stdout=temp_handle, stderr=sp.STDOUT) process.wait() #print( "Loading : %s" % temp_file ) imageBuffer = ImageBuf(temp_file) # Just load the image using OIIO else: #print( "Using OIIO ImageBuf read route" ) imageBuffer = ImageBuf(imagePath) return imageBuffer
def write_image_OpenImageIO(image, path, bit_depth='float32', attributes=None): """ Writes given image at given path using *OpenImageIO*. Parameters ---------- image : array_like Image data. path : unicode Image path. bit_depth : unicode, optional **{'float32', 'uint8', 'uint16', 'float16'}**, Bit depth to write the image at, the bit depth conversion behaviour is ruled directly by *OpenImageIO*. attributes : array_like, optional An array of :class:`colour.io.ImageAttribute_Specification` class instances used to set attributes of the image. Returns ------- bool Definition success. Examples -------- Basic image writing: >>> import os >>> import colour >>> path = os.path.join(colour.__path__[0], 'io', 'tests', 'resources', ... 'CMS_Test_Pattern.exr') >>> image = read_image(path) # doctest: +SKIP >>> path = os.path.join(colour.__path__[0], 'io', 'tests', 'resources', ... 'CMSTestPattern.tif') >>> write_image(image, path) # doctest: +SKIP True Advanced image writing while setting attributes: >>> compression = ImageAttribute_Specification('Compression', 'none') >>> write_image(image, path, 'uint8', [compression]) # doctest: +SKIP True """ if is_openimageio_installed(raise_exception=True): # pragma: no cover from OpenImageIO import VERSION_MAJOR, ImageOutput, ImageSpec path = str(path) if attributes is None: attributes = [] bit_depth_specification = BIT_DEPTH_MAPPING[bit_depth] bit_depth = bit_depth_specification.openimageio image = as_float_array(image) image = image * bit_depth_specification.domain if bit_depth_specification.clip: image = np.clip(image, 0, bit_depth_specification.domain) image = image.astype(bit_depth_specification.numpy) if image.ndim == 2: height, width = image.shape channels = 1 else: height, width, channels = image.shape specification = ImageSpec(width, height, channels, bit_depth) for attribute in attributes: name = str(attribute.name) value = (str(attribute.value) if isinstance( attribute.value, string_types) else attribute.value) type_ = attribute.type_ if attribute.type_ is None: specification.attribute(name, value) else: specification.attribute(name, type_, value) image_output = ImageOutput.create(path) if VERSION_MAJOR == 1: from OpenImageIO import ImageOutputOpenMode image_output.open(path, specification, ImageOutputOpenMode.Create) image_output.write_image(bit_depth, image.tostring()) else: image_output.open(path, specification) image_output.write_image(image) image_output.close() return True
def write(image, filename, format=oiio.UNKNOWN): if not image.has_error: image.set_write_format(format) image.write(filename) if image.has_error: print "Error writing", filename, ":", image.geterror() ###################################################################### # main test starts here try: # Some handy images to work with gridname = "../../../../../oiio-images/grid.tif" grid = ImageBuf(gridname) checker = ImageBuf(ImageSpec(256, 256, 3, oiio.UINT8)) ImageBufAlgo.checker(checker, 8, 8, 8, (0, 0, 0), (1, 1, 1)) gray128 = make_constimage(128, 128, 3, oiio.HALF, (0.5, 0.5, 0.5)) # black b = ImageBuf(ImageSpec(320, 240, 3, oiio.UINT8)) ImageBufAlgo.zero(b) write(b, "black.tif") # fill (including use of ROI) b = ImageBuf(ImageSpec(256, 256, 3, oiio.UINT8)) ImageBufAlgo.fill(b, (1, 0.5, 0.5)) ImageBufAlgo.fill(b, (0, 1, 0), oiio.ROI(100, 180, 100, 180)) write(b, "filled.tif") # checker
def loadImageBuffer( imagePath, outputGamut=None, rawSaturationPoint=-1.0, dcrawVariant=None ): ''' Load an image buffer. Manage raw formats if OIIO can't load them directly ''' global temp_dirs # Raw camera files require special handling imageExtension = os.path.splitext( imagePath )[-1][1:].lower() if imageExtension in rawExtensions: # Either OIIO can read the data directly if oiioSupportsRaw(): print( "\tUsing OIIO ImageInput to read raw file" ) # Convert gamut number to text gamuts = { 0 : "raw", 1 : "sRGB", 2 : "Adobe", 3 : "Wide", 4 : "ProPhoto", 5 : "XYZ" } outputGamutText = "sRGB" if outputGamut in gamuts: outputGamutText = gamuts[outputGamut] # Spec will be used to configure the file read spec = ImageSpec() spec.attribute("raw:ColorSpace", outputGamutText) spec.attribute("raw:use_camera_wb", 1) spec.attribute("raw:auto_bright", 0) spec.attribute("raw:use_camera_matrix", 0) spec.attribute("raw:adjust_maximum_thr", 0.0) imageBuffer = ImageBuf() imageBuffer.reset( imagePath, 0, 0, spec ) # Or we need to use dcraw to help the process along else: print( "\tUsing dcraw to convert raw, then OIIO to read file" ) # Create a new temp dir for each image so there's no chance # of a name collision temp_dir = tempfile.mkdtemp() temp_dirs.append( temp_dir ) imageName = os.path.split(imagePath)[-1] temp_file = os.path.join(temp_dir, "%s_temp.tiff" % imageName) if outputGamut is None: outputGamut = 1 if dcrawVariant == "dcraw": cmd = "dcraw" args = [] #args += ['-v'] args += ['-w', '-o', str(outputGamut), '-4', '-T', '-W'] args += ['-c'] if rawSaturationPoint > 0.0: args += ['-S', str(int(rawSaturationPoint))] args += [imagePath] cmdargs = [cmd] cmdargs.extend(args) #print( "\tTemp_file : %s" % temp_file ) print( "\tCommand : %s" % " ".join(cmdargs) ) with open(temp_file, "w") as temp_handle: process = sp.Popen(cmdargs, stdout=temp_handle, stderr=sp.STDOUT) process.wait() # Use the libraw dcraw_emu when dcraw doesn't support a camera yet else: cmd = "dcraw_emu" args = [] args += ['-w', '-o', str(outputGamut), '-4', '-T', '-W'] #if rawSaturationPoint > 0.0: # args += ['-c', str(float(rawSaturationPoint/16384.0))] if rawSaturationPoint > 0.0: args += ['-S', str(int(rawSaturationPoint))] args += [imagePath] cmdargs = [cmd] cmdargs.extend(args) print( "\tCommand : %s" % " ".join(cmdargs) ) dcraw_emu_temp_file = "%s.tiff" % imageName process = sp.Popen(cmdargs, stderr=sp.STDOUT) process.wait() print( "\tMoving temp file to : %s" % temp_dir ) shutil.move( dcraw_emu_temp_file, temp_file ) #print( "Loading : %s" % temp_file ) imageBuffer = ImageBuf( temp_file ) # Just load the image using OIIO else: #print( "Using OIIO ImageBuf read route" ) imageBuffer = ImageBuf( imagePath ) return imageBuffer