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_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 save_img_using_oiio(img, fname, out_img_type_desc=oiio.UINT16, attr=None): """ OIIO を使った画像保存。 Parameters ---------- img : ndarray image data. fname : strings filename of the image. out_img_type_desc : oiio.desc type descripter of img attr : dictionary attribute parameters. Returns ------- - Examples -------- see ```_test_save_various_format()``` """ img_out = oiio.ImageOutput.create(fname) if not img_out: raise Exception("Error: {}".format(oiio.geterror())) out_img_spec = gen_out_img_spec(img, out_img_type_desc) set_img_spec_attribute(out_img_spec, attr) img_out.open(fname, out_img_spec) img_out.write_image(img) img_out.close()
def load_img_using_oiio(fname): """ OIIO を使った画像読込。 Parameters ---------- fname : strings filename of the image. Returns ------- img : ndarray image data. attr : dictionary attribute parameters for dpx. Examples -------- see ```_test_load_various_format()``` """ # データの読み込みテスト img_input = oiio.ImageInput.open(fname) if not img_input: raise Exception("Error: {}".format(oiio.geterror())) img_spec = img_input.spec() attr = get_img_spec_attribute(img_spec) typedesc = img_spec.format img_data = img_input.read_image(typedesc) return img_data, attr
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 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 find_min_max(filename, output='both'): inputFile = oiio.ImageInput.open(filename) if not inputFile: print 'Could not open: "' + filename + '"' print '\tError: "', oiio.geterror() return spec = inputFile.spec() nchans = spec.nchannels pixels = inputFile.read_image(oiio.FLOAT) if not pixels: print 'Could not read:', inputFile.geterror() return inputFile.close() #we're done with the file at this point minval = pixels[0:nchans] #initialize to the first pixel value maxval = pixels[0:nchans] i = 0 #absolute index for z in range(spec.depth): for y in range(spec.height): for x in range(spec.width): for c in range(nchans): if pixels[i + c] < minval[c]: minval[c] = pixels[i + c] if pixels[i + c] > maxval[c]: maxval[c] = pixels[i + c] i = i + nchans #advance the index if output == 'min': return minval elif output == 'max': return maxval else: return minval, maxval
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 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): print("@", (spec.x, y + spec.y), "=", data[0]) 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 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 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 _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 _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 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 convertImage(filename = '',fileOutName = '',format='tif'): # open the file inputFile = oiio.ImageInput.open(filename) # check if the input file is valid if not inputFile: print 'Could not open: "' + filename + '"' print '\tError: "', oiio.geterror() return # get the spec of the input file spec = inputFile.spec() nchans = spec.nchannels # read the image and return the pixels as array type pixels = inputFile.read_image(oiio.FLOAT) # check that the pixels are ok if not pixels: print 'Could not read:', inputFile.geterror() return inputFile.close() #we're done with the file at this point # open the OCIO config config = OCIO.GetCurrentConfig() #""" transform = OCIO.ColorSpaceTransform() transform.setSrc('srgb8') transform.setDst('acescg') #transform.setDirection(OCIO.Constants.TRANSFORM_DIR_INVERSE) processor = config.getProcessor(transform) #""" """ # get the processor to transform from srgb8 to acescg space processor = config.getProcessor('srgb8','acescg') #processor = config.getProcessor('linear','srgb8') """ # apply the transform buf = processor.applyRGBA(pixels) # convert the list to an array type imgTrans = array('f',[0,0,0,0]) imgTrans.fromlist(buf) # create an output image output = oiio.ImageOutput.create(fileOutName) # if tif format output as 16bit otherwise 8bit # if format != 'tif': # spec.set_format(oiio.UINT8) # else: # spec.set_format(oiio.UINT16) spec.set_format(oiio.HALF) # open and write the data transformed output.open(fileOutName,spec,oiio.Create) output.write_image(imgTrans) output.close() print 'done'
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 read_img_metadata(cls, img_file: Path) -> dict: img_buf = ImageBuf(img_file.as_posix()) img_dict = dict() if not img_buf: LOGGER.error(oiio.geterror()) return img_dict for param in img_buf.spec().extra_attribs: img_dict[param.name] = param.value cls.close_img_buf(img_buf, img_file) return img_dict
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
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 compareStereo(res={},rv=False): seqA = res['framePathCompoComp'] seqB = res['framePathCompoStereo'] cutIn = res['cutIn'] cutOut = res['cutOut'] path = _OUTPATH_+'/'+res['name']+'/' # delete the old files in the directory if os.path.isdir(path): files = glob.glob(path+'*') for f in files: os.remove(f) diff = False matchStatus = '\x1b[0;32;40m match\x1b[0m' wrongStatus = "\x1b[0;31;40m don't match\x1b[0m" print '\n\n\n\x1b[0;32;40m---Starting comparison for shot '+ res['name']+' of '+res['version compo_comp']+ ' compo_comp to '+res['version compo_stereo']+ ' compo_stereo for frame '+ str(cutIn)+' to frame '+str(cutOut)+'---\x1b[0m' for imNb in range(cutIn,cutOut+1): imLeft = False imLestStatus = '' frameNb = str(imNb).zfill(4) imgA = seqA.replace('%04d',frameNb) imgB= seqB.replace('%04d', frameNb) # test if images exist for im in [imgA,imgB]: test = oiio.ImageInput.open(im) if not test: print "\x1b[0;31;40m",oiio.geterror(),"\x1b[0m" exit(0) imLeft = doCompare(imgA,imgB,path) if imLeft: imLestStatus = matchStatus else: imLestStatus = wrongStatus diff = True print('for frame nb '+frameNb+ ' the images'+ imLestStatus) # if rv and diff: # print path # os.system('rv '+ path ) shotList = [seqA,seqB,path] return shotList,diff
def SetAsOpenedImage(self, path): """ Sets the image and opens it. :param path: image filepath to be opened """ try: # Open the image as an array img_input = oiio.ImageInput.open(path) if img_input == None: print("IO ERROR: ", oiio.geterror()) image = img_input.read_image(format="uint16") # Enforce RGBA if image.shape[2] == 3: self._img = cv2.cvtColor(image, cv2.COLOR_RGB2RGBA) else: self._img = image except FileNotFoundError: print("IO ERROR: COULD NOT OPEN IMAGE!")
def findMinMaxSingleChannel(filename='', output='both'): inputFile = oiio.ImageInput.open(filename) if not inputFile: print 'Could not open: "' + filename + '"' print '\tError: "', oiio.geterror() return spec = inputFile.spec() nchans = spec.nchannels # the read_image value 1 and 1 correspond to channel begin and channel end i.e we only read one channel pixels = inputFile.read_image(1, 1, oiio.FLOAT) if not pixels: print 'Could not read:', inputFile.geterror() return inputFile.close() #we're done with the file at this point minval = pixels[0:1] #initialize to the first pixel value maxval = pixels[0:1] i = 0 #absolute index #loops going throught the height and width of the frame for y in range(spec.height): for x in range(spec.width): if output == 'both': if pixels[i] < minval[0]: minval[0] = pixels[i] if pixels[i] > maxval[0]: maxval[0] = pixels[i] elif output == 'min': if pixels[i] < minval[0]: minval[0] = pixels[i] elif output == 'max': if pixels[i] > maxval[0]: maxval[0] = pixels[i] else: print 'wrong type of ouput' return i = i + 1 #advance the index if output == 'min': return minval[0] elif output == 'max': return maxval[0] else: return minval[0], maxval[0]
def compareStereo(res={}): seqA = res['framePathCOmpoStereo'] seqB = res['framePathCompoDi'] cutIn = res['cutIn'] cutOut = res['cutOut'] matchStatus = '\x1b[0;32;40m match\x1b[0m' wrongStatus = "\x1b[0;31;40m doesn't match\x1b[0m" print '\n\n\n\x1b[0;32;40m---Starting comparison for shot '+ res['name']+' of '+res['version comp_stereo']+ ' compo_stereo to '+res['version comp_di']+ ' compo_di for frame '+ str(cutIn)+' to frame '+str(cutOut)+'---\x1b[0m' # print 'comparing version: '+ res['version comp_stereo'] + ' of compo_stereo to version ' +res['version comp_di'] + ' of compo_di' # print 'checking from frame: '+ str(cutIn) + ' to frame: ' + str(cutOut) for imNb in range(cutIn,cutOut+1): imLeft = False imRight = False imLestStatus = '' imRightStatus ='' frameNb = str(imNb).zfill(4) imgA = seqA.replace('%04d',frameNb) imgB= seqB.replace('%04d', frameNb) imgARight = imgA.replace('left','right') imgBRight =imgB.replace('left','right') # test if images exist for im in [imgA,imgARight,imgB,imgBRight]: test = oiio.ImageInput.open(im) if not test: print "\x1b[0;31;40m",oiio.geterror(),"\x1b[0m" exit(0) imLeft = doCompare(imgA,imgB) imRight = doCompare(imgARight,imgBRight) if imLeft: imLestStatus = matchStatus else: imLestStatus = wrongStatus if imRight: imRightStatus = matchStatus else: imRightStatus = wrongStatus print('for frame nb '+frameNb+ ' the left images'+ imLestStatus+', the right images '+imRightStatus)
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 maketx(): Input = oiio.ImageBuf( "/s/prodanim/ta/assets/Character/huHuman/surface_texturing/surface_texturing/work/textures/testAces/huHuman_longSleevesShirt_smooth_1001_BaseColor.exr" ) config = oiio.ImageSpec() config.set_format(oiio.HALF) oiio.ImageBufAlgo.colorconvert(Input, Input, 'linear_srgb', 'Utility - sRGB - Texture') config.attribute("maketx:highlightcomp", 1) config.attribute("maketx:filtername", "lanczos3") config.attribute("maketx:opaque_detect", 1) config.attribute('maketx:forcefloat', 1) config.attribute('maketx:fileformatname', 'tx') config.attribute('maketx:incolorspace', 'srgb8') config.attribute('maketx:outcolorspace', 'acescg') Input.set_write_format(oiio.HALF) ok = oiio.ImageBufAlgo.make_texture( oiio.MakeTxTexture, Input, "/s/prodanim/ta/_sandbox/duda/tmp/crap/acescg_testC.tx", config) if not ok: print("error:", oiio.geterror())
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
####################################################### # 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()
def convertImage(filename=__FILEIN__, fileOutName=__FILEOUT__, format='tif'): # open the file inputFile = oiio.ImageInput.open(filename) # check if the input file is valid if not inputFile: print 'Could not open: "' + filename + '"' print '\tError: "', oiio.geterror() return # get the spec of the input file spec = inputFile.spec() nchans = spec.nchannels # read the image and return the pixels as array type pixels = inputFile.read_image(oiio.FLOAT) # check that the pixels are ok if not pixels: print 'Could not read:', inputFile.geterror() return inputFile.close() #we're done with the file at this point # open the OCIO config config = OCIO.GetCurrentConfig() # get the processor to transform from linear to Asterix2_Film space newConfig = OCIO.Config() colorspace = OCIO.ColorSpace(name='rawInput') group = OCIO.GroupTransform() main_lut = OCIO.FileTransform( '/s/prodanim/asterix2/_sandbox/duda/tmp/ocioLut/test.csp', interpolation=OCIO.Constants.INTERP_LINEAR, direction=OCIO.Constants.TRANSFORM_DIR_FORWARD) group.push_back(main_lut) colorspace.setTransform(group, OCIO.Constants.COLORSPACE_DIR_TO_REFERENCE) newConfig.addColorSpace(colorspace) colorspace = OCIO.ColorSpace(name='srgb8') group = OCIO.GroupTransform() main_lut = OCIO.FileTransform( '/s/prodanim/asterix2/_sandbox/duda/tmp/ocioLut/linTosrgbA2.csp', interpolation=OCIO.Constants.INTERP_LINEAR, direction=OCIO.Constants.TRANSFORM_DIR_FORWARD) group.push_back(main_lut) colorspace.setTransform(group, OCIO.Constants.COLORSPACE_DIR_TO_REFERENCE) newConfig.addColorSpace(colorspace) colorspace = OCIO.ColorSpace(name='processedOutput') newConfig.addColorSpace(colorspace) newProccessor = newConfig.getProcessor( 'rawInput', 'srgb8', ) # apply the transform buf = newProccessor.applyRGBA(pixels) #processor = config.getProcessor('Asterix2_Film','srgb8') #buf = processor.applyRGBA(pixels) # convert the list to an array type imgTrans = array('f', [0, 0, 0, 0]) imgTrans.fromlist(buf) # create an output image output = oiio.ImageOutput.create(__FILEOUT__) # if tif format output as 16bit otherwise 8bit if format != 'tif': spec.set_format(oiio.UINT8) else: spec.set_format(oiio.UINT16) # open and write the data transformed output.open(__FILEOUT__, spec, oiio.Create) output.write_image(imgTrans) output.close()
####################################################### # 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()
def _perform(self): """ Perform the task. """ import OpenImageIO as oiio import PyOpenColorIO as ocio sourceColorSpace = self.option('sourceColorSpace') targetColorSpace = self.option('targetColorSpace') metadata = { 'sourceColorSpace': sourceColorSpace, 'targetColorSpace': targetColorSpace } # open color io configuration config = self.ocioConfig() for crawler in self.crawlers(): # resolving the lut path lut = self.templateOption('lut', crawler=crawler) # adding color space transform groupTransform = ocio.GroupTransform() groupTransform.push_back( ocio.ColorSpaceTransform(src=sourceColorSpace, dst=targetColorSpace)) # adding lut transform groupTransform.push_back( ocio.FileTransform(lut, interpolation=ocio.Constants.INTERP_LINEAR)) # source image sourceImage = oiio.ImageInput.open(crawler.var('filePath')) spec = sourceImage.spec() spec.set_format(oiio.FLOAT) metadata['lutFile'] = lut pixels = sourceImage.read_image() sourceImage.close() transformedPixels = config.getProcessor(groupTransform).applyRGB( pixels) targetFilePath = 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) # centipede metadata information UpdateImageMetadata.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(FileColorTransformation, self)._perform()
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