def withIcospheres(time_window=None): with open(os.path.join(baseDir, csvFilename), 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') header = reader.next() peaks = [RealPoint.wrap(imap(float, peak.split('::'))) for peak in islice(header, 1, None)] # Template icosahedron ico = MeshMaker.createIcosahedron(2, radius) # Share lists of Point3f across all timepoints icos = [MeshMaker.copyTranslated(ico, peak.getFloatPosition(0), peak.getFloatPosition(1) , peak.getFloatPosition(2)) for peak in peaks] # univ = Image3DUniverse(512, 512) instants = TreeMap() # rows = reader if time_window is None else islice(reader, time_window[0], time_window[1]) for row in rows: # Values mapped to 0-1: Color3f takes 3 values in domain [0, 1]. # So: ensure the value is inside [minimum, maximum] range, then rezero by subtracting minimum, and divide by span (maximum - minimum) values = ((min(max(float(v), minimum), maximum) - minimum) / span for v in islice(row, 1, None)) meshes = [CustomTriangleMesh(mesh, Color3f(v, v, v), 0) for v, mesh in izip(values, icos)] ci = ContentInstant(str(row[0])) ci.display(CustomMultiMesh(meshes)) # each mesh has its color ci.setLocked(True) print row[0] instants.put(int(row[0]), ci) print "n instants:", instants.size() univ.addContent(Content("deltaF/F", instants, False)) univ.show() univ.updateStartAndEndTime(0, len(instants) -1)
def withVirtualStack(time_window=None, subsample=None): with open(os.path.join(baseDir, csvFilename), 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') header = reader.next() peaks = [ RealPoint.wrap(imap(float, peak.split('::'))) for peak in islice(header, 1, None) ] frames = [ virtualPointsRAI(peaks, radius, interval, inside=to8bitRange( map(float, islice(row, 1, None)))) for row in reader ] if time_window: first, last = time_window frames = frames[first:last + 1] img4D = Views.stack(frames) # Scale by a factor of 'subsample' in every dimension by nearest neighbor, sort of: if subsample: img4D = Views.subsample(img4D, subsample) imp = ImagePlus("deltaF/F", ImageJVirtualStackUnsignedByte.wrap(img4D)) imp.setDimensions(1, img4D.dimension(2), img4D.dimension(3)) imp.setDisplayRange(0, 255) com = CompositeImage(imp, CompositeImage.GRAYSCALE) com.show() univ = Image3DUniverse(512, 512) univ.show() univ.addVoltex(com)
def analyze_cells(imp, size, i, zmin): test = [] cdf = [] #ip = imp.getProcessor() #print "grabbing image..." #test = ip.getHistogram() #test = StackStatistics(imp).getHistogram() #print "calculating stack statistics..." #total = sum(test) #print "calculate threshold" #cdf = map(lambda x: x/float(total), acc(test)) #thresh = min(filter(lambda x: cdf[x] >= quantile, xrange(1,len(cdf)) )) max_int = StackStatistics(imp).max cal= imp.getCalibration() scale2D = cal.pixelWidth / cal.pixelDepth sigma = (size / cal.pixelWidth) * scale2D iso = Compute.inFloats(Scale2D(ImgLib.wrap(imp),scale2D)) peaks = DoGPeaks(iso, sigma, sigma * 0.5, thresh, 1) print "FOund", len(peaks), "peaks" ps = [] file = open(folder+str(i).zfill(4)+'_test_out.csv','w') exporter = csv.writer(file) for peak in peaks: if peak[2]>=zmin: print "raw",peak p = Point3f(peak) p.scale(cal.pixelWidth * 1/scale2D) print "sf", cal.pixelWidth * 1/scale2D print "scaled", p ps.append(p) t = () exporter.writerow([p.x, p.y, p.z]) file.close() if vis: iso = Compute.inFloats(Scale2D(Red(ImgLib.wrap(imp)),scale2D)) univ = Image3DUniverse(512,512) univ.addIcospheres(ps,Color3f(1,0,0), 2, size/2, "Cells").setLocked(True) univ.addOrthoslice(imp).setLocked(True) univ.show()
def run(imp, preprocessor_path, postprocessor_path, threshold_method, user_comment): output_parameters = { "image title": "", "preprocessor path": float, "post processor path": float, "thresholding op": float, "use ridge detection": bool, "high contrast": int, "low contrast": int, "line width": int, "minimum line length": int, "mitochondrial footprint": float, "branch length mean": float, "branch length median": float, "branch length stdevp": float, "summed branch lengths mean": float, "summed branch lengths median": float, "summed branch lengths stdevp": float, "network branches mean": float, "network branches median": float, "network branches stdevp": float } output_order = [ "image title", "preprocessor path", "post processor path", "thresholding op", "use ridge detection", "high contrast", "low contrast", "line width", "minimum line length", "mitochondrial footprint", "branch length mean", "branch length median", "branch length stdevp", "summed branch lengths mean", "summed branch lengths median", "summed branch lengths stdevp", "network branches mean", "network branches median", "network branches stdevp" ] # Perform any preprocessing steps... status.showStatus("Preprocessing image...") if preprocessor_path != None: if preprocessor_path.exists(): preprocessor_thread = scripts.run(preprocessor_path, True) preprocessor_thread.get() imp = WindowManager.getCurrentImage() else: pass # Store all of the analysis parameters in the table if preprocessor_path == None: preprocessor_str = "" else: preprocessor_str = preprocessor_path.getCanonicalPath() if postprocessor_path == None: postprocessor_str = "" else: postprocessor_str = preprocessor_path.getCanonicalPath() output_parameters["preprocessor path"] = preprocessor_str output_parameters["post processor path"] = postprocessor_str output_parameters["thresholding op"] = threshold_method output_parameters["use ridge detection"] = str(use_ridge_detection) output_parameters["high contrast"] = rd_max output_parameters["low contrast"] = rd_min output_parameters["line width"] = rd_width output_parameters["minimum line length"] = rd_length # Create and ImgPlus copy of the ImagePlus for thresholding with ops... status.showStatus("Determining threshold level...") imp_title = imp.getTitle() slices = imp.getNSlices() frames = imp.getNFrames() output_parameters["image title"] = imp_title imp_calibration = imp.getCalibration() imp_channel = Duplicator().run(imp, imp.getChannel(), imp.getChannel(), 1, slices, 1, frames) img = ImageJFunctions.wrap(imp_channel) # Determine the threshold value if not manual... binary_img = ops.run("threshold.%s" % threshold_method, img) binary = ImageJFunctions.wrap(binary_img, 'binary') binary.setCalibration(imp_calibration) binary.setDimensions(1, slices, 1) # Get the total_area if binary.getNSlices() == 1: area = binary.getStatistics(Measurements.AREA).area area_fraction = binary.getStatistics( Measurements.AREA_FRACTION).areaFraction output_parameters[ "mitochondrial footprint"] = area * area_fraction / 100.0 else: mito_footprint = 0.0 for slice in range(binary.getNSlices()): binary.setSliceWithoutUpdate(slice) area = binary.getStatistics(Measurements.AREA).area area_fraction = binary.getStatistics( Measurements.AREA_FRACTION).areaFraction mito_footprint += area * area_fraction / 100.0 output_parameters[ "mitochondrial footprint"] = mito_footprint * imp_calibration.pixelDepth # Generate skeleton from masked binary ... # Generate ridges first if using Ridge Detection if use_ridge_detection and (imp.getNSlices() == 1): skeleton = ridge_detect(imp, rd_max, rd_min, rd_width, rd_length) else: skeleton = Duplicator().run(binary) IJ.run(skeleton, "Skeletonize (2D/3D)", "") # Analyze the skeleton... status.showStatus("Setting up skeleton analysis...") skel = AnalyzeSkeleton_() skel.setup("", skeleton) status.showStatus("Analyzing skeleton...") skel_result = skel.run() status.showStatus("Computing graph based parameters...") branch_lengths = [] summed_lengths = [] graphs = skel_result.getGraph() for graph in graphs: summed_length = 0.0 edges = graph.getEdges() for edge in edges: length = edge.getLength() branch_lengths.append(length) summed_length += length summed_lengths.append(summed_length) output_parameters["branch length mean"] = eztables.statistical.average( branch_lengths) output_parameters["branch length median"] = eztables.statistical.median( branch_lengths) output_parameters["branch length stdevp"] = eztables.statistical.stdevp( branch_lengths) output_parameters[ "summed branch lengths mean"] = eztables.statistical.average( summed_lengths) output_parameters[ "summed branch lengths median"] = eztables.statistical.median( summed_lengths) output_parameters[ "summed branch lengths stdevp"] = eztables.statistical.stdevp( summed_lengths) branches = list(skel_result.getBranches()) output_parameters["network branches mean"] = eztables.statistical.average( branches) output_parameters["network branches median"] = eztables.statistical.median( branches) output_parameters["network branches stdevp"] = eztables.statistical.stdevp( branches) # Create/append results to a ResultsTable... status.showStatus("Display results...") if "Mito Morphology" in list(WindowManager.getNonImageTitles()): rt = WindowManager.getWindow( "Mito Morphology").getTextPanel().getOrCreateResultsTable() else: rt = ResultsTable() rt.incrementCounter() for key in output_order: rt.addValue(key, str(output_parameters[key])) # Add user comments intelligently if user_comment != None and user_comment != "": if "=" in user_comment: comments = user_comment.split(",") for comment in comments: rt.addValue(comment.split("=")[0], comment.split("=")[1]) else: rt.addValue("Comment", user_comment) rt.show("Mito Morphology") # Create overlays on the original ImagePlus and display them if 2D... if imp.getNSlices() == 1: status.showStatus("Generate overlays...") IJ.run(skeleton, "Green", "") IJ.run(binary, "Magenta", "") skeleton_ROI = ImageRoi(0, 0, skeleton.getProcessor()) skeleton_ROI.setZeroTransparent(True) skeleton_ROI.setOpacity(1.0) binary_ROI = ImageRoi(0, 0, binary.getProcessor()) binary_ROI.setZeroTransparent(True) binary_ROI.setOpacity(0.25) overlay = Overlay() overlay.add(binary_ROI) overlay.add(skeleton_ROI) imp.setOverlay(overlay) imp.updateAndDraw() # Generate a 3D model if a stack if imp.getNSlices() > 1: univ = Image3DUniverse() univ.show() pixelWidth = imp_calibration.pixelWidth pixelHeight = imp_calibration.pixelHeight pixelDepth = imp_calibration.pixelDepth # Add end points in yellow end_points = skel_result.getListOfEndPoints() end_point_list = [] for p in end_points: end_point_list.append( Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth)) univ.addIcospheres(end_point_list, Color3f(255.0, 255.0, 0.0), 2, 1 * pixelDepth, "endpoints") # Add junctions in magenta junctions = skel_result.getListOfJunctionVoxels() junction_list = [] for p in junctions: junction_list.append( Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth)) univ.addIcospheres(junction_list, Color3f(255.0, 0.0, 255.0), 2, 1 * pixelDepth, "junctions") # Add the lines in green graphs = skel_result.getGraph() for graph in range(len(graphs)): edges = graphs[graph].getEdges() for edge in range(len(edges)): branch_points = [] for p in edges[edge].getSlabs(): branch_points.append( Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth)) univ.addLineMesh(branch_points, Color3f(0.0, 255.0, 0.0), "branch-%s-%s" % (graph, edge), True) # Add the surface univ.addMesh(binary) univ.getContent("binary").setTransparency(0.5) # Perform any postprocessing steps... status.showStatus("Running postprocessing...") if postprocessor_path != None: if postprocessor_path.exists(): postprocessor_thread = scripts.run(postprocessor_path, True) postprocessor_thread.get() else: pass status.showStatus("Done analysis!")
impMask = IJ.openImage(maskPath) impMask.setCalibration(cal.copy()) impMask.show() IJ.run("Enhance Contrast", "saturated=0.35") IJ.run("Apply LUT", "stack") impMask.changes = 0 # will not ask to save on close impSkel = IJ.openImage(skelPath) impSkel.setCalibration(cal.copy()) impSkel.show() IJ.run("Enhance Contrast", "saturated=0.35") IJ.run("Apply LUT", "stack") impSkel.changes = 0 # will not ask to save on close # Create a universe and show it univ = Image3DUniverse(512, 512) c1 = univ.addVoltex(imp) myColor = Color3f((0.0, 1.0, 0.0)) c1.setColor(myColor) c1.setThreshold(5) #print('c1:', type(c1), c1) c2 = univ.addVoltex(impMask) myColor = Color3f((0.0, 0.0, 0.0)) c2.setColor(myColor) c3 = univ.addVoltex(impSkel) myColor = Color3f((1.0, 0.0, 0.0)) c2.setColor(myColor)
from ij3d import Image3DUniverse from org.scijava.java3d import View from ij import IJ from isosurface import SmoothControl univ = Image3DUniverse(512, 512) # view size, not universe size univ.getViewer().getView().setProjectionPolicy(View.PERSPECTIVE_PROJECTION) univ.show() #imp = IJ.openImage("/home/albert/lab/projects/20170112_small_animals/chameleon/Brookeesia-chameleon-sagital-flat.am") #imp = IJ.getImage() resample = 4 #univ.addVoltex(imp, None, imp.getTitle(), 0, [True, True, True], resample) brain_hemisphere_left = "/home/albert/lab/projects/20170112_small_animals/chameleon/Brookesia-segmented-brain-volumes/brain-hemisphere-left.zip" brain_hemisphere_right = "/home/albert/lab/projects/20170112_small_animals/chameleon/Brookesia-segmented-brain-volumes/brain-hemisphere-right.zip" brain_rest = "/home/albert/lab/projects/20170112_small_animals/chameleon/Brookesia-segmented-brain-volumes/rest-of-brain.zip" c1 = univ.addMesh(IJ.openImage(brain_hemisphere_left), resample) c2 = univ.addMesh(IJ.openImage(brain_hemisphere_right), resample) c3 = univ.addMesh(IJ.openImage(brain_rest), resample) c1.setLocked(True) c2.setLocked(True) c3.setLocked(True) sc = SmoothControl(univ)
from ij import IJ, ImagePlus, ImageStack from script.imglib.analysis import DoGPeaks from script.imglib.color import Red from script.imglib.algorithm import Scale2D from script.imglib.math import Compute from script.imglib import ImgLib from ij3d import Image3DUniverse # from javax.vecmath import Color3f, Point3f # Load a stack of images: a fly brain, in RGB imp = IJ.openImage("http://imagej.nih.gov/ij/images/flybrain.zip") stack = imp.getImageStack() # http://3dviewer.neurofly.de/ univ = Image3DUniverse() univ.show() c = univ.addVoltex(imp) print "number of slices:", imp.getNSlices() """ # A list of green slices greens = [] # Iterate each slice in the stack for i in xrange(1, imp.getNSlices()+1): # Get the ColorProcessor slice at index i cp = stack.getProcessor(i) # Get its green channel as a FloatProcessor fp = cp.toFloat(1, None) # ... and store it in a list greens.append(fp)