def poor_mans_iinfo (filename) : input = oiio.ImageInput.open (filename) if not input : print 'Could not open "' + filename + '"' print "\tError: ", oiio.geterror() print return print 'Opened "' + filename + '" as a ' + input.format_name() sub = 0 mip = 0 while True : if sub > 0 or mip > 0 : print "Subimage", sub, "MIP level", mip, ":" print_imagespec (input.spec(), mip=mip) mip = mip + 1 if input.seek_subimage (sub, mip) : continue # proceed to next MIP level else : sub = sub + 1 mip = 0 if input.seek_subimage (sub, mip) : continue # proceed to next subimage break # no more MIP levels or subimages input.close () print
def test_readtile(filename, sub=0, mip=0, type=oiio.UNKNOWN): input = oiio.ImageInput.open(filename) if not input: print('Could not open "' + filename + '"') print("\tError: ", oiio.geterror()) print() return print('Opened "' + filename + '" as a ' + input.format_name()) input.seek_subimage(sub, mip) spec = input.spec() if spec.tile_width == 0: print("Error: not tiled") return if type == oiio.UNKNOWN: type = spec.format.basetype # Randomly read a couple of tiles, print a pixel from within it (tx, ty) = (spec.x, spec.y) data = input.read_tile(tx + spec.x, ty + spec.y, spec.z, type) if data is None: print("read returned None") return (x, y) = (tx + spec.tile_width // 2, ty + spec.tile_height // 2) print("@", (x, y), "=", data[y, x]) (tx, ty) = (spec.x + 2 * spec.tile_width, spec.y + 2 * spec.tile_height) data = input.read_tile(tx + spec.x, ty + spec.y, spec.z, type) print("@", (x, y), "=", data[y, x]) input.close() print()
def copy_image(in_filename, out_filename, method="image", memformat=oiio.TypeFloat, outformat=oiio.TypeUnknown): input = oiio.ImageInput.open(in_filename) if not input: print('Could not open "' + filename + '"') print("\tError: ", oiio.geterror()) print() return outspec = input.spec() if outformat != oiio.TypeUnknown: outspec.format = outformat output = oiio.ImageOutput.create(out_filename) if not output: print("Could not create ImageOutput for", out_filename) return ok = output.open(out_filename, outspec) if not ok: print("Could not open", out_filename) return ok = copy_subimage(input, output, method, memformat) input.close() output.close() if ok: print("Copied", in_filename, "to", out_filename, "as", method, "(memformat", memformat, "outformat", outformat, ")")
def test_readscanline(filename, sub=0, mip=0, type=oiio.UNKNOWN): input = oiio.ImageInput.open(filename) if not input: print('Could not open "' + filename + '"') print("\tError: ", oiio.geterror()) print() return print('Opened "' + filename + '" as a ' + input.format_name()) input.seek_subimage(sub, mip) spec = input.spec() if spec.tile_width != 0: print("Error: tiled") return if type == oiio.UNKNOWN: type = spec.format.basetype for y in range(spec.height): data = input.read_scanline(y + spec.y, spec.z, type) if data is None: print("read returned None") return # print the first pixel of the first and last scanline if y == 0 or y == (spec.height - 1): i = 0 * spec.nchannels print("@", (spec.x, y + spec.y), "=", data[i:i + spec.nchannels]) input.close() print()
def poor_mans_iinfo(filename): input = oiio.ImageInput.open(filename) if not input: print 'Could not open "' + filename + '"' print "\tError: ", oiio.geterror() print return print 'Opened "' + filename + '" as a ' + input.format_name() sub = 0 mip = 0 while True: if sub > 0 or mip > 0: print "Subimage", sub, "MIP level", mip, ":" print_imagespec(input.spec(), mip=mip) mip = mip + 1 if input.seek_subimage(sub, mip): continue # proceed to next MIP level else: sub = sub + 1 mip = 0 if input.seek_subimage(sub, mip): continue # proceed to next subimage break # no more MIP levels or subimages input.close() print
def test_readtile(filename, sub=0, mip=0, type=oiio.UNKNOWN): input = oiio.ImageInput.open(filename) if not input: print 'Could not open "' + filename + '"' print "\tError: ", oiio.geterror() print return print 'Opened "' + filename + '" as a ' + input.format_name() input.seek_subimage(sub, mip) spec = input.spec() if spec.tile_width == 0: print "Error: not tiled" return if type == oiio.UNKNOWN: type = spec.format.basetype # Randomly read a couple of tiles, print a pixel from within it (tx, ty) = (spec.x, spec.y) data = input.read_tile(tx + spec.x, ty + spec.y, spec.z, type) if data == None: print "read returned None" return (x, y) = (tx + spec.tile_width / 2, ty + spec.tile_height / 2) i = ((y - ty) * spec.tile_width + (x - tx)) * spec.nchannels print "@", (x, y), "=", data[i:i + spec.nchannels] (tx, ty) = (spec.x + 2 * spec.tile_width, spec.y + 2 * spec.tile_height) data = input.read_tile(tx + spec.x, ty + spec.y, spec.z, type) (x, y) = (tx + spec.tile_width / 2, ty + spec.tile_height / 2) i = ((y - ty) * spec.tile_width + (x - tx)) * spec.nchannels print "@", (x, y), "=", data[i:i + spec.nchannels] input.close() print
def ii_create_test(): print "Running ImageInput::create() tests..." spec = oiio.ImageSpec() #this is tested in ImageSpec test # test 1 pic1 = oiio.ImageInput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path) if pic1 == None: print "Test 1 failed: check your plugin path and whether you ran the script from <trunk>/src/python. The oiio-images folder is supposed to be in the same folder as <trunk>. \n This error will cause all the open_<something> and read_<something> tests to fail." else: print "Test 1 passed" # test 2 pic2 = oiio.ImageInput.create("", plugin_path) if pic2 == None: print "Test 2 passed" else: print "Test 2 error" # test 3 test3 = "failed" try: pic3 = oiio.ImageInput.create(3, plugin_path) except: test3 = "passed" print "Test 3", test3 # test 4 pic4 = oiio.ImageInput.create(plugin_path) if pic4 == None: print "Test 4 passed" else: print "Test 4 failed" print
def test_readtile (filename, sub=0, mip=0, type=oiio.UNKNOWN) : input = oiio.ImageInput.open (filename) if not input : print 'Could not open "' + filename + '"' print "\tError: ", oiio.geterror() print return print 'Opened "' + filename + '" as a ' + input.format_name() input.seek_subimage (sub, mip) spec = input.spec () if spec.tile_width == 0 : print "Error: not tiled" return if type == oiio.UNKNOWN : type = spec.format.basetype # Randomly read a couple of tiles, print a pixel from within it (tx,ty) = (spec.x, spec.y) data = input.read_tile (tx+spec.x, ty+spec.y, spec.z, type) if data == None : print "read returned None" return (x,y) = (tx+spec.tile_width/2, ty+spec.tile_height/2) i = ((y-ty)*spec.tile_width + (x-tx)) * spec.nchannels print "@", (x,y), "=", data[i:i+spec.nchannels] (tx,ty) = (spec.x+2*spec.tile_width, spec.y+2*spec.tile_height) data = input.read_tile (tx+spec.x, ty+spec.y, spec.z, type) (x,y) = (tx+spec.tile_width/2, ty+spec.tile_height/2) i = ((y-ty)*spec.tile_width + (x-tx)) * spec.nchannels print "@", (x,y), "=", data[i:i+spec.nchannels] input.close () print
def ii_open_test(): print "Running ImageInput::open() tests..." pic_o = oiio.ImageInput.create("../../../oiio-images/tahoe-gps.jpg", plugin_path) if pic_o == None: print "Can't open test image, skipping open() tests" print return spec_o = oiio.ImageSpec() #this is tested in ImageSpec test # test 1 if (pic_o.open("../../../oiio-images/tahoe-gps.jpg", spec_o)): print "Test 1 passed" else: print "Test 1 failed" # test 2 if (not pic_o.open("", spec_o)): print "Test 2 passed" else: print "Test 2 failed" # test 3 test3 = "failed" try: pic_o.open(spec_o) except: test3 = "passed" print "Test 3", test3 print
def test_readscanline (filename, sub=0, mip=0, type=oiio.UNKNOWN) : input = oiio.ImageInput.open (filename) if not input : print 'Could not open "' + filename + '"' print "\tError: ", oiio.geterror() print return print 'Opened "' + filename + '" as a ' + input.format_name() input.seek_subimage (sub, mip) spec = input.spec () if spec.tile_width != 0 : print "Error: tiled" return if type == oiio.UNKNOWN : type = spec.format.basetype for y in range(spec.height) : data = input.read_scanline (y+spec.y, spec.z, type) if data == None : print "read returned None" return # print the first pixel of the first and last scanline if y == 0 or y == (spec.height-1) : i = 0 * spec.nchannels print "@", (spec.x,y+spec.y), "=", data[i:i+spec.nchannels] input.close () print
def test_readtile (filename, sub=0, mip=0, type=oiio.UNKNOWN) : input = oiio.ImageInput.open (filename) if not input : print ('Could not open "' + filename + '"') print ("\tError: ", oiio.geterror()) print () return print ('Opened "' + filename + '" as a ' + input.format_name()) input.seek_subimage (sub, mip) spec = input.spec () if spec.tile_width == 0 : print ("Error: not tiled") return if type == oiio.UNKNOWN : type = spec.format.basetype # Randomly read a couple of tiles, print a pixel from within it (tx,ty) = (spec.x, spec.y) data = input.read_tile (tx+spec.x, ty+spec.y, spec.z, type) if data is None : print ("read returned None") return (x,y) = (tx+spec.tile_width//2, ty+spec.tile_height//2) print ("@", (x,y), "=", data[y,x]) (tx,ty) = (spec.x+2*spec.tile_width, spec.y+2*spec.tile_height) data = input.read_tile (tx+spec.x, ty+spec.y, spec.z, type) print ("@", (x,y), "=", data[y,x]) input.close () print ()
def frame_thread(self): stitch_args = None try: stitch_args = self.stitch_queue.get_nowait() except queue.Empty: pass while stitch_args: frame = stitch_args[0] tiles_path = Path(stitch_args[1]) images_path = Path(stitch_args[2]) frame_path = str(os.path.join(images_path, frame["outfile"])) print("Assembling frame {}".format(frame_path)) first_tile_path = os.path.join(tiles_path, frame["tiles"][0]["outfile"]) if os.path.isfile(first_tile_path): first_tile = oiio.ImageBuf(str(first_tile_path)) spec = first_tile.spec() frame_buf = oiio.ImageBuf( oiio.ImageSpec(frame["res_x"], frame["res_y"], spec.nchannels, spec.format)) for tile in frame["tiles"]: tile_path = os.path.join(tiles_path, tile["outfile"]) if not os.path.isfile(tile_path): continue tile_buf = oiio.ImageBuf(str(tile_path)) oiio.ImageBufAlgo.paste(frame_buf, tile["coords"][0], tile["coords"][1], 0, 0, tile_buf) print("Writing {}".format(frame_path)) try: os.mkdir(os.path.dirname(frame_path)) except FileExistsError: pass frame_buf.write(str(frame_path)) else: print("Could not find first tile. Aborting frame stitch") try: stitch_args = self.stitch_queue.get_nowait() except queue.Empty: print("Worker exiting") break
def _image_input(cls, img_file: Path): """ CLOSE the returned object after usage! """ img_input = oiio.ImageInput.open(img_file.as_posix()) if img_input is None: LOGGER.error('Error reading image: %s', oiio.geterror()) return return img_input
def oiio_get_buf(source, hash=None, force=False): """Check and load a source image with OpenImageIO's format reader. Args: source (str): Path to an OpenImageIO compatible image file. hash (str): Specify the hash manually, otherwise will be generated. force (bool): When `true`, forces the buffer to be re-cached. Returns: ImageBuf: An `ImageBuf` instance or `None` if the image cannot be read. """ common.check_type(source, str) if hash is None: hash = common.get_hash(source) if not force and ImageCache.contains(hash, BufferType): return ImageCache.value(hash, BufferType) # We use the extension to initiate an ImageInput with a format # which in turn is used to check the source's validity if '.' not in source: return None ext = source.split('.').pop().lower() if ext not in get_oiio_extensions(): return None i = OpenImageIO.ImageInput.create(ext) if not i or not i.valid_file(source): i.close() return None # If all went well, we can initiate an ImageBuf config = OpenImageIO.ImageSpec() config.format = OpenImageIO.TypeDesc(OpenImageIO.FLOAT) buf = OpenImageIO.ImageBuf() buf.reset(source, 0, 0, config=config) if buf.has_error: print(buf.geterror()) return None ImageCache.setValue(hash, buf, BufferType) return buf
def close_img_buf(img_buf, img_file: Union[Path, None] = None): try: img_buf.clear() del img_buf if img_file: oiio.ImageCache().invalidate(img_file.as_posix()) except Exception as e: LOGGER.error('Error closing img buf: %s', e)
def _perform(self): """ Perform the task. """ import OpenImageIO as oiio # open color io configuration config = self.ocioConfig() sourceColorSpace = self.option('sourceColorSpace') targetColorSpace = self.option('targetColorSpace') metadata = { 'sourceColorSpace': sourceColorSpace, 'targetColorSpace': targetColorSpace } for crawler in self.crawlers(): sourceImage = oiio.ImageInput.open( Crawler.Fs.Image.OiioCrawler.supportedString( crawler.var('filePath'))) spec = sourceImage.spec() spec.set_format(oiio.FLOAT) pixels = sourceImage.read_image() sourceImage.close() transformedPixels = config.getProcessor( sourceColorSpace, targetColorSpace).applyRGB(pixels) targetFilePath = Crawler.Fs.Image.OiioCrawler.supportedString( self.target(crawler)) # trying to create the directory automatically in case it does not exist try: os.makedirs(os.path.dirname(targetFilePath)) except OSError: pass targetImage = oiio.ImageOutput.create(targetFilePath) # kombi metadata information UpdateImageMetadataTask.updateDefaultMetadata( spec, crawler, metadata) success = targetImage.open(targetFilePath, spec, oiio.Create) # saving target image if success: writePixels = array('d') writePixels.fromlist(transformedPixels) targetImage.write_image(writePixels) else: raise Exception(oiio.geterror()) # default result based on the target filePath return super(ColorTransformationTask, self)._perform()
def write_image(image, filename): output = oiio.ImageOutput.create(filename) size = image.shape[0] spec_rgba = oiio.ImageSpec(size, size, 4, oiio.FLOAT) output.open(filename, spec_rgba, oiio.Create) # can't transform to rgb output.write_image(oiio.FLOAT, numpy.getbuffer(image)) output.close()
def process(self): path_p = self.input("path").receive() if path_p.isEOP(): return False self.output("image").send(OpenImageIO.ImageBuf(path_p.value())) path_p.drop() return True
def get_oiio_extensions(): """Returns a list of extensions accepted by OpenImageIO. """ v = OpenImageIO.get_string_attribute('extension_list') extensions = [] for e in [f.split(':')[1] for f in v.split(';')]: extensions += e.split(',') return sorted(extensions)
def tiles_from_heatmap(frame, depth, threshold, heatmap_dir): # Load rendered heatmap frame_path = os.path.join(heatmap_dir, frame["outfile"]) print("Frame path: {}".format(frame_path)) frame_buf = oiio.ImageBuf(str(os.path.join(heatmap_dir, frame["outfile"]))) orig_spec = oiio.ImageSpec(frame_buf.spec()) orig_spec.width = frame["res_x"] orig_spec.full_width = frame["res_x"] orig_spec.height = frame["res_y"] orig_spec.full_height = frame["res_y"] resized_frame_buf = oiio.ImageBuf(orig_spec) oiio.ImageBufAlgo.resize(resized_frame_buf, frame_buf) # Create tiles from resized images quadtree = QuadSplit(Rect(0, resized_frame_buf.spec().width, 0, resized_frame_buf.spec().height), 1, depth, ["raycount"], threshold) quadtree.test_image(resized_frame_buf) return quadtree.get_quads()
def test_deep(): # Test write and read of deep data # Let's try writing one print("\nWriting deep buffer...") deepbufout_spec = oiio.ImageSpec(2, 2, 5, oiio.FLOAT) deepbufout_spec.channelnames = ("R", "G", "B", "A", "Z") deepbufout_spec.deep = True deepbufout = oiio.ImageBuf(deepbufout_spec) deepbufout.set_deep_samples(x=1, y=0, z=0, nsamples=2) deepbufout.set_deep_value(x=1, y=0, z=0, channel=0, sample=0, value=0.42) deepbufout.set_deep_value(x=1, y=0, z=0, channel=4, sample=0, value=42.0) deepbufout.set_deep_value(x=1, y=0, z=0, channel=0, sample=1, value=0.47) deepbufout.set_deep_value(x=1, y=0, z=0, channel=4, sample=1, value=43.0) # Also insert some new samples deepbufout.deep_insert_samples(x=1, y=0, z=0, samplepos=1, nsamples=2) deepbufout.set_deep_value(x=1, y=0, z=0, channel=0, sample=1, value=1.1) deepbufout.set_deep_value(x=1, y=0, z=0, channel=1, sample=1, value=2.2) deepbufout.set_deep_value(x=1, y=0, z=0, channel=2, sample=1, value=2.3) deepbufout.set_deep_value(x=1, y=0, z=0, channel=3, sample=1, value=1.0) deepbufout.set_deep_value(x=1, y=0, z=0, channel=3, sample=1, value=42.25) deepbufout.set_deep_value(x=1, y=0, z=0, channel=0, sample=2, value=0.1) deepbufout.set_deep_value(x=1, y=0, z=0, channel=1, sample=2, value=0.2) deepbufout.set_deep_value(x=1, y=0, z=0, channel=2, sample=2, value=0.3) deepbufout.set_deep_value(x=1, y=0, z=0, channel=3, sample=2, value=1.0) deepbufout.set_deep_value(x=1, y=0, z=0, channel=3, sample=2, value=42.5) # But delete the first one deepbufout.deep_erase_samples(x=1, y=0, z=0, samplepos=1, nsamples=1) # Save deepbufout.write("deepbuf.exr") # And read it back print("\nReading back deep buffer:") deepbufin = oiio.ImageBuf("deepbuf.exr") deepbufin_spec = deepbufin.spec() dd = deepbufin.deepdata() for p in range(dd.pixels): ns = dd.samples(p) if ns > 1: print("Pixel", p // deepbufin_spec.width, p % deepbufin_spec.width, "had", ns, "samples") for s in range(ns): print("Sample", s) for c in range(dd.channels): print("\tc {0} : {1:.3f}".format(c, dd.deep_value(p, c, s)))
def main(): stage = Usd.Stage.CreateNew('CornField.usd') world = UsdGeom.Xform.Define(stage, '/World') _addCamera(stage) buf = oiio.ImageBuf('cropMap.png') spec = buf.spec() divisor = 1 width = spec.width / divisor depth = spec.height / divisor print("image dimensions {} {}".format(width, depth)) instancer = UsdGeom.PointInstancer.Define( stage, world.GetPath().AppendChild('TreePointInstance')) prototypesPrim = stage.DefinePrim( instancer.GetPath().AppendChild('prototypes')) prototypesPrimPath = prototypesPrim.GetPath() _addGround(stage, width, depth) models = ['corn.usd', 'crushedCorn.usd'] modelTargets = [] for m in models: modelTargets.append(_addModel(m, prototypesPrimPath, stage)) positions = [] indices = [] rotations = [] rot = Gf.Rotation() xstart = -width / 2.0 ystart = -depth / 2.0 print("x/y start {}{}".format(xstart, ystart)) for y in range(0, depth / divisor): for x in range(0, width / divisor): pixel = buf.getpixel(x, y) xpos = xstart + (x) + random.uniform(-0.2, 0.2) ypos = ystart + (y) + random.uniform(-0.2, 0.2) xpos = xpos * 0.3 ypos = ypos * 0.3 positions.append(Gf.Vec3f(xpos, 0, ypos)) rot = Gf.Rotation(Gf.Vec3d(0, 1, 0), random.uniform(0, 360)) r = rot.GetQuaternion().GetReal() img = rot.GetQuaternion().GetImaginary() rotations.append(Gf.Quath(r, img[0], img[1], img[2])) if pixel[0] > 0.0: indices.append(0) else: indices.append(1) instancer.CreatePositionsAttr(positions) instancer.CreateProtoIndicesAttr(indices) instancer.CreateOrientationsAttr(rotations) instancer.CreatePrototypesRel().SetTargets(modelTargets) stage.GetRootLayer().Save()
def test_readimage(filename, sub=0, mip=0, type=oiio.UNKNOWN, method="image", nchannels=0, print_pixels=True, keep_unknown=False): input = oiio.ImageInput.open(filename) if not input: print('Could not open "' + filename + '"') print("\tError: ", oiio.geterror()) print() return print('Opened "' + filename + '" as a ' + input.format_name()) input.seek_subimage(sub, mip) spec = input.spec() if nchannels == 0 or method == "image": nchannels = spec.nchannels if str(type) == "unknown" and not keep_unknown: type = spec.format.basetype if method == "image": data = input.read_image(type) elif method == "scanlines": data = input.read_scanlines(spec.y, spec.y + spec.height, spec.z, 0, nchannels, type) elif method == "tiles": data = input.read_tiles(spec.x, spec.x + spec.width, spec.y, spec.y + spec.height, spec.z, spec.z + spec.depth, 0, nchannels, type) else: print("Unknown method:", method) return if data is None: print("read returned None") return if print_pixels: # print the first, last, and middle pixel values (x, y) = (spec.x, spec.y) print("@", (x, y), "=", data[y, x]) (x, y) = (spec.x + spec.width - 1, spec.y + spec.height - 1) print("@", (x, y), "=", data[y, x]) (x, y) = (spec.x + spec.width // 2, spec.y + spec.height // 2) print("@", (x, y), "=", data[y, x]) else: print("Read array typecode", data.dtype, " [", data.size, "]") # Test the spec and spec_dimensions methods spec = input.spec_dimensions(0, 0) if len(spec.extra_attribs) > 0: print("wrong spec_dimensions(s,m) metadata items: ", len(spec.extra_attribs)) spec = input.spec(0, 0) if len(spec.extra_attribs) == 0: print("wrong spec(s,m) metadata items: ", len(spec.extra_attribs)) input.close() print()
def compare_image_pixels(self, result_image, correct_result_image, threshold): self.fail_test_if_no_oiio() """ Given a file to find it results, compare it against the correct result. Returns None if the input is not an image. Returns oiio.CompareResults if results can be compared. """ compresults = oiio.CompareResults() ImageBufAlgo.compare(result_image, correct_result_image, threshold, threshold, compresults) return compresults
def main(): image = "Tictactoe-X.png" buf = oiio.ImageBuf(image) if buf.spec().alpha_channel < 0: raise RuntimeError( f"{image} does not have an identifiable alpha channel") root = generate_x(buf) with open("x-tree.csv", "w") as out_f: output(root, out_f)
def minMaxOIIO(filename = '', output = 'both'): file = oiio.ImageBuf(filename) stats = oiio.ImageBufAlgo.computePixelStats(file) if output == 'min': return stats.min elif output == 'max': return stats.max else: return (stats.min,stats.max)
def shutdown(self): """ Release resources """ try: del self.metadata_cache del self.manifest_cache self.img.clear() del self.img oiio.ImageCache().invalidate(self.img_file.as_posix()) except Exception as e: LOGGER.error('Error closing img buf: %s', e)
def is_size_t_safe_test(): print "Running ImageSpec::size_t_safe tests..." spec = oiio.ImageSpec() # test 1 if spec.size_t_safe(): print "Test 1 passed" else: print "Test 1 failed" print
def is_init_test(): print "Starting ImageSpec constructors tests..." desc = oiio.TypeDesc() # test 1 spec1 = None spec1 = oiio.ImageSpec() # the default arg is TypeDesc::UNKNOWN if spec1 != None: print "Test 1 passed" else: print "Test 1 failed" # test 2 - give it a typedesc! spec2 = None try: spec2 = oiio.ImageSpec(desc) if spec2 != None: print "Test 2 passed" else: print "Test 2 failed (returns None)" except: print "Test 2 failed (raises argument mismatch exception)" # test 3 spec3 = None try: spec3 = oiio.ImageSpec(800, 600, 3, desc) if spec3 != None: print "Test 3 passed" else: print "Test 3 failed (returns None)" except: print "Test 3 failed (raises argument mismatch exception)" # test 4 test4 = "failed" a = "not a proper argument" try: spec4 = oiio.ImageSpec(a) except: test4 = "passed" print "Test 4", test4 print
def test_tiff_remembering_config(): # Create a file that has unassociated alpha print("Testing write and read of unassociated:") spec = oiio.ImageSpec(2, 2, 4, "float") spec.attribute("oiio:UnassociatedAlpha", 1) wbuf = oiio.ImageBuf(spec) oiio.ImageBufAlgo.fill(wbuf, (0.5, 0.5, 0.5, 0.5)) print(" writing: ", wbuf.get_pixels()) wbuf.write("test_unassoc.tif") rbuf = oiio.ImageBuf("test_unassoc.tif") print("\n default reading as IB: ", rbuf.get_pixels()) config = oiio.ImageSpec() config.attribute("oiio:UnassociatedAlpha", 1) rbuf = oiio.ImageBuf("test_unassoc.tif", 0, 0, config) print("\n reading as IB with unassoc hint: ", rbuf.get_pixels()) print("\n reading as II with hint, read scanlines backward: ") ii = oiio.ImageInput.open("test_unassoc.tif", config) print(" [1] = ", ii.read_scanline(1)) print(" [0] = ", ii.read_scanline(0)) print("\n")
def imgInfo(self,img): """ Returns the image width """ try: read=oiio.ImageInput.open(img) except: print "Bad image path -- please try again." return else: specs=oiio.ImageSpec(read.spec()) imageWidth = specs.width return imageWidth
def check_criteria(self, criteria, dirname, identifier, files): """Check that the passed files match the timecode and naming we're looking for. Alternatively it will attempt to match frame number against source_range :param criteria: `dict` containing regex and timecode tests :param dirname: str` with dirname of file location :param identifier: `str` filename with hashed frame number :param files: `list` of first and last file found :return: `bool` reflecting a match or not """ testname = 'timecode' for index, filename in enumerate(files): fullpath = os.path.join(dirname, filename) valid_path = criteria['regex'].search(fullpath) if not valid_path: return False buf = oiio.ImageBuf(fullpath) if buf.has_error: return False if index == 0: value = self.file_cache[dirname][identifier].setdefault( 'tc_in', get_timecode_str(buf)) self.file_cache[dirname][identifier].setdefault( 'fps', get_fps(buf)) else: value = get_timecode_str(buf) # No TimeCode found. Try using frame number if not value: testname = 'frames' try: if index == 0: value = self.file_cache[dirname][ identifier].setdefault( 'first_frame', int(frame_regex.search(filename).group())) else: value = int(frame_regex.search(filename).group()) except (ValueError, AttributeError): value = None func, test_value = criteria['tests'][testname][index] if not func(test_value, value): return False return True
def writeLayers( img=oiio.ImageBuf(), frameNb='0101', path='/tmp', channelDict={}): print 'writing layers for ' + path + ' frane number: ' + frameNb for key in sorted(channelDict.keys()): frameTmp = oiio.ImageBuf(img.spec()) oiio.ImageBufAlgo.channels(frameTmp, img, channelDict[key]) # create the path for the image and set it to be 8bit (suffisant for matte) shotPathLayer = path + '/' + key imageName = '/' + key + '.' + frameNb + '.exr' frameTmp.set_write_format(oiio.UINT8) # if it's the primary set the path and the output to be exr half float if key == 'd0': frameTmp.set_write_format(oiio.HALF) #frameTmp.set_write_tiles(0,0) shotPathLayer = path + '/primary' imageName = '/primary.' + frameNb + '.exr' # create the output path if it doesn't exist if not os.path.isdir(shotPathLayer): os.makedirs(shotPathLayer) frameTmp.write(shotPathLayer + imageName)
def ii_open_with_config_test(): # I don't know how config is supposed to act so I'm skipping this test for now print "Running ImageInput::open() (overload) tests..." print "Unimplemented yet" print pic_owc = oiio.ImageInput.create("../../../oiio-testimages/tahoe-gps.jpg", plugin_path) if pic_owc == None: print "Can't open test image, skipping open_with_config() tests" print return spec_owc = oiio.ImageSpec()
def oiioSupportsRaw(): ''' Check to see if raw files can be loaded natively ''' # Check to see if the raw plugin has been loaded format_list = oiio.get_string_attribute( "format_list" ).split(',') raw_plugin_present = 'raw' in format_list # Check to see if version is above when raw reading was fixed # Update this version number to reflect when the functionality is fixed version_great_enough = oiio.VERSION >= 10707 return (raw_plugin_present and version_great_enough)
def test_readimage (filename, sub=0, mip=0, type=oiio.UNKNOWN, method="image", nchannels=0, print_pixels = True, keep_unknown=False) : input = oiio.ImageInput.open (filename) if not input : print ('Could not open "' + filename + '"') print ("\tError: ", oiio.geterror()) print () return print ('Opened "' + filename + '" as a ' + input.format_name()) input.seek_subimage (sub, mip) spec = input.spec () if nchannels == 0 or method == "image" : nchannels = spec.nchannels if str(type) == "unknown" and not keep_unknown : type = spec.format.basetype if method == "image" : data = input.read_image (type) elif method == "scanlines" : data = input.read_scanlines (spec.y, spec.y+spec.height, spec.z, 0, nchannels, type) elif method == "tiles" : data = input.read_tiles (spec.x, spec.x+spec.width, spec.y, spec.y+spec.height, spec.z, spec.z+spec.depth, 0, nchannels, type) else : print ("Unknown method:", method) return if data is None : print ("read returned None") return if print_pixels : # print the first, last, and middle pixel values (x,y) = (spec.x, spec.y) print ("@", (x,y), "=", data[y,x]) (x,y) = (spec.x+spec.width-1, spec.y+spec.height-1) print ("@", (x,y), "=", data[y,x]) (x,y) = (spec.x+spec.width//2, spec.y+spec.height//2) print ("@", (x,y), "=", data[y,x]) else : print ("Read array typecode", data.dtype, " [", data.size, "]") # Test the spec and spec_dimensions methods spec = input.spec_dimensions (0, 0) if len(spec.extra_attribs) > 0 : print ("wrong spec_dimensions(s,m) metadata items: ", len(spec.extra_attribs)) spec = input.spec (0, 0) if len(spec.extra_attribs) == 0 : print ("wrong spec(s,m) metadata items: ", len(spec.extra_attribs)) input.close () print ()
def test_readimage (filename, sub=0, mip=0, type=oiio.UNKNOWN, method="image", nchannels=0, print_pixels = True, keep_unknown=False) : input = oiio.ImageInput.open (filename) if not input : print 'Could not open "' + filename + '"' print "\tError: ", oiio.geterror() print return print 'Opened "' + filename + '" as a ' + input.format_name() input.seek_subimage (sub, mip) spec = input.spec () if nchannels == 0 or method == "image" : nchannels = spec.nchannels if type == oiio.UNKNOWN and not keep_unknown : type = spec.format.basetype if method == "image" : data = input.read_image (type) elif method == "scanlines" : data = input.read_scanlines (spec.y, spec.y+spec.height, spec.z, 0, nchannels, type) elif method == "tiles" : data = input.read_tiles (spec.x, spec.x+spec.width, spec.y, spec.y+spec.height, spec.z, spec.z+spec.depth, 0, nchannels, type) else : print "Unknown method:", method return if data == None : print "read returned None" return if print_pixels : # print the first, last, and middle pixel values (x,y) = (spec.x, spec.y) i = ((y-spec.y)*spec.width + (x-spec.x)) * nchannels print "@", (x,y), "=", data[i:i+nchannels] (x,y) = (spec.x+spec.width-1, spec.y+spec.height-1) i = ((y-spec.y)*spec.width + (x-spec.x)) * nchannels print "@", (x,y), "=", data[i:i+nchannels] (x,y) = (spec.x+spec.width/2, spec.y+spec.height/2) i = ((y-spec.y)*spec.width + (x-spec.x)) * nchannels print "@", (x,y), "=", data[i:i+nchannels] else : print "Read array typecode", data.typecode, " [", len(data), "]" input.close () print
def copy_image (in_filename, out_filename, method="image") : input = oiio.ImageInput.open (in_filename) if not input : print 'Could not open "' + filename + '"' print "\tError: ", oiio.geterror() print return spec = input.spec () output = oiio.ImageOutput.create (out_filename) if not output : print "Could not create ImageOutput for", out_filename return ok = output.open (out_filename, spec, oiio.Create) if not ok : print "Could not open", out_filename return ok = copy_subimage (input, output, method) input.close () output.close () if ok : print "Copied", in_filename, "to", out_filename, "as", method
def copy_image (in_filename, out_filename, method="image", memformat=oiio.TypeFloat, outformat=oiio.TypeUnknown) : input = oiio.ImageInput.open (in_filename) if not input : print ('Could not open "' + filename + '"') print ("\tError: ", oiio.geterror()) print () return outspec = input.spec() if outformat != oiio.TypeUnknown : outspec.format = outformat output = oiio.ImageOutput.create (out_filename) if not output : print ("Could not create ImageOutput for", out_filename) return ok = output.open (out_filename, outspec) if not ok : print ("Could not open", out_filename) return ok = copy_subimage (input, output, method, memformat) input.close () output.close () if ok : print ("Copied", in_filename, "to", out_filename, "as", method)
def copy_image (in_filename, out_filename, method="image", memformat=oiio.FLOAT, outformat=oiio.UNKNOWN) : input = oiio.ImageInput.open (in_filename) if not input : print 'Could not open "' + filename + '"' print "\tError: ", oiio.geterror() print return outspec = input.spec () if (outformat != oiio.UNKNOWN) : outspec.format = oiio.TypeDesc(outformat) output = oiio.ImageOutput.create (out_filename) if not output : print "Could not create ImageOutput for", out_filename return ok = output.open (out_filename, outspec, oiio.Create) if not ok : print "Could not open", out_filename return ok = copy_subimage (input, output, method, memformat) input.close () output.close () if ok : print "Copied", in_filename, "to", out_filename, "as", method
print ("r == r2 (expect yes): ", (r == r2)) print ("r != r2 (expect no): ", (r != r2)) print ("r == r3 (expect no): ", (r == r3)) print ("r != r3 (expect yes): ", (r != r3)) print ("") print ("r contains (10,10) (expect yes): ", r.contains(10,10)) print ("r contains (1000,10) (expect no): ", r.contains(1000,10)) print ("r contains roi(10,20,10,20,0,1,0,1) (expect yes): ", r.contains(oiio.ROI(10,20,10,20,0,1,0,1))) print ("r contains roi(1010,1020,10,20,0,1,0,1) (expect no): ", r.contains(oiio.ROI(1010,1020,10,20,0,1,0,1))) A = oiio.ROI (0, 10, 0, 8, 0, 1, 0, 4) B = oiio.ROI (5, 15, -1, 10, 0, 1, 0, 4) print ("A =", A) print ("B =", B) print ("ROI.union(A,B) =", oiio.union(A,B)) print ("ROI.intersection(A,B) =", oiio.intersection(A,B)) print ("") spec = oiio.ImageSpec(640, 480, 3, oiio.UINT8) print ("Spec's roi is", oiio.get_roi(spec)) oiio.set_roi (spec, oiio.ROI(3, 5, 7, 9)) oiio.set_roi_full (spec, oiio.ROI(13, 15, 17, 19)) print ("After set, roi is", oiio.get_roi(spec)) print ("After set, roi_full is", oiio.get_roi_full(spec)) print ("") print ("Done.") except Exception as detail: print ("Unknown exception:", detail)
####################################################### # Create an exr file with deliberately missing tiles tilesize = 64 res = 256 tile = np.ones((tilesize,tilesize,3), dtype='float') * 0.75 spec = oiio.ImageSpec(res, res, 3, "half") spec.tile_width = tilesize spec.tile_height = tilesize spec.attribute('openexr:lineOrder', 'randomY') out = oiio.ImageOutput.create ('partial.exr') if not out : print ('Could not create ImageOutput: ', oiio.geterror()) ok = out.open ('partial.exr', spec) if not ok : print ('Could not open file: ', out.geterror()) count = 0 for y in range(0,res,tilesize) : for x in range(0,res,tilesize) : # Skip every 7th tile if (count % 7) > 1 : ok = out.write_tile (x, y, 0, tile) if not ok : print ('Could not write tile y={} x={}: {}'.format(y, x, out.geterror())) count += 1 out.close()
print "getattribute('foo_str') retrieves", s.getattribute("foo_str") print "getattribute('foo_vector') retrieves", s.getattribute("foo_vector") print "getattribute('foo_matrix') retrieves", s.getattribute("foo_matrix") print "getattribute('foo_no') retrieves", s.getattribute("foo_no") print print "extra_attribs size is", len(s.extra_attribs) for i in range(len(s.extra_attribs)) : print i, s.extra_attribs[i].name, s.extra_attribs[i].type, s.extra_attribs[i].value print s.metadata_val (s.extra_attribs[i], True) print # test initialization from ROI print ("Testing construction from ROI:") sroi = oiio.ImageSpec (oiio.ROI(0,640,0,480,0,1,0,3), oiio.FLOAT); print_imagespec (sroi) # Also test global OIIO functions here print "\nTesting global attribute store/retrieve:" oiio.attribute ("plugin_searchpath", "perfect") print "get_string_attribute plugin_searchpath : ", oiio.get_string_attribute ("plugin_searchpath", "bad") print "get_int_attribute plugin_searchpath : ", oiio.get_int_attribute ("plugin_searchpath", 0) print "getattribute TypeString plugin_searchpath : ", oiio.getattribute ("plugin_searchpath", oiio.TypeDesc.TypeString) print "getattribute TypeFloat plugin_searchpath : ", oiio.getattribute ("plugin_searchpath", oiio.TypeDesc.TypeFloat) print "getattribute TypeString blahblah : ", oiio.getattribute ("blahblah", oiio.TypeDesc.TypeString) print "Done." except Exception as detail: print "Unknown exception:", detail
def get_stats_from_image(filename): import math # TODO: Migrate it outside callbacks.py try: import OpenImageIO as oiio except: print "Cant' find OpenImageIO." return None source = oiio.ImageInput.open(str(filename)) if not source: print oiio.geterror() return spec = source.spec() info = [] info.append(["resolution", (spec.width, spec.height, spec.x, spec.y)]) info.append(["channels: ", spec.channelnames]) info.append(["format", str(spec.format)]) if spec.channelformats : info.append(["channelformats", str(spec.channelformats)]) info.append(["alpha channel", str(spec.alpha_channel)]) info.append(["z channel", str(spec.z_channel)]) info.append(["deep", str(spec.deep)]) for i in range(len(spec.extra_attribs)): if type(spec.extra_attribs[i].value) == str: info.append([spec.extra_attribs[i].name, spec.extra_attribs[i].value]) else: info.append([spec.extra_attribs[i].name, spec.extra_attribs[i].value]) source.close () return info