def show(title, nuclei, radius, bounds, scale=1.0): points = [RealPoint.wrap([c * scale for c in coords]) for coords in nuclei] interval = FinalInterval([int(b * scale) for b in bounds[0]], [int(b * scale) for b in bounds[1]]) img = virtualPointsRAI(points, radius * scale, interval) imp = showStack(img, title=title) return imp, img, points
def findNucleiByMaxProjection(img4D, params, img3D_filepath, projection_strategy="1by1", mask=None, show=True): """ img4D: the 4D series to max-project and then detect nuclei in. params: for difference of Gaussian to detect somas. img3D: optional, provide a ready-made max projection. projection_strategy: defaults to "1by1". See maxProjectLastDimension. mask: defaults to None, can be a 3D image (a RandomAccesibleInterval of 3 dimensions) used to filter nuclei detections by whether their coordinates have a non-zero value. show: defaults to True, and if so opens a 3D volume showing the nuclei as white spheres. """ if not os.path.exists(img3D_filepath): print "Will max project 4D to 3D" img3D = maxProjectLastDimension(img4D, strategy=projection_strategy) writeZip(img3D, img3D_filepath, title=os.path.basename(img3D_filepath)) else: print "Loading max projection" img3D = ImageJLoader().get(img3D_filepath) peaks = doGPeaks(img3D, params) if mask: ra = mask.randomAccess() def isNonZero(peak): ra.setPosition(peak) return 0 != ra.get().get() peaks = filter(isNonZero, peaks) if show: spheresRAI = virtualPointsRAI(peaks, params["somaDiameter"] / 2.0, img3D) imp = showStack(spheresRAI, title="nuclei by max projection") return img3D, peaks, spheresRAI, imp else: return img3D, peaks
def findNucleiOverTime(img4D, params, show=True): """ params["frames"]: number of time frames to average params["calibration"]: e.g. [1.0, 1.0, 1.0] params["somaDiameter"]: width of a soma, in pixels params["minPeakValue"]: determine it by hand with e.g. difference of Gaussians sigma=somaDiameter/4 minus sigma=somaDiameter/2 params["sigmaSmaller"]: for difference of Gaussian to detect somas. Recommended somaDiameter / 4.0 -- in pixels params["sigmaLarger"]: for difference of Gaussian to detect somas. Recommended somaDiameter / 2.0 -- in pixels params["searchRadius"]: for finding nearby DoG peaks which are actually the same soma. Recommended somaDiameter / 3.0 -- in pixels parmams["min_count"]: to consider only somas detected in at least min_count time points, i.e. their coordinates are the average of at least min_count independent detections. """ peaks = findPeaks(img4D, params) mergedPeaks = mergePeaks(peaks, params) nuclei = filterNuclei(mergedPeaks, params) # Show as a 3D volume with spheres if show: spheresRAI = virtualPointsRAI(nuclei, params["somaDiameter"] / 2.0, Views.hyperSlice(img4D, 3, 1)) imp = showStack(spheresRAI, title="nuclei (min_count=%i)" % params["min_count"]) return peaks, mergedPeaks, nuclei, spheresRAI, imp return peaks, mergedPeaks, nuclei
def projectLastDimension(img, showEarly=False): """ Project the last dimension, e.g. a 4D image becomes a 3D image, using the provided reducing function (e.g. min, max, sum). """ last_dimension = img.numDimensions() - 1 # The collapsed image imgC = ArrayImgs.unsignedShorts( [img.dimension(d) for d in xrange(last_dimension)]) if showEarly: showStack( imgC, title="projected") # show it early, will be updated progressively if img.dimension(last_dimension) > 10: # one by one print "One by one" for i in xrange(img.dimension(last_dimension)): print i compute(maximum(imgC, Views.hyperSlice(img, last_dimension, i))).into(imgC) else: # Each sample of img3DV is a virtual vector over all time frames at that 3D coordinate: imgV = Views.collapseReal(img) # Reduce each vector to a single scalar, using a Converter # The Converter class reduce_max = makeCompositeToRealConverter( reducer_class=Math, reducer_method="max", reducer_method_signature="(DD)D") img3DC = convert(imgV, reduce_max.newInstance(), img.randomAccess().get().getClass()) ImgUtil.copy(ImgView.wrap(imgV, img.factory()), imgC) return imgC
def viewAligned(filepaths, csvDir, params, paramsTileConfiguration, img_dimensions, cropInterval): matrices = align(filepaths, csvDir, params, paramsTileConfiguration) cellImg, cellGet = makeImg(filepaths, loadUnsignedShort, img_dimensions, matrices, cropInterval, 1, 5) print cellImg comp = showStack(cellImg, title=srcDir.split('/')[-2], proper=False) # Add the SourcePanning KeyListener as the first one canvas = comp.getWindow().getCanvas() kls = canvas.getKeyListeners() for kl in kls: canvas.removeKeyListener(kl) canvas.addKeyListener(SourcePanning(cellGet, comp)) for kl in kls: canvas.addKeyListener(kl) ImagePlus.addImageListener(OnClosing(comp, cellGet))
from functools import partial srcDir = "/home/albert/Desktop/t2/189/section189-images/" filepaths = [ os.path.join(srcDir, filename) for filename in sorted(os.listdir(srcDir)) if filename.endswith(".tif") ] dims = [2048, 2048] voldims = [dims[0], dims[1], len(filepaths)] cell_dimensions = [dims[0], dims[1], 1] def asNormalizedUnsignedByteArrayImg(blockRadius, stds, center, stretch, imp): sp = imp.getProcessor() # ShortProcessor NormalizeLocalContrast().run(sp, blockRadius, blockRadius, stds, center, stretch) return ArrayImgs.unsignedBytes( sp.convertToByte(True).getPixels(), [sp.getWidth(), sp.getHeight()]) loader = SectionCellLoader(filepaths, asArrayImg=partial(asNormalizedUnsignedByteArrayImg, 400, 3, True, True)) cachedCellImg = lazyCachedCellImg(loader, voldims, cell_dimensions, UnsignedByteType, BYTE) showStack(cachedCellImg)
showStack( imgC, title="projected") # show it early, will be updated progressively if img.dimension(last_dimension) > 10: # one by one print "One by one" for i in xrange(img.dimension(last_dimension)): print i compute(maximum(imgC, Views.hyperSlice(img, last_dimension, i))).into(imgC) else: # Each sample of img3DV is a virtual vector over all time frames at that 3D coordinate: imgV = Views.collapseReal(img) # Reduce each vector to a single scalar, using a Converter # The Converter class reduce_max = makeCompositeToRealConverter( reducer_class=Math, reducer_method="max", reducer_method_signature="(DD)D") img3DC = convert(imgV, reduce_max.newInstance(), img.randomAccess().get().getClass()) ImgUtil.copy(ImgView.wrap(imgV, img.factory()), imgC) return imgC img3D = projectLastDimension(img4D, showEarly=True) showStack(img3D, title="projected")
params.update(paramsFeatures) params.update(paramsModel) params.update(paramsTileConfiguration) modelclass = TranslationModel3D img4D = registerDeconvolvedTimePoints(targetDir, params, modelclass, exe=None, verbose=False, subrange=range(first_timepoint, last_timepoint + 1)) # IL.wrap gets structure wrong: uses channels for slices, and slices for frames #IL.wrap(img4D, "0-399").show() showStack(img4D, title="%i-%i" % (first_timepoint, last_timepoint)) # Materialize (write to disk) the registered deconvolved stacks targetDirN5 = os.path.join(targetDir, "deconvolved/n5/") nameN5 = "%s_%i-%i_%ix%ix%ix%i" % (targetDir.split("/")[-2], first_timepoint, last_timepoint, img4D.dimension(0), img4D.dimension(1), img4D.dimension(2), img4D.dimension(3)) writeN5Volume = True if not os.path.exists(targetDirN5): os.mkdir(targetDirN5) else:
dataset_name = "2017-5-10_1018_0-399_X203_Y155_Z65" # Load entire 4D IsoView deconvolved and registered data set img4D = readN5(n5dir, dataset_name) # A mask: only nuclei whose x,y,z coordinate has a non-zero value in the mask will be considered mask = None # Split CM00+CM01 (odd) from CM02+CM03 (even) into two series series = ["CM00-CM01", "CM02-CM03"] img4Da = Views.subsample(img4D, [1, 1, 1, 2]) # step img4Db = Views.subsample(Views.interval(img4D, [0, 0, 0, 1], Intervals.maxAsLongArray(img4D)), [1, 1, 1, 2]) # step showStack(img4Da, title="%s registered+deconvolved" % series[0]) showStack(img4Db, title="%s registered+deconvolved" % series[1]) calibration = [1.0, 1.0, 1.0] somaDiameter = 8 * calibration[0] # Parameters for detecting nuclei with difference of Gaussian params = { "frames": 5, # number of time frames to average, 5 is equivalent to 3.75 seconds: 0.75 * 5 "calibration": calibration, # Deconvolved images have isotropic calibration "somaDiameter": somaDiameter, # in pixels "minPeakValue": 50, # determined by hand: the bright peaks "sigmaSmaller": somaDiameter / 4.0, # in calibrated units: 1/4 soma "sigmaLarger": somaDiameter / 2.0, # in calibrated units: 1/2 soma "searchRadius": somaDiameter / 3.0, "min_count": 20,
import sys sys.path.append("/home/albert/lab/scripts/python/imagej/IsoView-GCaMP/") from lib.io import readN5 from lib.dogpeaks import createDoG from lib.synthetic import virtualPointsRAI from lib.ui import showStack from net.imglib2 import RealPoint, FinalInterval points = [RealPoint.wrap([255, 255, 255]), RealPoint.wrap([255, 255, 0]), RealPoint.wrap([128, 384, 128])] rai = virtualPointsRAI(points, 70, FinalInterval([512, 512, 512])) imp = showStack(rai, title="test virtualPointsRAI")
import sys sys.path.append( "/groups/cardona/home/cardonaa/lab/scripts/python/imagej/IsoView-GCaMP/") from net.imglib2.view import Views from net.imglib2 import FinalInterval from lib.io import readN5 from lib.ui import showStack name = "FIBSEM_L1116" img3D = readN5("/groups/cardona/cardonalab/FIBSEM_L1116_exports/n5/", name, show=None) #fov = Views.interval(img3D, FinalInterval([4096, 4096, 0], [8192 -1, 8192 -1, 13770 -1])) fov = img3D # whole imp = showStack(fov, title=name) #imp.setPosition(imp.getStack().size()) # last slice