def ThresholdMaxEntropy(imp0): """Thresholds image and returns thresholded image, merge code still quite clumsy but functional""" imp0 = IJ.getImage() impthres = imp0.duplicate() imp01 = ImagePlus("Channel1", ChannelSplitter.getChannel(imp0, 1)) imp02 = ImagePlus("Channel2", ChannelSplitter.getChannel(imp0, 2)) imp001 = imp01.duplicate() imp002 = imp02.duplicate() IJ.setAutoThreshold(imp001, "MaxEntropy dark") IJ.run(imp001, "Convert to Mask", "") IJ.run(imp001, "Divide...", "value=255") IJ.setAutoThreshold(imp002, "MaxEntropy dark") IJ.run(imp002, "Convert to Mask", "") IJ.run(imp002, "Divide...", "value=255") ic = ImageCalculator() imp0001 = ic.run("Multiply create", imp01, imp001) ic2 = ImageCalculator() imp0002 = ic2.run("Multiply create", imp02, imp002) imp0001.copy() impthres.setC(1) impthres.paste() imp0002.copy() impthres.setC(2) impthres.paste() imp01.close() imp02.close() imp001.close() imp002.close() imp0001.close() imp0002.close() return impthres
def exportSegmentation(evt=None): display = Display.getFront() canvas = display.getCanvas() numLayer = display.getLayerSet().size(); exportMask(evt) files = [] for l in display.getLayerSet().getLayers(): for p in l.getDisplayables(Patch): files.append(p.getFilePath()) # Create virtual stack 'vs' vs = None for f in files: # if first image... if vs is None: imp = IJ.openImage(f) vs = VirtualStack(imp.width, imp.height, None, "/") vs.addSlice(f) ImagePlus("VSeg", vs).show() IJ.run("Duplicate...", "title=Segmentation duplicate range=1-30"); WindowManager.getImage("VSeg").close() ic = ImageCalculator() ic.run("Multiply stack", WindowManager.getImage("Segmentation"), WindowManager.getImage("Labels")); WindowManager.getImage("Labels").close()
def cross_planes_approx_median_filter(stack_imp, filter_radius_um=5.0): """relatively computationally cheap, slightly crude approximation of median filter""" title = stack_imp.getTitle(); xy_imp = Duplicator().run(stack_imp); xy_imp.setTitle("xy {}".format(title)); xz_imp = Duplicator().run(stack_imp); xz_imp.setTitle("xz {}".format(title)); xz_imp = rot3d(xz_imp, 'x'); zy_imp = Duplicator().run(stack_imp); zy_imp.setTitle("zy {}".format(title)); zy_imp = rot3d(zy_imp, 'y'); stack_imp.changes = False; stack_imp.close(); xy_imp = stack_median_filter(xy_imp, radius_um=filter_radius_um); xz_imp = stack_median_filter(xz_imp, radius_um=filter_radius_um); zy_imp = stack_median_filter(zy_imp, radius_um=filter_radius_um); xz_imp = rot3d(xz_imp, 'x'); zy_imp = rot3d(zy_imp, '-y'); ic = ImageCalculator(); dummy = ic.run("Add create 32-bit stack", xy_imp, xz_imp); xz_imp.close(); xy_imp.close(); output_imp = ic.run("Add create 32-bit stack", dummy, zy_imp); zy_imp.close(); dummy.close(); output_imp.show(); IJ.run(output_imp, "Divide...", "value=3 stack"); output_imp.setTitle("Cross-plane median filtered {} (r={} um)".format(title, filter_radius_um).replace(".tif", "")); print("Image size after applying approx median filter = ({}x{}x{})".format(output_imp.getWidth(), output_imp.getHeight(), output_imp.getNSlices())); return output_imp;
def divide_img_by_bkg(impImg, impBkg, name): """ divide_img_by_bkg(impImg, impBkg, title) Divide an image by its background and set title Parameters ========== impImg: ImagePlus An 8 bit image from a channel impBkg: ImagePlus An 8-bit image of the background title: A string for the image title Return ====== impRet: ImagePlus The ImagePlus containing a 32 bit/px background subtracted image """ ic = ImageCalculator() impRet = ic.run("Divide create 32-bit", impImg, impBkg) impRet.setTitle(name) return impRet
def divide_img_by_bkg(impImg, impBkg, name): """ divide_img_by_bkg(impImg, impBkg, title) Divide an image by its background and set title Parameters ========== impImg: ImagePlus An 8 bit image from a channel impBkg: ImagePlus An 8-bit image of the background title: A string for the image title Return ====== impRet: ImagePlus The ImagePlus containing a 32 bit/px background subtracted image """ ic = ImageCalculator() impRet = ic.run("Divide create 32-bit", impImg, impBkg) impRet.setTitle(name) return impRet
def run(): leftdir = '/Users/rando/Downloads/NLM-MontgomeryCXRSet/MontgomerySet/ManualMask/leftMask/' rightdir = '/Users/rando/Downloads/NLM-MontgomeryCXRSet/MontgomerySet/ManualMask/rightMask/' savedir = '/Users/rando/Downloads/NLM-MontgomeryCXRSet/MontgomerySet/ManualMask/BinaryMask/' Raw_path = os.path.join(leftdir, '*png') X = glob.glob(Raw_path) axes = 'YX' for fname in X: print(fname) IJ.open(fname); imp = IJ.getImage() width = imp.width height = imp.height title_left = imp.getTitle(); print(title_left) Name = os.path.basename(os.path.splitext(fname)[0]) RightName = rightdir + title_left IJ.open(RightName) imp_right = IJ.getImage() title_right = imp_right.getTitle() print(title_right) imp_res = ImageCalculator.run(imp, imp_right, "add create 8-bit"); title = imp_res.getTitle() IJ.saveAs(imp_res, '.tif', savedir + Name); imp.close(); imp_right.close(); imp_res.close();
def Multiply(imp1, imp2): ic = ImageCalculator() imp = ic.run("Multiply create stack", imp1, imp2) stats = StackStatistics(imp) IJ.setMinAndMax(imp, stats.min, stats.max) print stats imp.setTitle("Multiply") imp.show() return imp
def DoG(imp0, kernel1, kernel2): """Thresholds image and returns thresholded image, merge code still quite clumsy but functional""" imp1 = imp0.duplicate() imp2 = imp0.duplicate() IJ.run(imp1, "Gaussian Blur...", "sigma=" + str(kernel1) + " stack") IJ.run(imp2, "Gaussian Blur...", "sigma=" + str(kernel2) + " stack") ic = ImageCalculator() imp3 = ic.run("Subtract create stack", imp1, imp2) return imp3
def filter_diff_gauss_3d(imp,dx1,dy1,dz1,dx2,dy2,dz2): imp_1 = imp.duplicate() GaussianBlur3D().blur(imp_1, dx1, dy1, dz1) imp_2 = imp.duplicate() GaussianBlur3D().blur(imp_2, dx2, dy2, dz2) ic = ImageCalculator() imp_diff = ic.run("Subtract stack create", imp_1, imp_2) imp_diff.show() return imp_diff
def make_outline_image(imp): #imp.show() # one needs to display it, otherwise below function cannot find it IJ.run(imp, "3D Fast Filters", "filter=Minimum radius_x_pix=1.0 radius_y_pix=1.0 radius_z_pix=1.0"); #imp.hide() imp_minimum = WindowManager.getImage("3D_Minimum") imp_outlines = imp.duplicate() ic = ImageCalculator() imp_outlines = ic.run("Subtract stack", imp_outlines, imp_minimum) # clean up imp_minimum.close() imp_outlines.setTitle("Outlines") return imp_outlines
def maskFromOverlay(imp): ''' TODO Documentation ''' overlay = imp.getOverlay(); img = ImageJFunctions.wrap(imp); emptyImg = ops.create().img(img); if overlay is None: return emptyImg; emptyImp = ImageJFunctions.wrap(emptyImg, "mask"); for roi in overlay.toArray(): imp.setRoi(roi); IJ.run(imp, "Create Mask", ""); manualMaskImp = IJ.getImage(); ic = ImageCalculator(); ic.run("OR", emptyImp, manualMaskImp); manualMask = ImageJFunctions.wrap(manualMaskImp); manualMaskImp.close(); #imp.setRoi(None); return manualMask;
def identifyTunicate(imp): # Clear ROI manager rm = RoiManager.getInstance() if rm is not None: rm.reset() # Get hue from HSB stack impHue = ProcessHSB.getHue(imp) width = impHue.width height = impHue.height # Get processor ipHue = impHue.getProcessor().convertToFloat() huePixels = ipHue.getPixels() # Get macro hue because it is the same color newPixels = map(ProcessHSB.macroHue, huePixels) ipNew = FloatProcessor(width, height, newPixels) impTunicate = ImagePlus("MacroHue", ipNew) # Bring brightness into the equation impBrightness = ProcessHSB.getBrightness(imp) IJ.run(impBrightness, "Auto Threshold", "method=MaxEntropy white") #IJ.run(impBrightness, "Analyze Particles...", "size=10000-Infinity circularity=0.10-1.00 show=Masks in_situ") # "add" right after "include" to include roi to manager # Logic AND pictures together ic = ImageCalculator() impTunicateMask = ic.run("AND create", impTunicate, impBrightness) IJ.run(impTunicateMask, "8-bit", "") # convert to 8-bit impTunicate.close() impBrightness.close() IJ.run(impTunicateMask, "Analyze Particles...", "size=10000-Infinity circularity=0.50-1.00 show=Masks add in_situ" ) # "add" right after "include" to include roi to manager impTunicateMask.close() #imp.show() #rm = RoiManager.getInstance() #return rm #testImp = IJ.getImage() #result = identifyTunicate(testImp) #print type(result)
def make_and_clean_binary(imp, threshold_method): """convert the membrane identification channel into binary for segmentation""" if "Local: " in threshold_method: dup = Duplicator() imp1 = dup.run(imp) imp2 = dup.run(imp) imp.changes = False imp.close() threshold_method = threshold_method.split("Local: ")[1] IJ.run(imp1, "8-bit", "") IJ.run( imp1, "Auto Local Threshold", "method=" + threshold_method + " radius=15 parameter_1=0 parameter_2=0 white stack") IJ.run(imp2, "Make Binary", "method=MinError background=Dark calculate") ic = ImageCalculator() imp = ic.run("AND create stack", imp1, imp2) IJ.run(imp, "Invert", "stack") IJ.run(imp, "Make Binary", "method=Default background=Default calculate") elif "Edge" in threshold_method: IJ.run(imp, "Find Edges", "stack") IJ.run(imp, "Make Binary", "method=Mean background=Dark calculate") else: IJ.run(imp, "Make Binary", "method=" + threshold_method + " background=Dark calculate") # "calculate" ensures that threshold is calculated image-wise IJ.run(imp, "Open", "stack") IJ.run(imp, "Close-", "stack") IJ.run(imp, "Close-", "stack") IJ.run(imp, "Open", "stack") IJ.run(imp, "Fill Holes", "stack") IJ.run(imp, "Erode", "stack") IJ.run(imp, "Erode", "stack") keep_largest_blob(imp) IJ.run(imp, "Dilate", "stack") IJ.run(imp, "Dilate", "stack") IJ.run(imp, "Open", "stack") if "Edge" in threshold_method: IJ.run(imp, "Erode", "stack") IJ.run(imp, "Erode", "stack") return imp
def identifyRed(imp): # Clear ROI manager rm = RoiManager.getInstance() if rm is not None: rm.reset() # Get hue from HSB stack impHue = ProcessHSB.getHue(imp) width = impHue.width height = impHue.height # Get processor for hue ipHue = impHue.getProcessor().convertToFloat() huePixels = ipHue.getPixels() # Bring brightness into the equation impBrightness = ProcessHSB.getBrightness(imp) IJ.run(impBrightness, "Auto Threshold", "method=Default white") #IJ.run(impBrightness, "Analyze Particles...", "size=10000-Infinity circularity=0.00-1.00 show=Masks in_situ") # If hue < 30 and hue > 225, True newPixels = map(ProcessHSB.redHue, huePixels) # Pause: Do this later ipNew = FloatProcessor(width, height, newPixels) impRed = ImagePlus("RedHue", ipNew) IJ.run(impRed, "8-bit", "") # convert to 8-bit # Logic AND pictures together ic = ImageCalculator() impRedMask = ic.run("AND create", impRed, impBrightness) IJ.run(impRedMask, "8-bit", "") # convert to 8-bit IJ.run(impRedMask, "Analyze Particles...", "size=10000-Infinity circularity=0.00-1.00 show=Masks add in_situ") # "add" right after "include" to include roi to manager impHue.close() impBrightness.close() impRed.close() impRedMask.close()
def open_fli(filepth): # load the dataset options = ImporterOptions() options.setId(filepth) options.setOpenAllSeries(1) imps = BF.openImagePlus(options) for imp in imps: title = imp.getTitle() if title.find("Background Image")==-1: img = imp imp.close() else: bkg = imp imp.close() ic = ImageCalculator() img2 = ic.run("Subtract create 32-bit stack",img,bkg) #copy the metadata props = img.getProperties() for prop in props: img2.setProperty(prop,props.getProperty(prop)) img.close() bkg.close() return img2
def create(imp): # Prep Roi Manager rm = RoiManager.getInstance() if rm is not None: rm.reset() # Get current image imp2 = imp.duplicate() IJ.run(imp2, "8-bit", "") # convert to 8-bit IJ.run(imp2, "Auto Threshold", "method=Shanbhag white") IJ.run(imp2, "Analyze Particles...", "size=10000-Infinity circularity=0-1.00 show=Masks add in_situ") # "add" right after "include" to include roi to manager # Remove background ic = ImageCalculator() imp3 = ic.run("AND create", imp, imp2) imp.close() imp2.close() ### Begin manipulating ROIs ### rm = RoiManager.getInstance() # Get number of objects found roiCount = rm.getCount() print "Number of Particles found:" + str(roiCount)
from ij import IJ; from ij.plugin import ImageCalculator; imp1 = IJ.getImage(); imp2 = imp1.duplicate(); IJ.run(imp2, "Minimum...", "radius=10"); IJ.run(imp2, "Maximum...", "radius=10"); ic = ImageCalculator(); imp3 = ic.run("Subtract create", imp1, imp2); imp3.show();
def process_imgdir( directory, close_after ) : print( 'Processing: ' + directory ) original_image_filename = directory + '/uniform.tif' probabilities_image_filename = directory + '/probabilities.tif' cube_rois_filename = directory + '/CubeROIs.csv' cubes = [] f = open(cube_rois_filename) lines = f.readlines() for line in lines[1:]: #els = [ int(el)-1 for el in line.strip().split(',') ] els = [ int(el) for el in line.strip().split(',') ] cubes += [ { 'idx': els[0], 'class': els[1], 'x1':min(els[2],els[5]), 'y1':min(els[3],els[6]), 'z1':min(els[4],els[7]), 'x2':max(els[5],els[2]), 'y2':max(els[6],els[3]), 'z2':max(els[4],els[7]) } ] f.close() print( 'Read ' + str(len(cubes)) + ' cubes from file' ) #for cube in cubes: #for cube_idx in range( len( cubes ) ): for cube_idx in [0]: cube = cubes[cube_idx] print( cube ) all_edt_histograms['name'] += [ directory.split( '/' )[-1] + '_' + str(cube_idx) ] all_skeleton_edt_histograms['name'] += [ directory.split( '/' )[-1] + '_' + str(cube_idx) ] cube_basename = directory + '/cube_' + str(cube_idx) + '_' # Check if we have a parameters file, and evaluate it if so, otherwise make one with defaults param_filename = cube_basename + 'parameters.py' # Make a default to start with no_params_set = False if not os.path.isfile( param_filename ): f = open( param_filename, 'w' ) f.write( 'mesh_thresh=200\n' ) f.write( 'interior_coords=[ (1,1,1) ]\n' ) f.close() no_params_set = True if os.path.isfile( param_filename ): f = open( param_filename ) lines = f.readlines() for line in lines: if 'mesh_thresh' in line: mesh_thresh = eval(line.split('=')[1]) if 'interior_coords' in line: interior_coords = eval(line.split('=')[1]) load_uniform = True if load_uniform: #open uniform uniform = IJ.openImage( original_image_filename ) #crop uniform uniform.setRoi( cube['x1'], cube['y1'], cube['x2'], cube['y2'] ) IJ.run( uniform, "Crop", "") IJ.run( uniform, "Make Substack...", "slices=" + str(cube['z1']) + '-' + str(cube['z2']) ) uniform.close() uniform = IJ.getImage() IJ.saveAsTiff( uniform, cube_basename + 'raw.tif' ) #save max_projection of uniform IJ.run(uniform, "Z Project...", "projection=[Max Intensity]") uniform_mp = IJ.getImage() IJ.run(uniform_mp, "Enhance Contrast", "saturated=0.35") IJ.saveAsTiff( uniform_mp, cube_basename + 'raw_maxproj.tif' ) #open probabilites probabilities = IJ.openImage( probabilities_image_filename ) #crop probabilites probabilities.setRoi( cube['x1'], cube['y1'], cube['x2'], cube['y2'] ) IJ.run( probabilities, "Crop", "") IJ.run( probabilities, "Make Substack...", "slices=" + str(cube['z1']) + '-' + str(cube['z2']) ) time.sleep( 5 ) probabilities.close() probabilities = IJ.getImage() #IJ.saveAsTiff( probabilities, cube_basename + 'probabilities.tif' ) time.sleep( 5 ) #save max_projection of probabilites IJ.run(probabilities, "Z Project...", "projection=[Max Intensity]") probabilities_mp = IJ.getImage() IJ.run(probabilities_mp, "Enhance Contrast", "saturated=0.35") IJ.saveAsTiff( probabilities_mp, cube_basename + 'probabilities_maxproj.tif' ) time.sleep( 5 ) # blur probabilities to help smooth the isosurfaces blur_radius = 2 IJ.run( probabilities, "Gaussian Blur 3D...", 'x=' + str(blur_radius) + ' y=' + str(blur_radius) + ' z=' + str(blur_radius) ) #threshold probabilities #IJ.run(probabilities, "Enhance Contrast", "saturated=0.35") IJ.run( probabilities, "8-bit", "") #IJ.saveAsTiff( probabilities, cube_basename + 'probabilities.tif' ) #for k in range( probabilities.getNSlices() ): # probabilities.setSlice(k+1) # probabilities.getProcessor().setThreshold( mesh_thresh - 1, mesh_thresh + 1, 0 ) #IJ.run( probabilities, 'Convert to Mask', 'method=Default background=Dark black') #time.sleep( 5 ) IJ.saveAsTiff( probabilities, cube_basename + 'probabilities.tif' ) time.sleep( 5 ) #mesh binary_probabilities #IJ.run( "3D Viewer", "") threedType = 2 threedName = 'cube_' + str(cube_idx) IJ.runPlugIn( "ij3d.ImageJ3DViewer", probabilities.getTitle() ) univ = Image3DUniverse.universes.get(0) univ.addContent( probabilities, Color3f(1,1,1), threedName, mesh_thresh, [True, False, False], 2, threedType ) ImageJ3DViewer.select( threedName ) ImageJ3DViewer.exportContent( 'wavefront', cube_basename + 'mesh.obj' ) #smooth mesh c = univ.getSelected() n = c.getContent() ctm = n.getMesh() fim = customnode.FullInfoMesh( ctm.getMesh() ) ec = customnode.EdgeContraction( fim, False ) initial_num_verts = ec.getVertexCount() num_to_remove = int( initial_num_verts * 0.1 ) #v = InteractiveMeshDecimation.simplify( ec, num_to_remove ) enable_smoothing = False if enable_smoothing: part = num_to_remove / 10 last = num_to_remove % 10 ret = 0 for i in range(10): IJ.showProgress(i + 1, 10) ret = ec.removeNext(part) if (last != 0): ret = ec.removeNext(last) IJ.showProgress(1) ctm.setMesh( fim.getMesh() ) ImageJ3DViewer.exportContent( 'wavefront', cube_basename + 'smooth_mesh.obj' ) # 3d viewer screenshot screenshot_3d = univ.takeSnapshot() IJ.saveAsTiff( screenshot_3d, cube_basename + 'mesh_screenshot.tif' ) #voxelize mesh voxelizer = InteractiveMeshVoxelization() voxelizer.voxelize( ctm, probabilities.getWidth(), probabilities.getHeight(), probabilities.getStackSize() ) #voxelization = WindowManager.getImage( ctm.getName() + '_voxelization' ) voxelization = WindowManager.getImage( 'null_voxelization' ) voxelization.setCalibration( probabilities.getCalibration().copy() ) #manually 3D fill vasculature, fill with thresholdable-color #save selected vasculature #call('process3d.Flood_Fill.fill', x,y,z) if not no_params_set: fill_color = 100 Flood_Fill.fill( voxelization, interior_coords[0][0], interior_coords[0][1], interior_coords[0][2], fill_color ) # Threshold to extract #IJ.setAutoThreshold( voxelization, 'Default dark' ) #Prefs.blackBackground = true #IJ.run( voxelization, 'Convert to Mask', 'method=Default background=Dark black') for k in range( voxelization.getNSlices() ): voxelization.setSlice(k+1) voxelization.getProcessor().setThreshold( fill_color - 1, fill_color + 1, 0 ) IJ.run( voxelization, 'Convert to Mask', 'method=Default background=Dark black') IJ.saveAsTiff( voxelization, cube_basename + 'voxelization.tif' ) # Calculate and record volume HERE IJ.run(voxelization, "Z Project...", "projection=[Max Intensity]") voxelization_mp = IJ.getImage() IJ.run(voxelization_mp, "Enhance Contrast", "saturated=0.35") IJ.saveAsTiff( voxelization_mp, cube_basename + 'voxelization_maxproj.tif' ) # Calculate EDT IJ.run( voxelization, "Exact Euclidean Distance Transform (3D)", "" ) edt = WindowManager.getImage( 'EDT' ) IJ.run( edt, 'Fire', '' ) # Get the histogram data in an array hist_nBins = int( ( hist_max - hist_min ) / hist_step ) #edt_stats = edt.getStatistics( Measurements.MEDIAN, hist_nBins, hist_min, hist_max ) edt_stats = StackStatistics( edt, hist_nBins, hist_min, hist_max ) hist_data = edt_stats.getHistogram() hist_binLabels = [ ( hist_min + hist_step * el ) for el in range( hist_nBins ) ] max_radius = 20 IJ.run( edt, 'Histogram', 'bins=' + str(hist_nBins) + ' x_min=' + str(hist_min) + ' x_max=' + str(hist_max) + ' y_max=Auto stack' ) edt_histogram = WindowManager.getImage( 'Histogram of EDT' ) IJ.saveAsTiff( edt_histogram, cube_basename + 'edt_histogram.tif' ) x_unit_scale = uniform.getCalibration().getX(1) y_unit_scale = uniform.getCalibration().getY(1) z_unit_scale = uniform.getCalibration().getZ(1) f = open( cube_basename + 'edt_histogram.csv', 'w' ) for k in range( len( hist_data ) ): f.write( str(hist_binLabels[k]) + '\t' + str(hist_data[k]*x_unit_scale*y_unit_scale*z_unit_scale) + '\n' ) #f.write( str(hist_binLabels[k]) + '\t' + str(hist_data[k]) + '\n' ) all_edt_histograms[hist_binLabels[k]] += [ hist_data[k] ] f.close() # Handling skeletons IJ.run( voxelization, "Skeletonize (2D/3D)", "") skeleton = voxelization # For simplicity later, but note that voxelization has been mutated IJ.run(skeleton, "32-bit", "") IJ.run(skeleton, "Calculator Plus", 'i1=' + str(skeleton.getTitle()) + ' i2=' + str(skeleton.getTitle()) + ' operation=[Scale: i2 = i1 x k1 + k2] k1=0.003921568627 k2=0' ) IJ.run(skeleton, "Z Project...", "projection=[Max Intensity]") skeleton_mp = IJ.getImage() IJ.run(skeleton_mp, "Enhance Contrast", "saturated=0.35") IJ.saveAsTiff( skeleton_mp, cube_basename + 'skeleton_maxproj.tif' ) ic = ImageCalculator() skeleton_edt = ic.run("Multiply 32-bit stack", edt, skeleton) IJ.run( skeleton_edt, 'Fire', '' ) # Get the histogram data in an array hist_nBins = int( ( hist_max - hist_min ) / hist_step ) #skeleton_edt_stats = edt.getStatistics( Measurements.MEDIAN, hist_nBins, hist_min, hist_max ) skeleton_edt_stats = StackStatistics( edt, hist_nBins, hist_min, hist_max ) hist_data = skeleton_edt_stats.getHistogram() hist_binLabels = [ ( hist_min + hist_step * el ) for el in range( hist_nBins ) ] IJ.run( skeleton_edt, 'Histogram', 'bins=' + str(hist_nBins) + ' x_min=' + str(hist_min) + ' x_max=' + str(hist_max) + ' y_max=Auto stack' ) skeleton_edt_histogram = WindowManager.getImage( 'Histogram of EDT' ) IJ.saveAsTiff( skeleton_edt_histogram, cube_basename + 'skeleton_edt_histogram.tif' ) unit_scale = uniform.getCalibration().getX(1) f = open( cube_basename + 'skeleton_edt_histogram.csv', 'w' ) for k in range( len( hist_data ) ): f.write( str(hist_binLabels[k]) + '\t' + str(hist_data[k] * unit_scale) + '\n' ) all_skeleton_edt_histograms[hist_binLabels[k]] += [ hist_data[k] * unit_scale ] f.close() else: IJ.saveAsTiff( voxelization, cube_basename + 'voxelization.tif' ) # Free up resources if close_after: ImageJ3DViewer.close() IJ.run( 'Close All', '' ) IJ.freeMemory()
def calculate(str_comm, imp1, imp2): ic = IC() ic.run(str_comm, imp1, imp2)
def analyze(iDataSet, tbModel, p, output_folder): # # LOAD FILES # filepath = tbModel.getFileAPth(iDataSet, "RAW", "IMG") filename = tbModel.getFileName(iDataSet, "RAW", "IMG") print("Analyzing: "+filepath) IJ.run("Bio-Formats Importer", "open=["+filepath+"] color_mode=Default view=Hyperstack stack_order=XYCZT"); imp = IJ.getImage() # # INIT # IJ.run("Options...", "iterations=1 count=1"); # # SCALING # IJ.run(imp, "Scale...", "x="+str(p["scale"])+" y="+str(p["scale"])+" z=1.0 interpolation=Bilinear average process create"); imp = IJ.getImage() # save output file output_file = filename+"--downscale_input.tif" IJ.saveAs(IJ.getImage(), "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "INPUT","IMG") # # CONVERSION # #IJ.run(imp, "8-bit", ""); # # CROPPING # #imp.setRoi(392,386,750,762); #IJ.run(imp, "Crop", ""); # # BACKGROUND SUBTRACTION # # IJ.run(imp, "Subtract...", "value=32768 stack"); IJ.run(imp, "Z Project...", "projection=[Average Intensity]"); imp_avg = IJ.getImage() ic = ImageCalculator(); imp = ic.run("Subtract create 32-bit stack", imp, imp_avg); # # REGION SEGMENTATION # imp1 = Duplicator().run(imp, 1, imp.getImageStackSize()-1) imp2 = Duplicator().run(imp, 2, imp.getImageStackSize()) imp_diff = ic.run("Subtract create 32-bit stack", imp1, imp2); #imp_diff.show() IJ.run(imp_diff, "Z Project...", "projection=[Standard Deviation]"); imp_diff_sd = IJ.getImage() # save IJ.run(imp_diff_sd, "Gaussian Blur...", "sigma=5"); output_file = filename+"--sd.tif" IJ.saveAs(imp_diff_sd, "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "SD","IMG") IJ.run(imp_diff_sd, "Enhance Contrast", "saturated=0.35"); IJ.run(imp_diff_sd, "8-bit", ""); IJ.run(imp_diff_sd, "Properties...", "unit=p pixel_width=1 pixel_height=1 voxel_depth=1"); IJ.run(imp_diff_sd, "Auto Local Threshold", "method=Niblack radius=60 parameter_1=2 parameter_2=0 white"); rm = ROIManipulator.getEmptyRm() IJ.run(imp_diff_sd, "Analyze Particles...", "add"); # select N largest Rois diameter_roi = [] for i in range(rm.getCount()): roi = rm.getRoi(i) diameter_roi.append([roi.getFeretsDiameter(), roi]) diameter_roi = sorted(diameter_roi, reverse=True) #print diameter_roi rm.reset() for i in range(min(len(diameter_roi), p["n_rois"])): rm.addRoi(diameter_roi[i][1]) # save output_file = filename+"--rois" ROIManipulator.svRoisToFl(output_folder, output_file, rm.getRoisAsArray()) tbModel.setFileAPth(output_folder, output_file+".zip", iDataSet, "REGIONS","ROI") # # FFT in each region # IJ.run(imp, "Variance...", "radius=2 stack"); output_file = filename+"--beats.tif" IJ.saveAs(imp, "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "BEATS","IMG") n = rm.getCount() for i_roi in range(n): imp_selection = Duplicator().run(imp) rm.select(imp_selection, i_roi) IJ.run(imp_selection, "Clear Outside", "stack"); imp_selection.show() # FFT using Parallel FFTJ transformer = FloatTransformer(imp_selection.getStack()) transformer.fft() imp_fft = transformer.toImagePlus(SpectrumType.FREQUENCY_SPECTRUM) imp_fft.show() # Analyze FFt IJ.run(imp_fft, "Gaussian Blur 3D...", "x=0 y=0 z=1.5"); IJ.run(imp_fft, "Plot Z-axis Profile", ""); output_file = filename+"--Region"+str(i_roi+1)+"--fft.tif" IJ.saveAs(IJ.getImage(), "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "FFT_R"+str(i_roi+1),"IMG") IJ.run(imp_fft, "Select All", ""); rm.addRoi(imp_fft.getRoi()) rm.select(rm.getCount()) rt = ResultsTable() rt = rm.multiMeasure(imp_fft); #print(rt.getColumnHeadings); x = rt.getColumn(rt.getColumnIndex("Mean1")) #rm.runCommand("delete") peak_height_pos = [] x_min = 10 for i in range(x_min,len(x)/2): before = x[i-1] center = x[i] after = x[i+1] if (center>before) and (center>after): peak_height_pos.append([float(x[i]),i]) if len(peak_height_pos)>0: peak_height_pos = sorted(peak_height_pos, reverse=True) n_max = 3 for i_max in range(min(len(peak_height_pos),n_max)): tbModel.setNumVal(round(float(len(x))/float(peak_height_pos[i_max][1]),2), iDataSet, "F"+str(i_max+1)+"_R"+str(i_roi+1)) tbModel.setNumVal(int(peak_height_pos[i_max][0]), iDataSet, "A"+str(i_max+1)+"_R"+str(i_roi+1))
from ij import IJ from ij.plugin import ImageCalculator IJ.run("Close All") path_tif = "/Users/jrminter/Documents/git/tips/ImageJ/tif/lena-eyes.tif" path_jpg = "/Users/jrminter/Documents/git/tips/ImageJ/jpg/lena-eyes.jpg" lena_tif = IJ.openImage(path_tif) lena_tif.show() IJ.saveAs(lena_tif, "Jpeg", path_jpg) for i in range(201): lena_jpg = IJ.openImage(path_jpg) IJ.saveAs(lena_jpg, "Jpeg", path_jpg) IJ.run(lena_jpg, "32-bit", "") IJ.run(lena_tif, "32-bit", "") lena_tif.show() lena_jpg.show() ic = ImageCalculator() imp_sub = ic.run("Subtract create 32-bit", lena_jpg, lena_tif) IJ.run(imp_sub, "Enhance Contrast", "saturated=0.35") IJ.run(imp_sub, "8-bit", "") imp_sub.show()
def startTracking(filepath, fdir, ffile, filename): outpath = fdir troutpath = fdir + separator + ffile + separator + "tracked" + separator stackoutpath = fdir + separator + ffile + separator + "stacks" + separator pixwidth = 0.647 interval_sec = 600 #pr if "141006" in fdir: interval_sec = 600 elif "141117" in fdir: interval_sec = 300 elif "141215" in fdir: interval_sec = 300 if not os.path.isdir(outpath): os.mkdir(outpath) if not os.path.isdir(troutpath): os.mkdir(troutpath) if not os.path.isdir(stackoutpath): os.mkdir(stackoutpath) print 'filepath: ', filepath #pr print 'fdir: ', fdir #pr print 'ffile: ', ffile #pr IJ.run("Image Sequence...", "open=" + filepath + " file=" + filename + " sort") #pr #IJ.run("Image Sequence...", "open=" + filepath + " file=molm sort"); #pr imp = WindowManager.getCurrentImage() imptitle = imp.getTitle() nframes = imp.getNSlices() IJ.run( imp, "Properties...", "channels=1 slices=1 frames=" + str(nframes) + " unit=inch pixel_width=" + str(pixwidth) + " pixel_height=" + str(pixwidth) + " voxel_depth=1.0000 frame=[" + str(interval_sec) + " sec]") IJ.run(imp, "Duplicate...", "title=" + imptitle + "_dup duplicate") imp_dup = WindowManager.getImage(imptitle + "_dup") IJ.run(imp_dup, "Gaussian Blur...", "sigma=50 stack") ic = ImageCalculator() imp_corr = ic.run("Divide create 32-bit stack", imp, imp_dup) imp_corr.setTitle(imptitle + "_corrected") imp_corr.show() imp.changes = False imp.close() imp_dup.changes = False imp_dup.close() IJ.run(imp_corr, "8-bit", "") IJ.run( imp_corr, "Normalize Local Contrast", "block_radius_x=100 block_radius_y=100 standard_deviations=1 stretch stack" ) IJ.saveAs(imp_corr, "Tiff", stackoutpath + separator + imptitle + "_corrected.tif") IJ.run(imp_corr, "Duplicate...", "title=" + imptitle + "_bg duplicate") imp_bg = WindowManager.getImage(imptitle + "_bg") #Prefs.blackBackground = True; IJ.setAutoThreshold(imp_bg, "MinError dark") IJ.run(imp_bg, "Convert to Mask", "stack") IJ.run(imp_bg, "Analyze Particles...", "size=10000-Infinity show=Masks stack") imp_bg.changes = False imp_bg.close() imp_bgmask = WindowManager.getImage("Mask of " + imptitle + "_bg") ic = ImageCalculator() imp_corr_wobg = ic.run("Subtract create stack", imp_corr, imp_bgmask) imp_corr_wobg.setTitle(imptitle + "_corrected_womask") imp_corr_wobg.show() IJ.saveAs(imp_corr_wobg, "Tiff", stackoutpath + separator + imptitle + "_corrected_womask.tif") #pr # pr: substract average frames zp = ZProjector(imp_corr_wobg) zp.setMethod(ZProjector.AVG_METHOD) zp.doProjection() zpimp = zp.getProjection() zpimp.show() imp_corr_wobg_sub = ImageCalculator().run("Subtract create stack", imp_corr_wobg, zpimp) imp_corr_wobg_sub.show() #imp_corr_wobg.changes = False #imp_corr_wobg.close() # pr: subtract average frames (END) IJ.saveAs( imp_corr_wobg_sub, "Tiff", stackoutpath + separator + imptitle + "_corrected_womask_substracted.tif") #pr IJ.saveAs( zpimp, "Tiff", stackoutpath + separator + imptitle + "_corrected_womask_avg.tif") #commented out: pr #IJ.saveAs(imp_corr_wobg, "Tiff", stackoutpath+separator+imptitle+"_corrected_womask.tif"); IJ.saveAs(imp_bgmask, "Tiff", stackoutpath + separator + imptitle + "_bgmask.tif") print(stackoutpath + separator + imptitle + "_corrected_womask_substracted.tif") print(stackoutpath + separator + imptitle + "_corrected_womask_avg.tif") print(stackoutpath + separator + imptitle + "_bgmask.tif") imp_corr.changes = False imp_corr.close() imp_bgmask.changes = False imp_bgmask.close() imp_corr_wobg.changes = False imp_corr_wobg.close() #imp_corr_wobg_sub.changes = False #imp_corr_wobg_sub.close() zpimp.changes = False zpimp.close() #IJ.log(System.getProperty("os.name")) #IJ.log(fdir) return imp_corr_wobg_sub
from ij import IJ from ij.plugin import ImageCalculator imp1 = IJ.getImage() imp2 = imp1.duplicate() IJ.run(imp2, "Minimum...", "radius=10") IJ.run(imp2, "Maximum...", "radius=10") ic = ImageCalculator() imp3 = ic.run("Subtract create", imp1, imp2) imp3.show()
mask.setTitle('mask_'+repr(i)) list_x3.append( mask )#almaceno la mascara en la lista correspondiente #cierro ventanas que no preciso x2_aux.close() img.close() # #SKELETONIZE for i in range(stepNumber): skeleton = list_x3[i].duplicate() skeleton.setTitle('skeleton_'+repr(i)) IJ.run(skeleton, "Skeletonize (2D/3D)", "");#se corre el plugin sobre la ventana activa que es mask #recorto con la máscara más restrictiva ("la mas corta") skeleton = ic.run("AND create stack", list_x3[-1] ,skeleton ) list_x4.append( skeleton )#guardo el esqueleto #skeleton.show() #ADD mask para sumar todos los skeletons for i in range(stepNumber): skeleton = list_x4[i] if i==0:#en caso que esté en la primera iteración sum_skeletons = skeleton sum_skeletons.setTitle('sum_skeletons_'+repr(i)) #sum_skeletons.show() else: sum_skeletons.setTitle('sum_skeletons_'+repr(i)) #sum_skeletons.show() sum_skeletons = ic.run("Add create stack", sum_skeletons , skeleton )
gd.showDialog() ## Does simple interpolation of the ROIs through the stack if len(sliceList)>0: sliceList.sort(reverse=True) for sl in range(theImage.getNSlices()): if (sl+1) < sliceList[-1]: maskImage.setSliceWithoutUpdate(sliceList[-1]) activeIp = maskImage.getProcessor().duplicate() elif (sl+1) > sliceList[0]: maskImage.setSliceWithoutUpdate(sliceList[0]) activeIp = maskImage.getProcessor().duplicate() else: isFound = False for mark in sliceList: dist = sl+1 - mark if dist >= 0 and not isFound: isFound = True refSlice = mark maskImage.setSliceWithoutUpdate(refSlice) activeIp = maskImage.getProcessor().duplicate() maskImage.setSliceWithoutUpdate(sl+1) maskImage.setProcessor(activeIp) ## Computes the overlay image ic = ImageCalculator() resultImage = ic.run("AND create stack",theImage,maskImage) resultImage.show() maskImage.close()
def addImages(self,img1, img2): ic = ImageCalculator() sumImage = ic.run("Add create stack",img1,img2) return(sumImage)
def process(subFolder, outputDirectory, filename): #IJ.close() imp = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", ".tif")) imp.show() # Get the pixel values from the xml file for file in os.listdir(inputDirectory + subFolder): if file.endswith('.xml'): xml = os.path.join(inputDirectory + subFolder, file) xml = "C:/Users/Harris/Desktop/test_xml_for_parsing_pixel.xml" element_tree = ET.parse(xml) root = element_tree.getroot() for dimensions in root.iter('DimensionDescription'): num_pixels = int(dimensions.attrib['NumberOfElements']) if dimensions.attrib['Unit'] == "m": length = float(dimensions.attrib['Length']) * 1000000 else: length = float(dimensions.attrib['Length']) pixel_length = length / num_pixels else: pixel_length = 0.8777017 IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=" + str(pixel_length) + " pixel_height=" + str(pixel_length) + " voxel_depth=25400.0508001") ic = ImageConverter(imp) ic.convertToGray8() #IJ.setThreshold(imp, 2, 255) #Automatically selects the area of the organoid based on automated thresholding and creates a mask to be applied on #all other images IJ.setAutoThreshold(imp, "Mean dark no-reset") IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Analyze Particles...", "size=100000-Infinity add select") rm = RoiManager.getInstance() num_roi = rm.getCount() for i in num_roi: imp = getCurrentImage() rm.select(imp, i) IJ.setBackgroundColor(0, 0, 0) IJ.run(imp, "Clear Outside", "") IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Remove Outliers...", "radius=5" + " threshold=50" + " which=Dark") IJ.run(imp, "Remove Outliers...", "radius=5" + " threshold=50" + " which=Bright") # Save the mask and open it IJ.saveAs("tiff", inputDirectory + '/mask' + i) mask = IJ.openImage(inputDirectory + '/mask' + i + '.tif') if not displayImages: imp.changes = False imp.close() images = [None] * 5 intensities = [None] * 5 blobsarea = [None] * 5 blobsnuclei = [None] * 5 bigAreas = [None] * 5 imp.close() # Loop to open all the channel images for chan in channels: v, x = chan images[x] = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", "_ch0" + str(x) + ".tif")) # Apply Mask on all the images and save them into an array apply_mask = ImageCalculator() images[x] = apply_mask.run("Multiply create 32 bit", mask, images[x]) ic = ImageConverter(images[x]) ic.convertToGray8() imp = images[x] # Calculate the intensities for each channel as well as the organoid area for roi in rm.getRoisAsArray(): imp.setRoi(roi) stats_i = imp.getStatistics(Measurements.MEAN | Measurements.AREA) intensities[x] = stats_i.mean bigAreas[x] = stats_i.area rm.close() # Opens the ch00 image and sets default properties #Get the pixel values from the xml file for file in os.listdir(subFolder): if file.endswith('.xml'): xml = os.path.join(inputDirectory + subFolder, file) xml = "C:/Users/Harris/Desktop/test_xml_for_parsing_pixel.xml" element_tree = ET.parse(xml) root = element_tree.getroot() for dimensions in root.iter('DimensionDescription'): num_pixels = int(dimensions.attrib['NumberOfElements']) if dimensions.attrib['Unit'] == "m": length = float(dimensions.attrib['Length']) * 1000000 else: length = float(dimensions.attrib['Length']) pixel_length = length / num_pixels else: pixel_length = 0.8777017 imp = IJ.openImage(inputDirectory + subFolder + '/' + filename) imp = apply_mask.run("Multiply create 32 bit", mask, imp) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=" + str(pixel_length) + "pixel_height=" + str(pixel_length) + "voxel_depth=25400.0508001") # Sets the threshold and watersheds. for more details on image processing, see https://imagej.nih.gov/ij/developer/api/ij/process/ImageProcessor.html ic = ImageConverter(imp) ic.convertToGray8() IJ.run(imp, "Remove Outliers...", "radius=2" + " threshold=50" + " which=Dark") IJ.run(imp, "Gaussian Blur...", "sigma=" + str(blur)) IJ.setThreshold(imp, lowerBounds[0], 255) if displayImages: imp.show() IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Watershed", "") if not displayImages: imp.changes = False imp.close() # Counts and measures the area of particles and adds them to a table called areas. Also adds them to the ROI manager table = ResultsTable() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 15, 9999999999999999, 0.2, 1.0) pa.setHideOutputImage(True) # imp = impM # imp.getProcessor().invert() pa.analyze(imp) areas = table.getColumn(0) # This loop goes through the remaining channels for the other markers, by replacing the ch00 at the end with its corresponding channel # It will save all the area fractions into a 2d array called areaFractionsArray areaFractionsArray = [None] * 5 for chan in channels: v, x = chan # Opens each image and thresholds imp = images[x] IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) ic = ImageConverter(imp) ic.convertToGray8() IJ.setThreshold(imp, lowerBounds[x], 255) if displayImages: imp.show() WaitForUserDialog("Title", "Adjust Threshold for Marker " + v).show() IJ.run(imp, "Convert to Mask", "") # Measures the area fraction of the new image for each ROI from the ROI manager. areaFractions = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA_FRACTION) areaFractions.append(stats.areaFraction) # Saves the results in areaFractionArray areaFractionsArray[x] = areaFractions roim.close() for chan in channels: v, x = chan imp = images[x] imp.deleteRoi() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 15, 9999999999999999, 0.2, 1.0) pa.analyze(imp) blobs = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA) blobs.append(stats.area) blobsarea[x] = sum( blobs ) #take this out and use intial mask tissue area from the beginning blobsnuclei[x] = len(blobs) if not displayImages: imp.changes = False imp.close() roim.reset() roim.close() imp.close() # Creates the summary dictionary which will correspond to a single row in the output csv, with each key being a column summary = {} summary['Image'] = filename summary['Directory'] = subFolder # Adds usual columns summary['size-average'] = 0 summary['#nuclei'] = 0 summary['all-negative'] = 0 summary['too-big-(>' + str(tooBigThreshold) + ')'] = 0 summary['too-small-(<' + str(tooSmallThreshold) + ')'] = 0 # Creates the fieldnames variable needed to create the csv file at the end. fieldnames = [ 'Name', 'Directory', 'Image', 'size-average', 'too-big-(>' + str(tooBigThreshold) + ')', 'too-small-(<' + str(tooSmallThreshold) + ')', '#nuclei', 'all-negative' ] # Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei) summary["organoid-area"] = bigAreas[x] fieldnames.append("organoid-area") for chan in channels: v, x = chan summary[v + "-positive"] = 0 fieldnames.append(v + "-positive") summary[v + "-intensity"] = intensities[x] fieldnames.append(v + "-intensity") summary[v + "-blobsarea"] = blobsarea[x] fieldnames.append(v + "-blobsarea") summary[v + "-blobsnuclei"] = blobsnuclei[x] fieldnames.append(v + "-blobsnuclei") # Adds the column for colocalization between first and second marker if len(channels) > 2: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-positive') # Adds the columns for colocalization between all three markers if len(channels) > 3: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[2][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive') # Loops through each particle and adds it to each field that it is True for. areaCounter = 0 for z, area in enumerate(areas): log.write(str(area)) log.write("\n") if area > tooBigThreshold: summary['too-big-(>' + str(tooBigThreshold) + ')'] += 1 elif area < tooSmallThreshold: summary['too-small-(<' + str(tooSmallThreshold) + ')'] += 1 else: summary['#nuclei'] += 1 areaCounter += area temp = 0 for chan in channels: v, x = chan if areaFractionsArray[x][z] > areaFractionThreshold[ 0]: # theres an error here im not sure why. i remember fixing it before summary[chan[0] + '-positive'] += 1 if x != 0: temp += 1 if temp == 0: summary['all-negative'] += 1 if len(channels) > 2: if areaFractionsArray[1][z] > areaFractionThreshold[1]: if areaFractionsArray[2][z] > areaFractionThreshold[2]: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] += 1 if len(channels) > 3: if areaFractionsArray[1][z] > areaFractionThreshold[1]: if areaFractionsArray[3][z] > areaFractionThreshold[3]: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[2][z] > areaFractionThreshold[2]: if areaFractionsArray[3][z] > areaFractionThreshold[3]: summary[channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[1][z] > areaFractionThreshold[1]: summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 # Calculate the average of the particles sizes if float(summary['#nuclei']) > 0: summary['size-average'] = round(areaCounter / summary['#nuclei'], 2) # Opens and appends one line on the final csv file for the subfolder (remember that this is still inside the loop that goes through each image) with open(outputDirectory + "/" + outputName + ".csv", 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore', lineterminator='\n') if os.path.getsize(outputDirectory + "/" + outputName + ".csv") < 1: writer.writeheader() writer.writerow(summary) IJ.run(imp, "Close All", "")
def main(): DEBUG = False CN = [c.strip() for c in channel_names.split(",")] if DEBUG: imp1, imp2, imp3 = open_test() else: imp1, imp2, imp3 = open_msr(str(msr_fn)) msr_fn_base = os.path.basename(str(msr_fn)) signed2unsigned16(imp1) signed2unsigned16(imp2) signed2unsigned16(imp3) imp1.updateAndDraw() imp2.updateAndDraw() imp3.updateAndDraw() IJ.run(imp1, "Enhance Contrast", "saturated=0.35") IJ.run(imp2, "Enhance Contrast", "saturated=0.35") IJ.run(imp3, "Enhance Contrast", "saturated=0.35") cal = imp1.getCalibration() IMAGE_AREA_UM = cal.pixelWidth * imp1.getWidth() * cal.pixelHeight * imp1.getHeight() t1 = apply_mask(imp1, sigma, CN[0], is_auto_thresh) t2 = apply_mask(imp2, sigma, CN[1], is_auto_thresh) t3 = apply_mask(imp3, sigma, CN[2], is_auto_thresh) results = ResultsTable() results.setHeading(0, "Channel") results.setHeading(1, "Count") results.setHeading(2, "Surface area (um)") results.setHeading(3, "Surface area (%)") results.setHeading(4, "Surface signal") #results.setHeading(5, "Threshold used") def add_to_table(channel, c, a, s): results.incrementCounter() results.setValue(0, results.getCounter()-1, channel) results.addValue(1, c) results.addValue(2, a) results.addValue(3, 100 * a /IMAGE_AREA_UM) results.addValue(4, s) #results.setLabel(msr_fn_base, results.getCounter()-1) imp1_mask, c,a,s = analyze(imp1, min_area) add_to_table(CN[0], c, a, s) #results.addValue(4, t1) imp2_mask, c,a,s = analyze(imp2, min_area) add_to_table(CN[1], c, a,s) #results.addValue(4, t2) imp3_mask, c,a,s = analyze(imp3, min_area) add_to_table(CN[2], c, a,s) #results.addValue(4, t3) # IJ.run(imp1, "Enhance Contrast", "saturated=0.35") # IJ.run(imp2, "Enhance Contrast", "saturated=0.35") # IJ.run(imp3, "Enhance Contrast", "saturated=0.35") imp_raw = RGBStackMerge.mergeChannels([imp1, imp2, imp3], True) luts = list(imp_raw.getLuts()) imp_raw.setLuts([luts[2], luts[0], luts[1]] ) imp_raw.setTitle(msr_fn_base ) imp_raw.show() if save_raw: save_base_fn = os.path.splitext(str(msr_fn))[0] IJ.save(imp_raw, save_base_fn + ".tif") IJ.run(imp1, "Convert to Mask", "") IJ.run(imp2, "Convert to Mask", "") IJ.run(imp3, "Convert to Mask", "") ic = ImageCalculator() imp12 = ic.run("Muliply create", imp1, imp2) imp13 = ic.run("Muliply create", imp1, imp3) imp23 = ic.run("Muliply create", imp2, imp3) imp123 = ic.run("Muliply create", imp12, imp3) imp12_mask, c,a,s = analyze(imp12, min_area) add_to_table("{}+{}".format(CN[0],CN[1]), c, a, -1) imp13_mask, c,a,s = analyze(imp13, min_area) add_to_table("{}+{}".format(CN[0],CN[2]), c, a, -1) imp23_mask,c,a,s = analyze(imp23, min_area) add_to_table("{}+{}".format(CN[1],CN[2]), c, a, -1) imp123_mask,c,a,s = analyze(imp123, min_area) add_to_table("{}+{}+{}".format(CN[0],CN[1], CN[2]), c, a, -1) title = "Coloco3surf {}".format(msr_fn_base) results.show(title) imp_merge = RGBStackMerge.mergeChannels([imp1_mask, imp2_mask, imp3_mask, imp12_mask, imp13_mask, imp23_mask, imp123_mask], False) luts = list(imp_merge.getLuts()) imp_merge.setLuts([luts[2], luts[0], luts[1]] + luts[3:]) imp_merge.setTitle(title) imp_merge.show() if save_surf: save_base_fn = os.path.splitext(str(msr_fn))[0] IJ.save(imp_merge, save_base_fn + "_surfaces.tif") IJ.log("Done")
def analyse(cwd, user, imagefolder, stats, experiments, multi, Rloc2, subfoldernames, names, statsfolderPath, cwdR): """ Main image analysis Gets user image analysis settings from the .csv file. If multiple experiments have been selected by the user (multi) each subfolder will be looped through. A nested loop will then interate through each .tif image and analyse. A .csv file will be produced for each folder analysed with the name of each image and its % neurite density and % myelination. A summary csv file will also be produced with the average % neurite density and % myelination for each subfolder. If statistical analysis has been selected (stats) then MyelinJ's Rscript will be run via the command line. If multple experiments is not selected then all of the images within the selected folder will be analysed together and no summary .csv will be produced. Independ of the analysis settings defined, a processed myelin channel image and a processed neurite channel image will be saved. The images can be any number of subdirectories (folders within folders). Parameters ---------- cwd : string Path for current working directory (location of MyelinJ folder in Fiji). user: string User name imagefolder: string Path to .tiff image folder(s) defined by user. stats: boolean Perform statistical analysing using R? experiments: 2D list of strings list of all the subfolders (experiments) that are in each experimental condition. multi: boolean Analyse multiple experiments? Rloc2: string file path to Rscript location subfoldernames: string name of each subfolder which denoates each individual experiment, if multple experiments are being analysed. names: array array of textfields for each experimental condition defined by user. User will enter the name of each experimental condition. statsfolderPath: string file path to the create statsfolder. cwdR: string file path to MyelinJstats.R """ # read settings from the user name CSV bg = False readsettings = [] imagenames = [] neuritedensity = [] myelinoverlay = [] myelinaverage2 = [] neuriteaverage2 = [] root = cwd filename = user fullpath = os.path.join(root, filename) f = open(fullpath, 'rb') readCSV = csv.reader(f) for row in readCSV: readsettings.append(row[0]) readsettings.append(row[1]) readsettings.append(row[2]) readsettings.append(row[3]) readsettings.append(row[4]) readsettings.append(row[5]) readsettings.append(row[6]) f.close() i = 0 for i in range(len(subfoldernames)): # if multiple experimental conditions has been selected each folder is treated as a # separate experiment and looped through separately otherwise all folders will be # treated as one experiment this only works for sub directories within the main folder. # Further folders will be ignored (each image can be in its own folder for example) if multi is True: # if multiple experiments are being analysed the file path is changed to the # current subfolder settings2 = os.path.join(imagefolder, subfoldernames[i]) if "Windows" in OS: settings2 = settings2 + "\\" elif "Mac" in OS: settings2 = settings2 + "/" else: settings2 = imagefolder # loop through all .tiff files in location for root, dirs, files in os.walk(settings2): for name in files: if name.endswith((".tif")): imagenames.append(os.path.join(name)) # open .tiff image, split channels and # convert to 8bit grey scale. imp = IJ.openImage(os.path.join(root, name)) g = int(readsettings[4]) r = int(readsettings[5]) imp = ChannelSplitter.split(imp) green = imp[g] red = imp[r] conv = ImageConverter(red) conv.convertToGray8() conv = ImageConverter(green) conv.convertToGray8() # thresholding to select cell bodies green2 = green.duplicate() if (readsettings[0] != "0") or (readsettings[1] != "0"): bg = True IJ.setAutoThreshold(green2, readsettings[2]) IJ.setRawThreshold(green2, int(readsettings[0]), int(readsettings[1]), None) Prefs.blackBackground = True IJ.run(green2, "Convert to Mask", "") IJ.run(green2, "Invert LUT", "") if readsettings[7] != "0": IJ.run(green2, "Make Binary", "") IJ.run( green2, "Remove Outliers...", "radius=" + readsettings[7] + " threshold=50 which=Dark") # CLAHE and background subtraction if readsettings[8] == "True": mpicbg.ij.clahe.Flat.getFastInstance().run( green, 127, 256, 3, None, False) if readsettings[9] == "True": calc = ImageCalculator() green = calc.run("Subtract create", green, red) elif readsettings[6] == "True": IJ.run(green, "Subtract Background...", "rolling=50") if readsettings[10] != "0": IJ.run(green, "Subtract...", "value=" + readsettings[10]) # run frangi vesselness pixelwidth = str(green.getCalibration().pixelWidth) IJ.run( green, "Frangi Vesselness (imglib, experimental)", "number=1 minimum=" + pixelwidth + " maximum=" + pixelwidth) green = IJ.getImage() # convert frangi vesselness image to 8bit grey scale conv = ImageConverter(green) conv.convertToGray8() IJ.run(green, "Convert to Mask", "") # remove cell bodies if bg is True: green = ImageCalculator().run("Subtract create", green, green2) # run grey scale morphology filter from MorpholibJ if readsettings[11] != "0": green = green.getProcessor() algo = BoxDiagonalOpeningQueue() algo.setConnectivity(4) result = algo.process(green, int(readsettings[11])) green = ImagePlus("result", result) IJ.run(green, "Invert LUT", "") if len(readsettings) > 14: # sparse neurite image analysis if readsettings[15] == "True": IJ.run( red, "Enhance Local Contrast (CLAHE)", "blocksize=127 histogram=256 maximum=3 mask=*None* fast_(less_accurate)" ) if readsettings[14] == "True": IJ.run(red, "Subtract Background...", "rolling=50") IJ.setAutoThreshold(red, readsettings[16]) IJ.setRawThreshold(red, int(readsettings[17]), int(readsettings[18]), None) IJ.run(red, "Convert to Mask", "") IJ.run(red, "Invert LUT", "") else: # dense neurite image analysis IJ.run( red, "Normalize Local Contrast", "block_radius_x=40 block_radius_y=40 standard_deviations=" + readsettings[12] + " center stretch") IJ.run(red, "Auto Threshold", "method=Default white") IJ.run(red, "Invert LUT", "") if readsettings[3] == "True": IJ.run(red, "Despeckle", "") IJ.saveAs(red, "Jpeg", settings2 + name + "neurites") # get number of neurite pixels # get number of neurite pixels statsneurite = red.getProcessor() statsneurite = statsneurite.getHistogram() neuritedensity.append(statsneurite[255]) IJ.saveAs(green, "Jpeg", settings2 + name + "myelinFinal") # get number of myelin pixels statsmyelin = green.getProcessor() statsmyelin = statsmyelin.getHistogram() myelinoverlay.append(statsmyelin[255]) closeallimages() # get pixel total of image whitepixels = (statsneurite[0]) blackpixels = (statsneurite[255]) totalpixels = whitepixels + blackpixels totalpixels = [totalpixels] * len(neuritedensity) # for each image calculate % myelination as number of myelin pixels # divided by the number of neurite pixels * 100 myelinoverlay = [ x1 / x2 * 100 for (x1, x2) in zip(myelinoverlay, neuritedensity) ] myelinaverage = sum(myelinoverlay) / len(myelinoverlay) myelinaverage2.append(myelinaverage) # for each image calculate % neurite density as neurite pixels divided # by the total number of pixels in the image * 100. neuritedensity = [ x1 / x2 * 100 for (x1, x2) in zip(neuritedensity, totalpixels) ] neuriteaverage = sum(neuritedensity) / len(neuritedensity) neuriteaverage2.append(neuriteaverage) name = "Image names" green = "% myelination" red = "% neurite density" imagenames = [name] + imagenames neuritedensity = [red] + neuritedensity myelinoverlay = [green] + myelinoverlay result = [] result.append(imagenames) result.append(neuritedensity) result.append(myelinoverlay) root = settings2 filename = "Results.csv" fullpath = os.path.join(root, filename) f = open(fullpath, 'wb') writer = csv.writer(f) for d in range(len(result)): row = [result[d]] writer.writerows(row) f.close() # must be reset to 0 for each iteration. y = 0 r = 0 # if statistical analysis is being performed the results .csv file # is also saved to a subfolder within the statistical analysis folder # which denotes the experimental condition the results belong to. if stats is True: # nested for loop to identify correct experimental condition # for the current subfolder being analysed. for y in range(0, len(experiments)): for r in range(0, len(experiments[0])): if experiments[y][r] == subfoldernames[i]: if "Windows" in OS: root = imagefolder + "\\statistical analysis\\" + names[ y].getText() elif "Mac" in OS: root = imagefolder + "/statistical analysis/" + names[ y].getText() filename = subfoldernames[i] + ".csv" fullpath = os.path.join(root, filename) f = open(fullpath, 'wb') writer = csv.writer(f) for e in range(len(result)): row = [result[e]] writer.writerows(row) f.close() break cwd2 = os.getcwd() for files in os.listdir(cwd2): if files.endswith(".csv"): os.remove(os.path.join(cwd2, files)) imagenames = [] myelinoverlay = [] neuritedensity = [] # create .csv summary sheet with average % neurite density # and average % myelination for each subfolder (experiment). if multi is True: name = "Folder name" imagenames = [name] + subfoldernames neuritedensity = [red] + neuriteaverage2 myelinoverlay = [green] + myelinaverage2 result = [] result.append(imagenames) result.append(neuritedensity) result.append(myelinoverlay) if "Windows" in OS: root = imagefolder + "\\" elif "Mac" in OS: root = imagefolder + "/" filename = "Result-Summary.csv" fullpath = os.path.join(root, filename) f = open(fullpath, 'wb') writer = csv.writer(f) for p in range(len(result)): row = [result[p]] writer.writerows(row) f.close() imagenames = [] myelinoverlay = [] neuritedensity = [] # Run Rscript for statistical analysis via the command line if stats is True: cmd = Rloc2 + " " + cwdR + " " + statsfolderPath Runtime.getRuntime().exec(cmd) Finished()
#directory = image.getFileInfo() print(directory) #IJ.run(image, "Duplicate...", "duplicate") #image_orig = IJ.getImage() #IJ.run(image, "Convert to Mask", "method=Default background=Default calculate black"); for i in range(erosions): IJ.run(image, "Erode", "stack") for i in range(erosions): IJ.run(image, "Dilate", "stack") calc = ImageCalculator() print(image, image_orig) result = calc.run("Subtract create stack", image_orig, image) #IJ.run(result, "Invert", "stack") result.show() image.changes = False image.close() image_orig.close() IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") IJ.run( result, "Analyze Particles...", "size=" + str(min_size) + "-Infinity show=Masks display clear add stack") #result.close() rt = ResultsTable.getResultsTable() print("saving to " + str(directory) + "/protrusions.csv")
val_high = rt.getValueAsDouble(1,0) val_bleed = rt.getValueAsDouble(1,1) val_low = rt.getValueAsDouble(1,2) val_zero = rt.getValueAsDouble(1,3) val_target = val_high - val_low # scale_target = val_target / val_bleed scale_target = val_target / (val_bleed - val_zero) print scale_target gd = GenericDialog("Scale factor") gd.addNumericField("Scale factor on subtraction:",scale_target,3) gd.showDialog() if (gd.wasCanceled()): quit() scale = gd.getNextNumber() tempImage = image2.duplicate() for i in range(tempImage.getNSlices()): tempImage.setSliceWithoutUpdate(i+1) ip = tempImage.getProcessor() ip.subtract(val_zero) ip.multiply(scale) ic = ImageCalculator() newImage = ic.run("Subtract create stack",image1,tempImage) newImage.show() else: IJ.error("No images are open.")
EDM().toEDM(ip) segip = MaximumFinder().findMaxima( ip, 10, ImageProcessor.NO_THRESHOLD, MaximumFinder.SEGMENTED , False, False) #imp.show() segimp = ImagePlus("regions", segip) segimp.show() segimps, info, perRegionlist = getNucLabels(segimp) segimps.show() numregions = len(perRegionlist) print numregions ic = ImageCalculator() stack = ImageStack(impcentSeg.getWidth(), impcentSeg.getHeight()) for amask in perRegionlist: masked = ic.run("AND create", amask, impcentSeg) stack.addSlice(masked.getProcessor()) regionedimp = ImagePlus("regioned", stack) #regionedimp.show() resrt = ResultsTable() for i in range(regionedimp.getStackSize()): aregion = regionedimp.getStack().getProcessor(i+1) particleAnalysis(i, ImagePlus("extract", aregion), resrt) #resrt.show("data") rm = RoiManager() for i in range(resrt.getCounter()): cc = resrt.getValue("counts", i) if cc == 2:
if rm is None: RoiManager() rm = RoiManager.getInstance() rm.reset() rstable = ResultsTable() ImageCalculator = ImageCalculator() dc = DirectoryChooser("Choose a folder") folder = dc.getDirectory() mask = IJ.openImage(folder + "vessels_result.tif") mask.setTitle("Mask") for i in range(1, 4): imp = IJ.openImage(folder + "\\split\\C" + str(i) + "\\result_READY.tif") imp.setTitle("C") imp.show() imp = ImageCalculator.run("Min", imp, mask) imp = WindowManager.getImage("C") IJ.run(imp, "Find Maxima...", "prominence=20 output=[Point Selection]") mroi = imp.getRoi() IJ.run("Measure") table = rstable.getResultsTable() X = table.getColumn(6) Y = table.getColumn(7) with open(folder + "\\split\\C" + str(i) + "\\cells.csv", 'wb') as csvfile: w = csv.writer(csvfile, delimiter=',', quotechar="\"", quoting=csv.QUOTE_NONNUMERIC) w.writerow(X) w.writerow(Y) rm.addRoi(mroi) imp.close()
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters): # set calibration detectionParameters.setCalibration(inputImp) # calculate area of roi stats = inputImp.getStatistics() inputRoiArea = stats.area # get the bounding box of the active roi inputRec = inputRoi.getBounds() x1 = long(inputRec.getX()) y1 = long(inputRec.getY()) x2 = x1 + long(inputRec.getWidth()) - 1 y2 = y1 + long(inputRec.getHeight()) - 1 # crop the roi interval = FinalInterval(array([x1, y1, 0], 'l'), array([x2, y2, 2], 'l')) #cropped=ops.image().crop(interval, None, inputDataset.getImgPlus() ) cropped = ops.image().crop(inputDataset.getImgPlus(), interval) datacropped = data.create(cropped) display.createDisplay("cropped", datacropped) croppedPlus = IJ.getImage() # instantiate the duplicator and the substackmaker classes duplicator = Duplicator() substackMaker = SubstackMaker() # duplicate the roi duplicate = duplicator.run(croppedPlus) # convert duplicate of roi to HSB and get brightness IJ.run(duplicate, "HSB Stack", "") brightnessPlus = substackMaker.makeSubstack(duplicate, "3-3") brightness = ImgPlus(ImageJFunctions.wrapByte(brightnessPlus)) brightnessPlus.setTitle("Brightness") #brightnessPlus.show() # make another duplicate, split channels and get red duplicate = duplicator.run(croppedPlus) channels = ChannelSplitter().split(duplicate) redPlus = channels[0] red = ImgPlus(ImageJFunctions.wrapByte(redPlus)) # convert to lab IJ.run(croppedPlus, "Color Transformer", "colour=Lab") IJ.selectWindow('Lab') labPlus = IJ.getImage() croppedPlus.changes = False croppedPlus.close() # get the A channel APlus = substackMaker.makeSubstack(labPlus, "2-2") APlus.setTitle('A') #APlus.show() APlus.getProcessor().resetMinAndMax() #APlus.updateAndDraw() AThresholded = threshold(APlus, -10, 50) # get the B channel BPlus = substackMaker.makeSubstack(labPlus, "3-3") BPlus.setTitle('B') #BPlus.show() BPlus.getProcessor().resetMinAndMax() #BPlus.updateAndDraw() BThresholded = threshold(BPlus, -10, 50) # AND the Athreshold and Bthreshold to get a map of the red pixels ic = ImageCalculator() redMask = ic.run("AND create", AThresholded, BThresholded) IJ.run(redMask, "Divide...", "value=255") labPlus.close() fast = True # threshold the spots from the red channel if (fast == False): thresholdedred = SpotDetectionGray(red, data, display, ops, "triangle") impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped") else: impthresholdedred = SpotDetection2(redPlus) # threshold the spots from the brightness channel if (fast == False): thresholded = SpotDetectionGray(brightness, data, display, ops, "triangle") impthresholded = ImageJFunctions.wrap(thresholded, "wrapped") else: impthresholded = SpotDetection2(brightnessPlus) # or the thresholding results from red and brightness channel impthresholded = ic.run("OR create", impthresholded, impthresholdedred) roim = RoiManager(True) # convert to mask Prefs.blackBackground = True IJ.run(impthresholded, "Convert to Mask", "") def isRed(imp, roi): stats = imp.getStatistics() if (stats.mean > detectionParameters.porphyrinRedPercentage): return True else: return False def notRed(imp, roi): stats = imp.getStatistics() if (stats.mean > detectionParameters.porphyrinRedPercentage): return False else: return True roiClone = inputRoi.clone() roiClone.setLocation(0, 0) Utility.clearOutsideRoi(impthresholded, roiClone) impthresholded.show() countParticles(impthresholded, roim, detectionParameters.porphyrinMinSize, detectionParameters.porphyrinMaxSize, \ detectionParameters.porphyrinMinCircularity, detectionParameters.porphyrinMaxCircularity) uvPoreList = [] for roi in roim.getRoisAsArray(): uvPoreList.append(roi.clone()) #allList=uvPoreList+closedPoresList+openPoresList # count particles that are porphyrins (red) porphyrinList = CountParticles.filterParticlesWithFunction( redMask, uvPoreList, isRed) # count particles that are visible on uv but not porphyrins sebumList = CountParticles.filterParticlesWithFunction( redMask, uvPoreList, notRed) # for each roi add the offset such that the roi is positioned in the correct location for the # original image [ roi.setLocation(roi.getXBase() + x1, roi.getYBase() + y1) for roi in uvPoreList ] # draw the ROIs on to the image inputImp.getProcessor().setColor(Color.green) IJ.run(inputImp, "Line Width...", "line=3") inputImp.getProcessor().draw(inputRoi) IJ.run(inputImp, "Line Width...", "line=1") [ CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in porphyrinList ] [ CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumList ] inputImp.updateAndDraw() # calculate stats for the UV visible particles detectionParameters.setCalibration(APlus) statsDictUV = CountParticles.calculateParticleStatsUV( APlus, BPlus, redMask, roim.getRoisAsArray()) totalUVPoreArea = 0 for area in statsDictUV['Areas']: totalUVPoreArea = totalUVPoreArea + area averageUVPoreArea = totalUVPoreArea / len(statsDictUV['Areas']) poreDiameter = 0 for diameter in statsDictUV['Diameters']: poreDiameter = poreDiameter + diameter poreDiameter = poreDiameter / len(statsDictUV['Diameters']) redTotal = 0 for red in statsDictUV['redPercentage']: redTotal = redTotal + red redAverage = redTotal / len(statsDictUV['redPercentage']) statslist = [len(porphyrinList), 100 * redAverage] statsheader = [Messages.Porphyrins, Messages.PercentageRedPixels] print("Roi Area: " + str(inputRoiArea)) print("Total Pore Area: " + str(totalUVPoreArea)) print("Average Pore Area: " + str(averageUVPoreArea)) print str(len(uvPoreList)) + " " + str(len(porphyrinList)) + " " + str( len(sebumList)) + " " + str( 100 * totalUVPoreArea / inputRoiArea) + " " + str(100 * redAverage) print "cp min circularity" + str( detectionParameters.closedPoresMinCircularity) + ":" + str( detectionParameters.closedPoresMinSize) # close the thresholded image impthresholded.changes = False impthresholded.close() return uvPoreList, statslist, statsheader
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters): # set calibration detectionParameters.setCalibration(inputImp); # calculate area of roi stats=inputImp.getStatistics() inputRoiArea=stats.area # get the bounding box of the active roi inputRec = inputRoi.getBounds() x1=long(inputRec.getX()) y1=long(inputRec.getY()) x2=x1+long(inputRec.getWidth())-1 y2=y1+long(inputRec.getHeight())-1 # crop the roi interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') ) #cropped=ops.image().crop(interval, None, inputDataset.getImgPlus() ) cropped=ops.image().crop(inputDataset.getImgPlus() , interval) datacropped=data.create(cropped) display.createDisplay("cropped", datacropped) croppedPlus=IJ.getImage() # instantiate the duplicator and the substackmaker classes duplicator=Duplicator() substackMaker=SubstackMaker() # duplicate the roi duplicate=duplicator.run(croppedPlus) # convert duplicate of roi to HSB and get brightness IJ.run(duplicate, "HSB Stack", ""); brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3") brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus)) brightnessPlus.setTitle("Brightness") #brightnessPlus.show() # make another duplicate, split channels and get red duplicate=duplicator.run(croppedPlus) channels=ChannelSplitter().split(duplicate) redPlus=channels[0] red=ImgPlus(ImageJFunctions.wrapByte(redPlus)) # convert to lab IJ.run(croppedPlus, "Color Transformer", "colour=Lab") IJ.selectWindow('Lab') labPlus=IJ.getImage() croppedPlus.changes=False croppedPlus.close() # get the A channel APlus=substackMaker.makeSubstack(labPlus, "2-2") APlus.setTitle('A') #APlus.show() APlus.getProcessor().resetMinAndMax() #APlus.updateAndDraw() AThresholded=threshold(APlus, -10, 50) # get the B channel BPlus=substackMaker.makeSubstack(labPlus, "3-3") BPlus.setTitle('B') #BPlus.show() BPlus.getProcessor().resetMinAndMax() #BPlus.updateAndDraw() BThresholded=threshold(BPlus, -10, 50) # AND the Athreshold and Bthreshold to get a map of the red pixels ic = ImageCalculator(); redMask = ic.run("AND create", AThresholded, BThresholded); IJ.run(redMask, "Divide...", "value=255"); labPlus.close() fast=True # threshold the spots from the red channel if (fast==False): thresholdedred=SpotDetectionGray(red, data, display, ops, "triangle") impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped") else: impthresholdedred=SpotDetection2(redPlus) # threshold the spots from the brightness channel if (fast==False): thresholded=SpotDetectionGray(brightness, data, display, ops, "triangle") impthresholded=ImageJFunctions.wrap(thresholded, "wrapped") else: impthresholded=SpotDetection2(brightnessPlus) # or the thresholding results from red and brightness channel impthresholded = ic.run("OR create", impthresholded, impthresholdedred); roim=RoiManager(True) # convert to mask Prefs.blackBackground = True IJ.run(impthresholded, "Convert to Mask", "") def isRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.porphyrinRedPercentage): return True else: return False def notRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.porphyrinRedPercentage): return False else: return True roiClone=inputRoi.clone() roiClone.setLocation(0,0) Utility.clearOutsideRoi(impthresholded, roiClone) impthresholded.show() countParticles(impthresholded, roim, detectionParameters.porphyrinMinSize, detectionParameters.porphyrinMaxSize, \ detectionParameters.porphyrinMinCircularity, detectionParameters.porphyrinMaxCircularity) uvPoreList=[] for roi in roim.getRoisAsArray(): uvPoreList.append(roi.clone()) #allList=uvPoreList+closedPoresList+openPoresList # count particles that are porphyrins (red) porphyrinList=CountParticles.filterParticlesWithFunction(redMask, uvPoreList, isRed) # count particles that are visible on uv but not porphyrins sebumList=CountParticles.filterParticlesWithFunction(redMask, uvPoreList, notRed) # for each roi add the offset such that the roi is positioned in the correct location for the # original image [roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in uvPoreList] # draw the ROIs on to the image inputImp.getProcessor().setColor(Color.green) IJ.run(inputImp, "Line Width...", "line=3"); inputImp.getProcessor().draw(inputRoi) IJ.run(inputImp, "Line Width...", "line=1"); [CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in porphyrinList] [CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumList] inputImp.updateAndDraw() # calculate stats for the UV visible particles detectionParameters.setCalibration(APlus) statsDictUV=CountParticles.calculateParticleStatsUV(APlus, BPlus, redMask, roim.getRoisAsArray()) totalUVPoreArea=0 for area in statsDictUV['Areas']: totalUVPoreArea=totalUVPoreArea+area averageUVPoreArea=totalUVPoreArea/len(statsDictUV['Areas']) poreDiameter=0 for diameter in statsDictUV['Diameters']: poreDiameter=poreDiameter+diameter poreDiameter=poreDiameter/len(statsDictUV['Diameters']) redTotal=0 for red in statsDictUV['redPercentage']: redTotal=redTotal+red redAverage=redTotal/len(statsDictUV['redPercentage']) statslist=[len(porphyrinList), 100*redAverage]; statsheader=[Messages.Porphyrins, Messages.PercentageRedPixels] print("Roi Area: "+str(inputRoiArea)) print("Total Pore Area: "+str(totalUVPoreArea)) print("Average Pore Area: "+str(averageUVPoreArea)) print str(len(uvPoreList))+" "+str(len(porphyrinList))+" "+str(len(sebumList))+" "+str(100*totalUVPoreArea/inputRoiArea)+" "+str(100*redAverage) print "cp min circularity"+str(detectionParameters.closedPoresMinCircularity)+":"+str(detectionParameters.closedPoresMinSize) # close the thresholded image impthresholded.changes=False impthresholded.close() return uvPoreList, statslist, statsheader
imp_ori = IJ.openImage(path_tif) imp_ori.show() imp_ori.setRoi(373,164,600,300) IJ.run("Crop") IJ.run(imp_ori, "Enhance Contrast", "saturated=0.35") imp_ori.show() ImageConverter.setDoScaling(True) IJ.run(imp_ori, "8-bit", "") imp_ori.setTitle("SEM lines") imp_ori.show() IJ.saveAs(imp_ori, "Jpeg", path_jpg) for i in range(201): imp_jpg = IJ.openImage(path_jpg) IJ.saveAs(imp_jpg, "Jpeg", path_jpg) IJ.run(imp_jpg, "32-bit", "") IJ.run(imp_ori, "32-bit", "") imp_ori.setTitle("TIF") imp_ori.show() imp_jpg.setTitle("200 x JPG") imp_jpg.show() ic = ImageCalculator() imp_sub = ic.run("Subtract create 32-bit", imp_jpg, imp_ori) IJ.run(imp_sub, "Enhance Contrast", "saturated=0.35") IJ.run(imp_sub, "8-bit", "") imp_sub.setTitle("subtracted") imp_sub.show()
redIntensity=(rt3.getColumnAsDoubles(rt3.getColumnIndex("IntDen")))[0]; imp.close() IJ.setAutoThreshold(green_coloc, "Default dark"); IJ.run(green_coloc, "Options...", "BlackBackground=true"); IJ.setThreshold(green_coloc,summary["Green" + "-threshold-used"], 255); IJ.run(green_coloc, "Convert to Mask", ""); pa_green.analyze(green_coloc) # green_coloc.show() rt4 = ResultsTable() ta_coloc2=Analyzer(green_coloc,Measurements.INTEGRATED_DENSITY ,rt4); ta_coloc2.measure(); greenIntensity=(rt4.getColumnAsDoubles(rt4.getColumnIndex("IntDen")))[0]; ic_coloc =ImageCalculator(); coloc_img=ic_coloc.run("Multiply create",red_coloc,green_coloc); rt5 = ResultsTable() ta_coloc3=Analyzer(coloc_img,Measurements.INTEGRATED_DENSITY ,rt5); ta_coloc3.measure(); totalIntensity=(rt5.getColumnAsDoubles(rt5.getColumnIndex("IntDen")))[0]; rgb=RGBStackMerge(); composite=rgb.mergeChannels([red_coloc,green_coloc],False); composite.show(); fs=FileSaver(composite); fs.saveAsJpeg(outputDirectory + '/' + "coloc_"+filename); composite.close(); if redIntensity == 0: summary["Red-Green-Coloc-%"]= "NaN" else: summary["Red-Green-Coloc-%"]= float (totalIntensity*100/redIntensity)
def process(dirIn, dirOut, expName, ps, pe, ts, te): jobid = commands.getoutput("echo $PBS_JOBID").split('.')[0] jobid = jobid.replace("[","_").replace("]","") # because the jobids look like 2356385[1] which causes problems print "job id: "+jobid jobdir = os.path.join("/tmp",str(jobid)+"_fiji") print "job dir: "+jobdir for p in range(ps,pe+1): pID = str(p); for t in range(ts,te+1): print "TIMEPOINT STARTING ***************" tID = "t"+str(t); print "time-point: "+tID; if os.path.isdir(jobdir): print "removing "+jobdir shutil.rmtree(jobdir) print "creating "+jobdir os.mkdir(jobdir) if stitching: fileOut = "rescaled_flipped_"; for z in range(zs,ze+1): zID = "z"+str(z); print "z-plane: "+zID; if bandpass: IJ.log("bandpass....") # load all images from same time point and same z-position fileID = expName+pID+"_b0"+tID+zID+"m.*"; IJ.log("opening images: "+os.path.join(dirIn,fileID)) IJ.run("Image Sequence...", "open=["+dirIn+"] starting=1 increment=1 scale=100 file=[] or=["+fileID+"] sort"); #selectWindow("im-2012-0007_Position35.tif_Files"); imp = IJ.getImage(); #imp.show(); imp.setTitle("Stack"); # illumination correction IJ.log("computing FFT..."); # run("Flip Horizontally", "stack"); impFFT = Duplicator().run(imp); for i in range(1, impFFT.getNSlices()+1): print "FFT of slice "+str(i) impFFT.setSlice(i) IJ.run(impFFT, "Bandpass Filter...", "filter_large=10000 filter_small=200 suppress=None tolerance=5 "); #impFFT.show() #stats = imp.getStatistics(Measurements.MEAN) #IJ.log("stats.mean = "+str(stats.mean)); # this is only the mean of one slice...is this a problem? print "dividing image stack by FFT stack..."; ic = ImageCalculator() impCorr = ic.run("Divide create 32-bit stack", imp, impFFT); #impCorr.show() def computeMean(pixels): return sum(pixels) / float(len(pixels)) print "multiplying each image by 128/mean for going back to 8 bit space..." stack = impCorr.getStack() for i in range(1, impCorr.getNSlices()+1): ip = stack.getProcessor(i).convertToFloat() mean = computeMean(ip.getPixels()) print "multiplying slice "+str(i)+" by "+str(float(128/mean)) ip.multiply(float(128/mean)) IJ.log("converting from 32-bit to 8-bit...") IJ.setMinAndMax(impCorr, 0, 255); IJ.run(impCorr,"8-bit",""); #IJ.saveAs(impCorr, "Tiff", "/Users/tischi/Documents/processed.tif"); #ff #impCorr.show() # save images IJ.log("saving bandpass corrected image sequence: "+os.path.join(jobdir,fileOut)) IJ.run(impCorr, "Image Sequence... ", "format=TIFF name=["+fileOut+"] start=1 digits=4 save=["+jobdir+"]"); if check: IJ.run(impCorr, "Image Sequence... ", "format=TIFF name=["+fileOut+"] start=1 digits=4 save=["+dirOut+"]"); #impCorr.close(); imp.close(); impFFT.hide(); # stitching IJ.log("STITCHING START **********") layoutFile = copyStitchingLayoutFile(dirIn,expName,jobdir,ps) ###layoutFile = makeStitchingLayoutFile(jobdir) createPreview = 0 computeOverlap = 0 fusion_method="Linear Blending" handleRGB = "Red, Green and Blue" showImage = 0 #fusion=1 regression=0.30 max/avg=2.50 absolute=3.50" st = Stitch_Image_Collection() st.alpha = 1 IJ.log("layout file: "+str(layoutFile)) impStitched = st.work(layoutFile, createPreview, computeOverlap, fusion_method, handleRGB, showImage) stitchedFile = os.path.join(jobdir,tID+zID+"_stitched.tif"); #impStitched.show() IJ.saveAs(impStitched,"Tiff", stitchedFile); if check: print os.path.join(dirOut,tID+zID+"_stitched.tif") stitchedFile = os.path.join(dirOut,tID+zID+"_stitched.tif"); IJ.saveAs(impStitched,"Tiff", stitchedFile); IJ.log("STITCHING END **********") if combine_z: IJ.log("combine z.....") ######### IJ.log("load stitched images into a stack...") for z in range(zs,ze+1): zID = "z"+str(z); stitchedFile = os.path.join(jobdir,tID+zID+"_stitched.tif"); IJ.log("opening "+stitchedFile) imp = IJ.openImage(stitchedFile) if z==zs: stack = ImageStack(imp.width,imp.height) stack.addSlice(imp.getProcessor()) imp = ImagePlus("stack", stack) #imp.show() ######## ######## IJ.log("cropping...") imp.setRoi(xs, ys, xe, ye); IJ.run(imp, "Crop", ""); #imp.show() ######## # the following normalisation should not be necessary, because they are already all 128/mean normalised #IJ.log("-- normalise intensity of all slices...") #stats = imp.getStatistics(Measurements.MEAN) #IJ.log("stats.mean = "+str(stats.mean)); # this is only the mean of one slice...is this a problem? #stack = imp.getStack() #for i in range(1, impFFT.getNSlices()+1): # ip = stack.getProcessor(i).convertToFloat() # ip.multiply(128/stats.mean) # #stack.setSlice(stack.getSliceLabel(i), ip) #run("Set Slice...", "slice="+1); #run("Set Measurements...", " mean redirect=None decimal=9"); #run("Select None"); #setBatchMode(true); #setMinAndMax(0, 255); run("32-bit"); #for(l=0; l<nSlices+1; l++) { ## run("Select All"); # run("Clear Results"); # run("Measure"); # picsum=getResult("Mean",0); # //if(l==0){picsum1=picsum;} # //int_ratio=picsum1/picsum; # int_ratio=128/picsum; # run("Select None"); # IJ.log("ratio ="+int_ratio); # run("Multiply...", "slice value="+int_ratio); # run("Next Slice [>]"); #} #setBatchMode(false); # stop here and try by hand #... #dfgfd #//stack-reg #//IJ.log("register xy...") #//run("StackReg", "transformation=Translation"); #// project into 1 plane .... #// run("Extended Depth of Field (Easy mode)..."); #//run("Z Project...", "start=["+1+"] stop=["+ze+"] projection=[Standard Deviation]"); doEDF = True if doEDF: IJ.log("EDF: start...") parameters = Parameters() parameters.setQualitySettings(1) parameters.setTopologySettings(0) parameters.show3dView = False parameters.showTopology = False edfh = ExtendedDepthOfFieldHeadless(imp, parameters) imp = edfh.processHeadless() IJ.log("EDF: done.") #imp.show() IJ.log("EDF: converting from 32-bit to 8-bit...") IJ.setMinAndMax(imp, 0, 255); IJ.run(imp,"8-bit",""); edfFile = os.path.join(dirOut,expName+pID+"-"+tID+"_EDOF_noTimeNorm.tif"); IJ.log("EDF save: "+edfFile) IJ.saveAs(imp,"Tiff", edfFile); IJ.log("EDF save: done.") #close(); // projection #close(); // stack print "TIMEPOINT FINISHED ***************" if os.path.isdir(jobdir): print "removing "+jobdir shutil.rmtree(jobdir)
def track(): imp = IJ.getImage() nChannels = imp.getNChannels() # Get the number of channels orgtitle = imp.getTitle() IJ.run("Subtract Background...", "rolling=50 sliding stack") IJ.run("Enhance Contrast...", "saturated=0.3") IJ.run("Multiply...", "value=10 stack") IJ.run("Subtract Background...", "rolling=50 sliding stack") IJ.run("Set Scale...", "distance=0") channels = ChannelSplitter.split(imp) imp_GFP = channels[0] imp_RFP = channels[1] IJ.selectWindow(orgtitle) IJ.run("Close") ic = ImageCalculator() imp_merge = ic.run("Add create stack", imp_GFP, imp_RFP) imp_merge.setTitle("add_channels") imp_merge.show() imp_RFP.show() imp_GFP.show() imp5 = ImagePlus() IJ.run(imp5, "Merge Channels...", "c1=[" + imp_merge.title + "] c2=" + imp_GFP.title + ' c3=' + imp_RFP.title + " create") print("c1=[" + imp_merge.title + "] c2=" + imp_GFP.title + ' c3=' + imp_RFP.title + " create") imp5.show() imp5 = IJ.getImage() nChannels = imp5.getNChannels() # Setup settings for TrackMate settings = Settings() settings.setFrom(imp5) # Spot analyzer: we want the multi-C intensity analyzer. settings.addSpotAnalyzerFactory(SpotMultiChannelIntensityAnalyzerFactory()) # Spot detector. settings.detectorFactory = LogDetectorFactory() settings.detectorSettings = settings.detectorFactory.getDefaultSettings() settings.detectorSettings['TARGET_CHANNEL'] = 1 settings.detectorSettings['RADIUS'] = 24.0 settings.detectorSettings['THRESHOLD'] = 0.0 # Spot tracker. # Configure tracker - We don't want to allow merges or splits settings.trackerFactory = SparseLAPTrackerFactory() settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap() # almost good enough settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = False settings.trackerSettings['ALLOW_TRACK_MERGING'] = False settings.trackerSettings['LINKING_MAX_DISTANCE'] = 8.0 settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = 8.0 settings.trackerSettings['MAX_FRAME_GAP'] = 1 # Configure track filters settings.addTrackAnalyzer(TrackDurationAnalyzer()) settings.addTrackAnalyzer(TrackSpotQualityFeatureAnalyzer()) filter1 = FeatureFilter('TRACK_DURATION', 20, True) settings.addTrackFilter(filter1) # Run TrackMate and store data into Model. model = Model() trackmate = TrackMate(model, settings) ok = trackmate.checkInput() if not ok: sys.exit(str(trackmate.getErrorMessage())) ok = trackmate.process() if not ok: sys.exit(str(trackmate.getErrorMessage())) selectionModel = SelectionModel(model) displayer = HyperStackDisplayer(model, selectionModel, imp5) displayer.render() displayer.refresh() IJ.log('TrackMate completed successfully.') IJ.log('Found %d spots in %d tracks.' % (model.getSpots().getNSpots(True) , model.getTrackModel().nTracks(True))) # Print results in the console. headerStr = '%10s %10s %10s %10s %10s %10s' % ('Spot_ID', 'Track_ID', 'Frame', 'X', 'Y', 'Z') rowStr = '%10d %10d %10d %10.1f %10.1f %10.1f' for i in range( nChannels ): headerStr += (' %10s' % ( 'C' + str(i+1) ) ) rowStr += ( ' %10.1f' ) #open a file to save results myfile = open('/home/rickettsia/Desktop/data/Clamydial_Image_Analysis/EMS_BMECBMELVA_20X_01122019/data/'+orgtitle.split('.')[0]+'.csv', 'wb') wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(['Spot_ID', 'Track_ID', 'Frame', 'X', 'Y', 'Z', 'Channel_1', 'Channel_2']) IJ.log('\n') IJ.log(headerStr) tm = model.getTrackModel() trackIDs = tm.trackIDs(True) for trackID in trackIDs: spots = tm.trackSpots(trackID) # Let's sort them by frame. ls = ArrayList(spots) for spot in ls: values = [spot.ID(), trackID, spot.getFeature('FRAME'), \ spot.getFeature('POSITION_X'), spot.getFeature('POSITION_Y'), spot.getFeature('POSITION_Z')] for i in range(nChannels): values.append(spot.getFeature('MEAN_INTENSITY%02d' % (i+1))) IJ.log(rowStr % tuple(values)) l1 = (values[0], values[1], values[2], values[3], values[4], values[5], values[7], values[8]) wr.writerow(l1) myfile.close() IJ.selectWindow("Merged") IJ.run("Close")
rt = ResultsTable() while goRun: wfud = WaitForUserDialog("Pick freehand ROI, then hit OK to analyze") wfud.show() roi = theImage.getRoi() if roi is None: goRun = False else: dataImage.setRoi(roi) subImage = dataImage.duplicate() dataIp = dataImage.getProcessor() dataIp.setRoi(roi) maskIp = dataIp.getMask() maskImage = ImagePlus("Mask Image",maskIp) ic = ImageCalculator() countingImage = ic.run("AND create stack",subImage,maskImage) pixelCount = 0 for i in range(1,countingImage.getNSlices()+1): countingImage.setSlice(i) countingIp = countingImage.getProcessor() for x in range(0,countingImage.getWidth()): for y in range(0,countingImage.getHeight()): if (countingIp.getPixel(x,y) >= intensityThreshold): pixelCount = pixelCount + 1 totAvailablePixels = countingImage.getWidth() * countingImage.getHeight() * countingImage.getNSlices() #IJ.log("Pixel count: " + str(pixelCount) + " of " + str(totAvailablePixels)) countingImage.close() rt.incrementCounter() rt.addValue("PosPixels",pixelCount) rt.addValue("TotPixels",totAvailablePixels) rt.show("DMI Results")
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters): title = inputImp.getTitle() title=title.replace('UV', 'SD') print title #trueColorImp= WindowManager.getImage(title) #print type( trueColorImp) # calculate are of roi stats=inputImp.getStatistics() inputRoiArea=stats.area print inputRoi # get the bounding box of the active roi inputRec = inputRoi.getBounds() x1=long(inputRec.getX()) y1=long(inputRec.getY()) x2=x1+long(inputRec.getWidth())-1 y2=y1+long(inputRec.getHeight())-1 print x1 print y1 print x2 print y2 # crop the roi interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') ) cropped=ops.crop(interval, None, inputDataset.getImgPlus() ) datacropped=data.create(cropped) display.createDisplay("cropped", datacropped) croppedPlus=IJ.getImage() duplicator=Duplicator() substackMaker=SubstackMaker() # duplicate the roi duplicate=duplicator.run(croppedPlus) #duplicate.show() # convert duplicate of roi to HSB and get brightness IJ.run(duplicate, "HSB Stack", ""); brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3") brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus)) brightnessPlus.setTitle("Brightness") #brightnessPlus.show() # make another duplicate, split channels and get red duplicate=duplicator.run(croppedPlus) channels=ChannelSplitter().split(duplicate) redPlus=channels[0] red=ImgPlus(ImageJFunctions.wrapByte(redPlus)) redPlus.show() # convert to lab IJ.run(croppedPlus, "Color Transformer", "colour=Lab") IJ.selectWindow('Lab') labPlus=IJ.getImage() # get the A channel APlus=substackMaker.makeSubstack(labPlus, "2-2") APlus.setTitle('A') APlus.show() APlus.getProcessor().resetMinAndMax() APlus.updateAndDraw() AThresholded=threshold(APlus, -10, 50) # get the B channel BPlus=substackMaker.makeSubstack(labPlus, "3-3") BPlus.setTitle('B') BPlus.show() BPlus.getProcessor().resetMinAndMax() BPlus.updateAndDraw() BThresholded=threshold(BPlus, -10, 50) # AND the Athreshold and Bthreshold to get a map of the red pixels ic = ImageCalculator(); redMask = ic.run("AND create", AThresholded, BThresholded); IJ.run(redMask, "Divide...", "value=255"); #redMask.show() labPlus.close() # threshold the spots from the red channel thresholdedred=SpotDetectionGray(red, data, display, ops, False) display.createDisplay("thresholdedred", data.create(thresholdedred)) impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped") # threshold the spots from the brightness channel thresholded=SpotDetectionGray(brightness, data, display, ops, False) display.createDisplay("thresholded", data.create(thresholded)) impthresholded=ImageJFunctions.wrap(thresholded, "wrapped") # or the thresholding results from red and brightness channel impthresholded = ic.run("OR create", impthresholded, impthresholdedred); # convert to mask Prefs.blackBackground = True IJ.run(impthresholded, "Convert to Mask", "") # clear the region outside the roi clone=inputRoi.clone() clone.setLocation(0,0) Utility.clearOutsideRoi(impthresholded, clone) # create a hidden roi manager roim = RoiManager(True) # count the particlesimp.getProcessor().setColor(Color.green) countParticles(impthresholded, roim, detectionParameters.minSize, detectionParameters.maxSize, detectionParameters.minCircularity, detectionParameters.maxCircularity) # define a function to determine the percentage of pixels that are foreground in a binary image # inputs: # imp: binary image, 0=background, 1=foreground # roi: an roi def isRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.redPercentage): return True else: return False def notRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.redPercentage): return False else: return True allList=[] for roi in roim.getRoisAsArray(): allList.append(roi.clone()) # count particles that are red redList=CountParticles.filterParticlesWithFunction(redMask, allList, isRed) # count particles that are red blueList=CountParticles.filterParticlesWithFunction(redMask, allList, notRed) print "Total particles: "+str(len(allList)) print "Filtered particles: "+str(len(redList)) # for each roi add the offset such that the roi is positioned in the correct location for the # original image [roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in allList] # create an overlay and add the rois overlay1=Overlay() inputRoi.setStrokeColor(Color.green) overlay1.add(inputRoi) [CountParticles.addParticleToOverlay(roi, overlay1, Color.red) for roi in redList] [CountParticles.addParticleToOverlay(roi, overlay1, Color.cyan) for roi in blueList] def drawAllRoisOnImage(imp, mainRoi, redList, blueList): imp.getProcessor().setColor(Color.green) IJ.run(imp, "Line Width...", "line=3"); imp.getProcessor().draw(inputRoi) imp.updateAndDraw() IJ.run(imp, "Line Width...", "line=1"); [CountParticles.drawParticleOnImage(imp, roi, Color.magenta) for roi in redList] [CountParticles.drawParticleOnImage(imp, roi, Color.green) for roi in blueList] imp.updateAndDraw() drawAllRoisOnImage(inputImp, inputRoi, redList, blueList) #drawAllRoisOnImage(trueColorImp, inputRoi, redList, blueList) # draw overlay #inputImp.setOverlay(overlay1) #inputImp.updateAndDraw() statsdict=CountParticles.calculateParticleStats(APlus, BPlus, redMask, roim.getRoisAsArray()) print inputRoiArea areas=statsdict['Areas'] poreArea=0 for area in areas: poreArea=poreArea+area ATotal=0 ALevels=statsdict['ALevel'] for A in ALevels: ATotal=ATotal+A AAverage=ATotal/len(ALevels) BTotal=0 BLevels=statsdict['BLevel'] for B in BLevels: BTotal=BTotal+B BAverage=BTotal/len(BLevels) redTotal=0 redPercentages=statsdict['redPercentage'] for red in redPercentages: redTotal=redTotal+red redAverage=redTotal/len(redPercentages) pixwidth=inputImp.getCalibration().pixelWidth inputRoiArea=inputRoiArea/(pixwidth*pixwidth) print str(len(allList))+" "+str(len(redList))+" "+str(len(blueList))+" "+str(poreArea/inputRoiArea)+" "+str(redAverage)
def getThresholdedMask(currIP, c, z, t, chanName, cfg, wellPath, dbgOutDesc): if (cfg.hasValue(ELMConfig.upperLeftExclusionX)): ulExclusionX = cfg.getValue(ELMConfig.upperLeftExclusionX) else: ulExclusionX = 0 if (cfg.hasValue(ELMConfig.upperLeftExclusionY)): ulExclusionY = cfg.getValue(ELMConfig.upperLeftExclusionY) else: ulExclusionY = 0 if (cfg.hasValue(ELMConfig.lowerRightExclusionX)): lrExclusionX = cfg.getValue(ELMConfig.lowerRightExclusionX) else: lrExclusionX = currIP.getWidth() if (cfg.hasValue(ELMConfig.lowerRightExclusionY)): lrExclusionY = cfg.getValue(ELMConfig.lowerRightExclusionY) else: lrExclusionY = currIP.getHeight() imgType = currIP.getType() if (chanName in cfg.getValue( ELMConfig.chansToSkip)): # Don't process skip channels currIP.close() return None elif imgType == ImagePlus.COLOR_RGB or imgType == ImagePlus.COLOR_256: if (chanName == ELMConfig.BRIGHTFIELD): toGray = ImageConverter(currIP) toGray.convertToGray8() if cfg.params[ELMConfig.imgType] == "png": darkBackground = True else: darkBackground = False elif (chanName == ELMConfig.BLUE) \ or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED) \ or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN): # chanIdx = 2 if (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED): chanIdx = 0 elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN): chanIdx = 1 imgChanns = ChannelSplitter.split(currIP) currIP.close() currIP = imgChanns[chanIdx] # Clear the Exclusion zone, so it doesn't mess with thresholding imgProc = currIP.getProcessor() imgProc.setColor(Color(0, 0, 0)) imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(), currIP.getHeight()) imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY) darkBackground = True elif (chanName == ELMConfig.YELLOW): # Clear the Exclusion zone, so it doesn't mess with thresholding imgProc = currIP.getProcessor() imgProc.setColor(Color(0, 0, 0)) imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(), currIP.getHeight()) imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY) # Create a new image that consists of the average of the red & green channels title = currIP.getTitle() width = currIP.getWidth() height = currIP.getHeight() newPix = ByteProcessor(width, height) for x in range(0, width): for y in range(0, height): currPix = currIP.getPixel(x, y) newPix.putPixel(x, y, (currPix[0] + currPix[1]) / 2) currIP.close() currIP = ImagePlus(title, newPix) darkBackground = True else: print "ERROR: Unrecognized channel name! Name: " + chanName currIP.close() return None elif imgType == ImagePlus.GRAY16 or imgType == ImagePlus.GRAY32 or imgType == ImagePlus.GRAY8: if (chanName == ELMConfig.BRIGHTFIELD): if cfg.params[ELMConfig.imgType] == "png": darkBackground = True else: darkBackground = False else: darkBackground = True if not imgType == ImagePlus.GRAY8: toGray = ImageConverter(currIP) toGray.convertToGray8() else: print "ERROR: Unrecognized channel name & image type! Channel: " + chanName + ", imgType: " + str( imgType) currIP.close() return None WindowManager.setTempCurrentImage(currIP) if cfg.getValue(ELMConfig.debugOutput): IJ.saveAs('png', os.path.join(wellPath, "Processing_" + dbgOutDesc + ".png")) upperThreshImg = currIP.duplicate() # If threshold value is set, use it if (cfg.hasValue(ELMConfig.imageThreshold)): thresh = cfg.getValue(ELMConfig.imageThreshold) if (darkBackground): currIP.getProcessor().setThreshold(thresh, 255, ImageProcessor.NO_LUT_UPDATE) else: currIP.getProcessor().setThreshold(0, thresh, ImageProcessor.NO_LUT_UPDATE) else: # Otherise, automatically compute threshold threshMethod = "Default" if cfg.hasValue(ELMConfig.thresholdMethod): threshMethod = cfg.getValue(ELMConfig.thresholdMethod) currIP.getProcessor().setAutoThreshold(threshMethod, darkBackground, ImageProcessor.NO_LUT_UPDATE) threshRange = currIP.getProcessor().getMaxThreshold( ) - currIP.getProcessor().getMinThreshold() #print "\t\tZ = " + str(z) + ", T = " + str(t) + ", chan " + chanName + ": Using default threshold of minThresh: " + str(currIP.getProcessor().getMinThreshold()) + ", maxThresh: " + str(currIP.getProcessor().getMaxThreshold()) if currIP.getType() != ImagePlus.GRAY8: print "\tChannel " + chanName + " is not GRAY8, instead type is %d" % currIP.getType( ) if threshRange > cfg.getValue(ELMConfig.maxThreshRange): if (cfg.hasValue(ELMConfig.defaultThreshold)): thresh = cfg.getValue(ELMConfig.defaultThreshold) print "\t\tZ = " + str(z) + ", T = " + str( t ) + ", chan " + chanName + ": Using default threshold of " + str( thresh) + ", minThresh: " + str(currIP.getProcessor( ).getMinThreshold()) + ", maxThresh: " + str( currIP.getProcessor().getMaxThreshold()) if (darkBackground): currIP.getProcessor().setThreshold( thresh, 255, ImageProcessor.NO_LUT_UPDATE) else: currIP.getProcessor().setThreshold( 0, thresh, ImageProcessor.NO_LUT_UPDATE) else: print "\t\tZ = " + str(z) + ", T = " + str( t ) + ", chan " + chanName + ": Ignored Objects due to threshold range! minThresh: " + str( currIP.getProcessor().getMinThreshold( )) + ", maxThresh: " + str( currIP.getProcessor().getMaxThreshold()) currIP.close() return None IJ.run(currIP, "Convert to Mask", "") # Clear out exclusion zones imgProc = currIP.getProcessor() imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(), currIP.getHeight()) imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY) IJ.run(currIP, "Close-", "") # Brightfield has an additional thresholding step if cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.BRIGHTFIELD: if cfg.getValue(ELMConfig.debugOutput): IJ.saveAs( 'png', os.path.join(wellPath, "OrigMask_" + dbgOutDesc + ".png")) upperThresh = 255 * 0.95 upperThreshImg.getProcessor().setThreshold( upperThresh, 255, ImageProcessor.NO_LUT_UPDATE) IJ.run(upperThreshImg, "Convert to Mask", "") IJ.run(upperThreshImg, "Close-", "") if cfg.getValue(ELMConfig.debugOutput): WindowManager.setTempCurrentImage(upperThreshImg) IJ.saveAs( 'png', os.path.join(wellPath, "UpperThreshMask_" + dbgOutDesc + ".png")) ic = ImageCalculator() compositeMask = ic.run("OR create", currIP, upperThreshImg) IJ.run(compositeMask, "Close-", "") currIP.close() currIP = compositeMask WindowManager.setTempCurrentImage(currIP) if cfg.getValue(ELMConfig.debugOutput): WindowManager.setTempCurrentImage(currIP) IJ.saveAs('png', os.path.join(wellPath, "Binary_" + dbgOutDesc + ".png")) upperThreshImg.close() return currIP
# use the same renaming trick as for the macro recorder imp.setTitle("current") # IJ.run executes commands from the macro recorder IJ.run( "Scale...", "x=.5 y=.5 z=1.0 width=128 height=128 depth=930 interpolation=Bilinear average process create" ) imp.close() IJ.selectWindow("current-1") IJ.run("Z Project...", "projection=[Average Intensity]") # Note the new imports above, WindowManager and ImageCalculator # ic.run executes commands within image calculator; wm.getImage selects the image using WindowsManager imp = ic.run("Subtract create 32-bit stack", wm.getImage("current-1"), wm.getImage("AVG_current-1")) imp.show() imp = ic.run("Divide create 32-bit stack", wm.getImage("Result of current-1"), wm.getImage("AVG_current-1")) imp.show() IJ.selectWindow("Result of Result of current-1") # adjust the Brightness/Contrast IJ.setMinAndMax(-0.0200, 0.2000) # this is the Lookup Tables step IJ.run("Aselfmade3") # IJ.saveAs has 3 arguments: (image, file type, file path) IJ.saveAs(IJ.getImage(), "Tiff", out_folder + the_file + '-processed') IJ.run("Close All", "")
IJ.run(nextStepImage,"Refractive Signal Loss Correction",params) mergingImages = [WindowManager.getImage("App Corrected"),WindowManager.getImage("Ref Corrected")] next2StepImage = RGBStackMerge.mergeChannels(mergingImages,True) for img in mergingImages: img.close() #next2StepImage.show() nextStepImage.close() else: next2StepImage = nextStepImage nextStepImage.close() ## Makes the amplified composite image ic = ImageCalculator() indChannels = ChannelSplitter.split(next2StepImage) sourceDataImage = indChannels[0].duplicate() for sl in range(1,sourceDataImage.getNSlices()+1): sourceDataImage.setSliceWithoutUpdate(sl) ip = sourceDataImage.getProcessor() ip.multiply(ampFactor) ratedRefImage = ic.run("Subtract create stack",indChannels[1],sourceDataImage) mergingImages = [indChannels[0],ratedRefImage] outputImage = RGBStackMerge.mergeChannels(mergingImages,True) for img in mergingImages: img.close() for img in indChannels: img.close() next2StepImage.close() sourceDataImage.close() outputImage.show()