def register(self, constraints=None, transform=None): if transform is None: t=ird.similarity(self.pm.R0, self.I0zcn, numiter=3, constraints=constraints) transform = { your_key: t[your_key] for your_key in ['angle','scale','tvec'] } self.transform=transform self.I0T=ird.transform_img_dict(self.I0zcn, self.transform) self.data=ird.transform_img_dict(self.I1zcf, self.transform)
def register(self, constraints=None, transform=None): if transform is None: t=ird.similarity(self.R0, self.R1, numiter=3, constraints=constraints) transform = { your_key: t[your_key] for your_key in ['angle','scale','tvec'] } self.transform=transform self.RT=ird.transform_img_dict(self.R1, self.transform) self.BT=ird.transform_img_dict(self.B1, self.transform) self.ST=ird.transform_img_dict(self.S1, self.transform)
def register(self, constraints=None, transform=None): if transform is None: t = ird.similarity(self.pm.R0, self.I0zcn, numiter=3, constraints=constraints) transform = { your_key: t[your_key] for your_key in ['angle', 'scale', 'tvec'] } self.transform = transform self.I0T = ird.transform_img_dict(self.I0zcn, self.transform) self.data = ird.transform_img_dict(self.I1zcf, self.transform)
def register(self, constraints=None, transform=None): if transform is None: t = ird.similarity(self.R0, self.R1, numiter=3, constraints=constraints) transform = { your_key: t[your_key] for your_key in ['angle', 'scale', 'tvec'] } self.transform = transform self.RT = ird.transform_img_dict(self.R1, self.transform) self.BT = ird.transform_img_dict(self.B1, self.transform) self.ST = ird.transform_img_dict(self.S1, self.transform)
def process_tile(ii, reports=None): global _SUCCS, _SHIFTS, _ANGLES, _SCALES, _DIFFS tile = _TILES[ii] image = _IMAGE opts = _OPTS pos = _POSS[ii] try: # TODO: Add unittests that zero success result # doesn't influence anything with reporting.report_wrapper(reports, ii) as wrapped: resdict = process_images((tile, image), opts, reports=wrapped) resdict['tvec'] += pos if np.isnan(_DIFFS[0]): _DIFFS[0] = resdict["Dangle"] _DIFFS[1] = resdict["Dscale"] _DIFFS[2] = resdict["Dt"] except ValueError: # probably incompatible images due to high scale change, so we # just add some harmless stuff here and proceed. resdict = dict(success=0) _distribute_resdict(resdict, ii) _SUCCS[ii] = resdict["success"] if _SUCCS[ii] > 0: # print("%d: succ: %g" % (ii, resdict["success"])) # import pylab as pyl resdict["tvec"] -= pos tosa = ird.transform_img_dict(image, resdict, 0, opts["order"]) tosa = utils.unextend_by(tosa, opts["extend"])
def _get_resdict(imgs, opts, tosa=None): import numpy as np reports = None # reports = dict() tiledim = None if opts["tile"]: shapes = np.array([np.array(img.shape) for img in imgs]) if (shapes[0] / shapes[1]).max() > 1.7: tiledim = np.min(shapes, axis=0) * 1.1 # TODO: Establish a translate region constraint of width tiledim * coef if tiledim is not None: resdict = ird.tiles.settle_tiles(imgs, tiledim, opts, reports) if tosa is not None: tosa[:] = ird.transform_img_dict(tosa, resdict) else: resdict = ird.tiles.process_images(imgs, opts, tosa, True, reports=reports) return resdict
def _get_resdict(imgs, opts, tosa=None): import numpy as np reports = opts.get("reports", None) tiledim = None if opts["tile"]: shapes = np.array([np.array(img.shape) for img in imgs]) if (shapes[0] / shapes[1]).max() > 1.7: tiledim = np.min(shapes, axis=0) * 1.1 # TODO: Establish a translate region constraint of width tiledim * coef if tiledim is not None: resdict = tiles.settle_tiles(imgs, tiledim, opts, reports) # TODO: This "tosa" occurence is convoluted - it is not needed # in process_images if tosa is not None: tosa[:] = ird.transform_img_dict(tosa, resdict) else: resdict = tiles.process_images(imgs, opts, tosa, True, reports=reports) if reports is not None: reports.set_global("aspect", imgs[0].shape[1] / float(imgs[0].shape[0])) return resdict
def process_images(ims, opts, tosa=None, get_unextended=False, reports=None): """ Args: tosa (np.ndarray): An array where to save the transformed subject. get_unextended (bool): Whether to get the transformed subject in the same shape and coord origin as the template. """ # lazy import so no imports before run() is really called from imreg_dft import imreg rcoef = opts["resample"] ims = _preprocess_extend(ims, opts["extend"], opts["low"], opts["high"], opts["cut"], rcoef) """ if reports is not None: reports["processed-0"] = ims """ resdict = imreg._similarity(ims[0], ims[1], opts["iters"], opts["order"], opts["constraints"], opts["filter_pcorr"], opts["exponent"], reports=reports) if reports is not None and reports.show("inputs", "translation", "scale_angle", "transformed"): reports["aspect"] = ims[0].shape[1] / float(ims[0].shape[0]) # reporting.report_tile(reports, "reports", aspect) # Seems that the reampling simply scales the translation resdict["Dt"] /= rcoef ty, tx = resdict["tvec"] resdict["tx"] = tx resdict["ty"] = ty resdict["imgs"] = ims tform = resdict if tosa is not None: tosa[:] = ird.transform_img_dict(tosa, tform) if get_unextended: im2 = imreg.transform_img_dict(ims[1], resdict, order=opts["order"]) resdict["unextended"] = _postprocess_unextend(ims, im2, opts["extend"]) # We need this intact until now (for the transform above) resdict["tvec"] /= rcoef return resdict
def process_images(ims, opts, tosa=None): # lazy import so no imports before run() is really called import numpy as np from imreg_dft import utils from imreg_dft import imreg ims = [utils.extend_by(img, opts["extend"]) for img in ims] bigshape = np.array([img.shape for img in ims]).max(0) ims = filter_images(ims, opts["low"], opts["high"]) rcoef = opts["resample"] if rcoef != 1: ims = [resample(img, rcoef) for img in ims] bigshape *= rcoef # Make the shape of images the same ims = [ utils.embed_to(np.zeros(bigshape) + utils.get_borderval(img, 5), img) for img in ims ] resdict = imreg.similarity(ims[0], ims[1], opts["iters"], opts["order"], opts["constraints"], opts["filter_pcorr"], opts["exponent"]) im2 = resdict.pop("timg") # Seems that the reampling simply scales the translation resdict["tvec"] /= rcoef ty, tx = resdict["tvec"] resdict["tx"] = tx resdict["ty"] = ty resdict["imgs"] = ims tform = resdict if tosa is not None: tosa[:] = ird.transform_img_dict(tosa, tform) if rcoef != 1: ims = [resample(img, 1.0 / rcoef) for img in ims] im2 = resample(im2, 1.0 / rcoef) resdict["Dt"] /= rcoef resdict["unextended"] = [ utils.unextend_by(img, opts["extend"]) for img in ims + [im2] ] return resdict
def process_images(ims, opts, tosa=None, get_unextended=False, reports=None): """ Args: tosa (np.ndarray): An array where to save the transformed subject. get_unextended (bool): Whether to get the transformed subject in the same shape and coord origin as the template. """ # lazy import so no imports before run() is really called from imreg_dft import imreg rcoef = opts["resample"] ims = _preprocess_extend(ims, opts["extend"], opts["low"], opts["high"], opts["cut"], rcoef) """ if reports is not None: reports["processed-0"] = ims """ resdict = imreg._similarity( ims[0], ims[1], opts["iters"], opts["order"], opts["constraints"], opts["filter_pcorr"], opts["exponent"], reports=reports) if reports is not None and reports.show( "inputs", "translation", "scale_angle", "transformed"): reports["aspect"] = ims[0].shape[1] / float(ims[0].shape[0]) # reporting.report_tile(reports, "reports", aspect) # Seems that the reampling simply scales the translation resdict["Dt"] /= rcoef ty, tx = resdict["tvec"] resdict["tx"] = tx resdict["ty"] = ty resdict["imgs"] = ims tform = resdict if tosa is not None: tosa[:] = ird.transform_img_dict(tosa, tform) if get_unextended: im2 = imreg.transform_img_dict(ims[1], resdict, order=opts["order"]) resdict["unextended"] = _postprocess_unextend(ims, im2, opts["extend"]) # We need this intact until now (for the transform above) resdict["tvec"] /= rcoef return resdict
def process_images(ims, opts, tosa=None): # lazy import so no imports before run() is really called import numpy as np from imreg_dft import utils from imreg_dft import imreg ims = [utils.extend_by(img, opts["extend"]) for img in ims] bigshape = np.array([img.shape for img in ims]).max(0) ims = filter_images(ims, opts["low"], opts["high"]) rcoef = opts["resample"] if rcoef != 1: ims = [resample(img, rcoef) for img in ims] bigshape *= rcoef # Make the shape of images the same ims = [utils.embed_to(np.zeros(bigshape) + utils.get_borderval(img, 5), img) for img in ims] resdict = imreg.similarity( ims[0], ims[1], opts["iters"], opts["order"], opts["constraints"], opts["filter_pcorr"], opts["exponent"]) im2 = resdict.pop("timg") # Seems that the reampling simply scales the translation resdict["tvec"] /= rcoef ty, tx = resdict["tvec"] resdict["tx"] = tx resdict["ty"] = ty resdict["imgs"] = ims tform = resdict if tosa is not None: tosa[:] = ird.transform_img_dict(tosa, tform) if rcoef != 1: ims = [resample(img, 1.0 / rcoef) for img in ims] im2 = resample(im2, 1.0 / rcoef) resdict["Dt"] /= rcoef resdict["unextended"] = [utils.unextend_by(img, opts["extend"]) for img in ims + [im2]] return resdict
def transform_images(self): self.RT=ird.transform_img_dict(self.R1, self.transform) self.DT=ird.transform_img_dict(self.D1, self.transform)
def settle_tiles(imgs, tiledim, opts, reports=None): global _SHIFTS coef = 0.41 coef = 0.81 img0 = imgs[0] tiles, poss = zip(* ird.utils.decompose(img0, tiledim, coef)) nrows, ncols = utils.starts2dshape(poss) _fill_globals(tiles, poss, imgs[1], opts) for ii, pos in enumerate(poss): process_tile(ii, reports) tile_coord = (ii // ncols, ii % ncols) if reports is not None and reports.show("tile_info"): shape = (nrows, ncols) slices = utils.getSlices(img0.shape, tiledim, coef) reports.set_global("tiles-whole", img0) reports.set_global("tiles-shape", shape) reports.set_global("tiles-successes", _SUCCS) reports.set_global("tiles-decomp", slices) """ if ncores == 0: # no multiprocessing (to see errors) _seg_init(mesh, dims, counter) data = map(_get_prep, allranges) else: pool = mp.Pool( processes=ncores, initializer=_seg_init, initargs=(mesh, dims, counter), ) res = pool.map_async(_get_prep, allranges) pool.close() while not res.ready(): reporter.update(counter.value) time.sleep(sleeptime) assert res.successful(), \ "Some exceptions have likely occured" data = res.get() """ tosa_offset = np.array(img0.shape)[:2] - np.array(tiledim)[:2] + 0.5 _SHIFTS -= tosa_offset / 2.0 # Get the cluster of the tiles that have similar results and that look # most promising along with the index of the best tile cluster, amax = utils.get_best_cluster(_SHIFTS, _SUCCS, 5) # Make the quantities estimation even more precise by taking # the average of all good tiles shift, angle, scale, score = utils.get_values( cluster, _SHIFTS, _SUCCS, _ANGLES, _SCALES) resdict = _assemble_resdict(amax) resdict["scale"] = scale resdict["angle"] = angle resdict["tvec"] = shift resdict["ty"], resdict["tx"] = resdict["tvec"] bgval = utils.get_borderval(imgs[1], 5) ims = _preprocess_extend(imgs, opts["extend"], opts["low"], opts["high"], opts["cut"], opts["resample"]) im2 = ird.transform_img_dict(ims[1], resdict, bgval, opts["order"]) # TODO: This is kinda dirty resdict["unextended"] = _postprocess_unextend(ims, im2, opts["extend"]) resdict["Dangle"], resdict["Dscale"], resdict["Dt"] = _DIFFS return resdict
ax[0].set_title('Green Transformed') ax[1].imshow(redSlice, cmap='Reds_r') ax[1].set_title('Red') ax[2].imshow(imRGB_t) ax[2].set_title('Transformed Overlay') for path in pathList: image_file = path + Filename # Load the image file: img_to_convert = io.imread(image_file) # Extract the red and green parts of the image greenSlice2 = (img_to_convert[0:256, 0:512]).astype('uint16') redSlice2 = (img_to_convert[256:512, 0:512]).astype('uint16') newresult = ird.transform_img_dict(greenSlice2, result, bgval=None, order=1, invert=False).astype('uint16') im = Image.fromarray(newresult) im.save(path + 'green_trans.tif') im2 = Image.fromarray(greenSlice2) im2.save(path + 'green.tif') im3 = Image.fromarray(redSlice2) im3.save(path + 'red.tif')
def _get_resdict(imgs, opts, tosa=None): import numpy as np tiledim = None if opts["tile"]: shapes = np.array([np.array(img.shape) for img in imgs]) if (shapes[0] / shapes[1]).max() > 1.7: tiledim = np.min(shapes, axis=0) * 1.1 # TODO: Establish a translate region constraint of width tiledim * coef if tiledim is not None: tiles = ird.utils.decompose(imgs[0], tiledim, 0.35) resdicts = [] shifts = np.zeros((len(tiles), 2), float) succs = np.zeros(len(tiles), float) angles = np.zeros(len(tiles), float) scales = np.zeros(len(tiles), float) for ii, (tile, pos) in enumerate(tiles): try: # TODO: Add unittests that zero success result # doesn't influence anything resdict = process_images((tile, imgs[1]), opts, None) angles[ii] = resdict["angle"] scales[ii] = resdict["scale"] shifts[ii] = np.array((resdict["ty"], resdict["tx"])) + pos except ValueError: # probably incompatible images due to high scale change, so we # just add some harmless stuff here and proceed. resdict = dict(success=0) resdicts.append(resdict) succs[ii] = resdict["success"] if 0: print(ii, succs[ii]) import pylab as pyl pyl.figure() pyl.imshow(tile) pyl.show() tosa_offset = np.array(imgs[0].shape)[:2] - np.array(tiledim)[:2] + 0.5 shifts -= tosa_offset / 2.0 # Get the cluster of the tiles that have similar results and that look # most promising along with the index of the best tile cluster, amax = utils.get_best_cluster(shifts, succs, 5) # Make the quantities estimation even more precise by taking # the average of all good tiles shift, angle, scale, score = utils.get_values(cluster, shifts, succs, angles, scales) resdict = resdicts[amax] resdict["scale"] = scale resdict["angle"] = angle resdict["tvec"] = shift resdict["ty"], resdict["tx"] = resdict["tvec"] # In non-tile cases, tosa is transformed in process_images if tosa is not None: tosa = ird.transform_img_dict(tosa, resdict) else: resdict = process_images(imgs, opts, tosa) return resdict
def process_images(ims, opts, tosa=None, get_unextended=False, reports=None): # lazy import so no imports before run() is really called from imreg_dft import imreg rcoef = opts["resample"] ims = _preprocess_extend(ims, opts["extend"], opts["low"], opts["high"], opts["cut"], rcoef) if reports is not None: reports["processed-0"] = ims resdict = imreg._similarity(ims[0], ims[1], opts["iters"], opts["order"], opts["constraints"], opts["filter_pcorr"], opts["exponent"], reports=reports) if reports is not None: import pylab as pyl fig = pyl.figure() for key, value in reports.items(): if "ims-filt" in key: for ii, im in enumerate(value): pyl.clf() pyl.title("filtered") pyl.imshow(im.real, cmap=pyl.cm.hot) pyl.colorbar() pyl.savefig("%s-%d.png" % (key, ii)) if "dfts-filt" in key: for ii, im in enumerate(value): pyl.clf() pyl.title("log abs dfts") pyl.imshow(np.log(np.abs(im)), cmap=pyl.cm.hot) pyl.colorbar() pyl.savefig("%s-%d.png" % (key, ii)) if "logpolars" in key: for ii, im in enumerate(value): pyl.clf() pyl.title("log abs log-ploar") pyl.imshow(np.log(np.abs(im)), cmap=pyl.cm.hot) pyl.colorbar() pyl.savefig("%s-%d.png" % (key, ii)) if "amt-orig" in key: pyl.clf() pyl.title("log abs pcorr") pyl.imshow(np.log(np.abs(value)), cmap=pyl.cm.hot) pyl.colorbar() pyl.savefig("%s-%d.png" % (key, ii)) reports.pop(key) del fig # Seems that the reampling simply scales the translation resdict["Dt"] /= rcoef ty, tx = resdict["tvec"] resdict["tx"] = tx resdict["ty"] = ty resdict["imgs"] = ims tform = resdict if tosa is not None: tosa[:] = ird.transform_img_dict(tosa, tform) if get_unextended: im2 = imreg.transform_img_dict(ims[1], resdict, order=opts["order"]) if rcoef != 1: ims = [resample(img, 1.0 / rcoef) for img in ims] im2 = resample(im2, 1.0 / rcoef) resdict["unextended"] = _postprocess_unextend(ims, im2, opts["extend"]) # We need this for the transform above resdict["tvec"] /= rcoef return resdict
def settle_tiles(imgs, tiledim, opts, reports=None): global _SHIFTS coef = 0.41 img0 = imgs[0] tiles, poss = zip(* ird.utils.decompose(img0, tiledim, coef)) nrows, ncols = utils.starts2dshape(poss) _fill_globals(tiles, poss, imgs[1], opts) for ii, pos in enumerate(poss): process_tile(ii, reports) tile_coord = (ii // ncols, ii % ncols) """ if ncores == 0: # no multiprocessing (to see errors) _seg_init(mesh, dims, counter) data = map(_get_prep, allranges) else: pool = mp.Pool( processes=ncores, initializer=_seg_init, initargs=(mesh, dims, counter), ) res = pool.map_async(_get_prep, allranges) pool.close() while not res.ready(): reporter.update(counter.value) time.sleep(sleeptime) assert res.successful(), \ "Some exceptions have likely occured" data = res.get() """ tosa_offset = np.array(img0.shape)[:2] - np.array(tiledim)[:2] + 0.5 _SHIFTS -= tosa_offset / 2.0 # Get the cluster of the tiles that have similar results and that look # most promising along with the index of the best tile cluster, amax = utils.get_best_cluster(_SHIFTS, _SUCCS, 5) # Make the quantities estimation even more precise by taking # the average of all good tiles shift, angle, scale, score = utils.get_values( cluster, _SHIFTS, _SUCCS, _ANGLES, _SCALES) if reports is not None and reports.show("tile_info"): shape = (nrows, ncols) slices = utils.getSlices(img0.shape, tiledim, coef) reports.set_global("tiles-whole", img0) reports.set_global("tiles-shape", shape) reports.set_global("tiles-cluster", cluster) reports.set_global("tiles_successes", _SUCCS) reports.set_global("tiles_decomp", slices) resdict = _assemble_resdict(amax) resdict["scale"] = scale resdict["angle"] = angle resdict["tvec"] = shift resdict["ty"], resdict["tx"] = resdict["tvec"] bgval = utils.get_borderval(imgs[1], 5) ims = _preprocess_extend(imgs, opts["extend"], opts["low"], opts["high"], opts["cut"], opts["resample"]) im2 = ird.transform_img_dict(ims[1], resdict, bgval, opts["order"]) # TODO: This is kinda dirty resdict["unextended"] = _postprocess_unextend(ims, im2, opts["extend"]) resdict["Dangle"], resdict["Dscale"], resdict["Dt"] = _DIFFS return resdict
def _get_resdict(imgs, opts, tosa=None): import numpy as np tiledim = None if opts["tile"]: shapes = np.array([np.array(img.shape) for img in imgs]) if (shapes[0] / shapes[1]).max() > 1.7: tiledim = np.min(shapes, axis=0) * 1.1 # TODO: Establish a translate region constraint of width tiledim * coef if tiledim is not None: tiles = ird.utils.decompose(imgs[0], tiledim, 0.35) resdicts = [] shifts = np.zeros((len(tiles), 2), float) succs = np.zeros(len(tiles), float) angles = np.zeros(len(tiles), float) scales = np.zeros(len(tiles), float) for ii, (tile, pos) in enumerate(tiles): try: # TODO: Add unittests that zero success result # doesn't influence anything resdict = process_images((tile, imgs[1]), opts, None) angles[ii] = resdict["angle"] scales[ii] = resdict["scale"] shifts[ii] = np.array((resdict["ty"], resdict["tx"])) + pos except ValueError: # probably incompatible images due to high scale change, so we # just add some harmless stuff here and proceed. resdict = dict(success=0) resdicts.append(resdict) succs[ii] = resdict["success"] if 0: print(ii, succs[ii]) import pylab as pyl pyl.figure(); pyl.imshow(tile) pyl.show() tosa_offset = np.array(imgs[0].shape)[:2] - np.array(tiledim)[:2] + 0.5 shifts -= tosa_offset / 2.0 # Get the cluster of the tiles that have similar results and that look # most promising along with the index of the best tile cluster, amax = utils.get_best_cluster(shifts, succs, 5) # Make the quantities estimation even more precise by taking # the average of all good tiles shift, angle, scale, score = utils.get_values( cluster, shifts, succs, angles, scales) resdict = resdicts[amax] resdict["scale"] = scale resdict["angle"] = angle resdict["tvec"] = shift resdict["ty"], resdict["tx"] = resdict["tvec"] # In non-tile cases, tosa is transformed in process_images if tosa is not None: tosa = ird.transform_img_dict(tosa, resdict) else: resdict = process_images(imgs, opts, tosa) return resdict