def generate_cell_masks(watershed_seeds_imp, intensity_channel_imp, find_edges=False): """perform marker-driven watershed on image in intensity_channel_imp""" intensity_channel_title = intensity_channel_imp.getTitle() watershed_seed_title = watershed_seeds_imp.getTitle() title = os.path.splitext(intensity_channel_title)[0] intensity_channel_imp.show() watershed_seeds_imp.show() if find_edges: IJ.run(intensity_channel_imp, "Find Edges", "") IJ.run( intensity_channel_imp, "Marker-controlled Watershed", "input={} marker={} mask=None binary calculate use".format( intensity_channel_title, watershed_seed_title)) ws_title = "{}-watershed.tif".format(title) watershed_imp = WM.getImage(ws_title) if watershed_imp is None: if ws_title[-3:] == 'tif': ws_title = os.path.splitext(ws_title)[0] else: ws_title = ws_title + '.tif' watershed_imp = WM.getImage(ws_title) IJ.setRawThreshold(watershed_imp, 1, watershed_imp.getProcessor().maxValue() + 1, "Red") binary_cells_imp = ImagePlus("thresholded", watershed_imp.createThresholdMask()) IJ.run(binary_cells_imp, "Kill Borders", "") kb_thresh_title = binary_cells_imp.getTitle() binary_cells_imp.close() binary_cells_imp = WM.getImage("{}-killBorders".format(kb_thresh_title)) watershed_imp.close() intensity_channel_imp.changes = False intensity_channel_imp.close() return binary_cells_imp
def generate_cell_masks(watershed_seeds_imp, intensity_channel_imp): """perform marker-driven watershed on image in intensity_channel_imp""" IJ.run( imp, "Marker-controlled Watershed", "input={} marker=Nuclei mask=None binary calculate use".format( os.path.splitext(intensity_channel_imp.getTitle())[0])) ws_title = "{}-watershed".format(intensity_channel_imp.getTitle()) watershed_imp = WM.getImage(ws_title) IJ.setRawThreshold(watershed_imp, 1, watershed_imp.getProcessor().maxValue(), "Red") binary_cells_imp = ImagePlus("thresholded", watershed_imp.createThresholdMask()) IJ.run(binary_cells_imp, "Kill Borders", "") kb_thresh_title = binary_cells_imp.getTitle() binary_cells_imp.close() binary_cells_imp = WM.getImage("{}-killBorders".format(kb_thresh_title)) watershed_imp.close() return binary_cells_imp
def findCells(imp, rm, channel, noisetol, thresh): ''' Function for finding cells as local maxima and creating an ROI showing them imp: ImagePlus rm: the current ROI manager channel, int: the channel being processed (used for ROI name) noisetol, thresh, ints: noise tolerance and pixel value threshold for findMaxima returns the count ''' # set the channel imp.setC(channel) # find maxima ip = imp.getProcessor() mf = MaximumFinder() maxima = mf.findMaxima(ip, noisetol, thresh, MaximumFinder.SINGLE_POINTS, False, False) findmaximashow = ImagePlus("Found Maxima", maxima) findmaximashow.show() # an image of all the points maximaip = findmaximashow.getProcessor() maximahist = maximaip.getHistogram() cellCount = maximahist[255] if cellCount != 0: IJ.setRawThreshold(findmaximashow, 255, 255, "red") IJ.run(findmaximashow, "Create Selection", "") rm.addRoi(findmaximashow.getRoi() ) # a selection consisting of all the points # close maxima image if present if findmaximashow: findmaximashow.close() return cellCount
# - commands generally do not work on the active image but need a imp (ImagePlus) object to operate on. from ij import IJ from ij import Prefs # Get input from user #@File image (label="input image") #@File (style="directory", label="output directory") outputDirectory # Open image IJ.run("Close All") imp = IJ.openImage(str(image)) title = imp.getTitle() # Binarize (Threshold) IJ.setRawThreshold(imp, 24, 255, None) Prefs.blackBackground = True IJ.run(imp, "Convert to Mask", "") # Connected components IJ.run(imp, "Connected Components Labeling", "connectivity=4 type=[16 bits]") # Measure shape IJ.run("Region Morphometry") # Export results IJ.saveAs("Results", str(outputDirectory) + "/" + title + ".csv") # Clean up IJ.run("Close All")
# - commands generally do not work on the active image but need a imp (ImagePlus) object to operate on. from ij import IJ; from ij import Prefs; # Get input from user #@File image (label="input image") #@File (style="directory", label="output directory") outputDirectory # Open image IJ.run("Close All"); imp = IJ.openImage( str(image) ); title = imp.getTitle(); # Binarize (Threshold) IJ.setRawThreshold(imp, 24, 255, None); Prefs.blackBackground = True; IJ.run(imp, "Convert to Mask", ""); # Connected components IJ.run(imp, "Connected Components Labeling", "connectivity=4 type=[16 bits]"); # Measure shape IJ.run("Region Morphometry"); # Export results IJ.saveAs("Results", str(outputDirectory) + "/" + title + ".csv"); # Clean up IJ.run("Close All");
from ij import IJ, ImagePlus from ij.plugin import Thresholder inputImage = IJ.openImage( "https://github.com/NEUBIAS/training-resources/raw/master/image_data/xy_8bit__two_cells.tif" ) IJ.setRawThreshold(inputImage, 44, 255, None) binaryImage = ImagePlus('Binary image 2 nuclei', Thresholder.createMask(inputImage)) binaryImage.show() IJ.setRawThreshold(inputImage, 88, 255, None) binaryImage_1 = ImagePlus('Binary image 1 nuclei', Thresholder.createMask(inputImage)) binaryImage_1.show()
close_open_non_image_window("Results") close_open_non_image_window("ROI Manager") IJ.run("Close All") imp = IJ.openImage(img_dir + "/nalco-img-04cr.tif") ti = imp.getShortTitle() imp.setTitle(ti) imp.show() imp_work = imp.duplicate() imp_work.setTitle("Processed") imp_work.show() IJ.run(imp_work, "Median...", "radius=" + mf_px) IJ.setAutoThreshold(imp_work, "Default dark") IJ.setAutoThreshold(imp_work, "Huang") IJ.setRawThreshold(imp_work, 0, 813, None) imp_work.show() IJ.run("Make Binary") IJ.run(imp_work, "Fill Holes", "") imp_work = run_closing(imp_work) # imp_work = run_closing(imp_work) imp_work = run_closing(imp_work) IJ.run(imp_work, "Dilate", "") IJ.run("Make Binary") IJ.run("Fill Holes", "") imp_work.show() IJ.run("Watershed", "") IJ.run("Set Measurements...", "area perimeter fit shape display add redirect=None decimal=3") ana_str_2 = "size=" + min_px + "-Infinity pixel circularity=" + min_circ + "-1.00 display exclude clear add" IJ.run("Analyze Particles...", ana_str_2)
from ij.gui import ShapeRoi from ij.plugin.frame import RoiManager from org.jfree.graphics2d.svg import SVGGraphics2D, SVGUtils import jmFijiGen as jmg # Start clean... IJ.run("Close All") jmg.close_open_non_image_window("Results") jmg.close_open_non_image_window("ROI Manager") imp = IJ.openImage("http://imagej.nih.gov/ij/images/blobs.gif") imp.show() IJ.setAutoThreshold(imp, "Default") imp.show() IJ.setRawThreshold(imp, 126, 255, None) # The recorder never records this... IJ.run("Make Binary") IJ.run("Convert to Mask") IJ.run("Set Measurements...", "area perimeter shape display add redirect=None decimal=3") IJ.run(imp, "Analyze Particles...", "size=20-Infinity circularity=0.2-1.00 show=Overlay display exclude clear add"); rm = RoiManager.getInstance() if rm is None: print 'None' sys.exit() # convert ROIs in RoiManager to an array of shapeRois jrois = rm.getRoisAsArray() srois = [ShapeRoi(jroi) for jroi in jrois] # http://www.jfree.org/jfreesvg/javadoc/ g2 = SVGGraphics2D(imp.getWidth(), imp.getHeight())
# to resliced image) imp.killRoi(); IJ.run(imp, "Reslice [/]...", "output=1.000 start=Top avoid"); rot_imp = IJ.getImage(); crop_roi = Roi(10, 0, rot_imp.getWidth()-20, rot_imp.getHeight()); rot_imp.setRoi(crop_roi); rot_imp.crop(); rot_imp.show(); WaitForUserDialog("pause").show(); split_ch = ChannelSplitter().split(rot_imp); mch_imp = split_ch[0]; egfp_imp = split_ch[1]; roi_imp = split_ch[2]; zproj_imp = ZProjector.run(roi_imp, "max"); IJ.setRawThreshold(zproj_imp, 33153, 65535, None); IJ.run(zproj_imp, "Make Binary", "") zproj_imp.show(); raise error; IJ.run(zproj_imp, "Skeletonize", ""); IJ.run(zproj_imp, "Create Selection", ""); roi = zproj_imp.getRoi(); floatpoly = roi.getContainedFloatPoints(); roi = PolygonRoi(floatpoly, Roi.FREELINE); zproj_imp.setRoi(roi); WaitForUserDialog("pause").show(); #IJ.setTool("freeline"); #WaitForUserDialog("Draw a line").show(); #IJ.run(zproj_imp, "Fit Spline", ""); #roi = zproj_imp.getRoi();
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()
1) # default is 1 decimal gd.showDialog() Pixel_size = gd.getNextNumber( ) #6.4 # ENTER mm, remember tolerance is +/-30% return Pixel_size ######### open image using dialogue box #imp = IJ.getImage() original = IJ.openImage(getFile()) original.show() ########## Use thresholding and selection to define UFOV ################################################################################### #IJ.run("ROI Manager...", "") # not sure if I need this IJ.setRawThreshold( original, 1, 255, '') # background pixels have value 0. See IMAGE>ADJUST>THRESHOLD IJ.run(original, "Create Selection", "") # add bounding box. See EDIT>SELECTION IJ.run(original, "To Bounding Box", "") # this box defines the UFOV. See EDIT>SELECTION IJ.resetThreshold( original) # get back original now UFOV is definedthresholding UFOV = Duplicator().run( original) # duplicate the original image, only the CFOV UFOV.setTitle("UFOV") UFOV.show() CFOV_fraction = 0.75 # choose the fraction of the UFOV that defines the CFOV IJ.run(original, "Scale... ", "x=" + str(CFOV_fraction) + " y=" +
Date Who What ---------- --- ------------------------------------------- 2019-07-17 JRM Prototype. Not sure it makes sense... """ IJ.run("Close All") imp = IJ.openImage( "/Users/jrminter/Downloads/Fiji Manual Resources/Demo Images/Widefield Images/Segmentation/Nuclei.tif" ) imp.show() IJ.setAutoThreshold(imp, "Default") IJ.run("Make Binary") IJ.run("Convert to Mask") IJ.run(imp, "Watershed", "") IJ.run(imp, "Options...", "iterations=1 count=1 black edm=16-bit do=Nothing") IJ.run(imp, "Invert", "") IJ.run(imp, "Distance Map", "") edm = WindowManager.getImage("EDM of Nuclei") edm.show() # IJ.run(edm, "8-bit", "") IJ.run(edm, "16_colors", "") IJ.run(edm, "Apply LUT", "") edm.updateAndRepaintWindow() IJ.setAutoThreshold(edm, "Default light") IJ.setRawThreshold(edm, 1, 65535, None) edm.show() IJ.run(edm, "Measure", "")
# POINT_SELECTION is supposed to give just that but can't figure out how to get it in the manager # https://stackoverflow.com/questions/26526269/image-analysis-finding-proteins-in-an-image # https://github.com/bgruening/galaxytools/blob/18b441b263846cece9c5527cab0de66a54ecba3a/tools/image_processing/imagej2/imagej2_find_maxima/jython_script.py maxima = mf.findMaxima(ip, 100.0, THRESH, MaximumFinder.SINGLE_POINTS, False, False) findmaximashow = ImagePlus("Found Maxima", maxima) findmaximashow.show() # an image of all the points maximaip = findmaximashow.getProcessor() maximahist = maximaip.getHistogram() CountMethod2 = maximahist[255] print "Using the findMaxima method with a threshold of " + str( THRESH) + ", I found " + str(CountMethod2) + " maxima." IJ.setRawThreshold(findmaximashow, 255, 255, "red") IJ.run(findmaximashow, "Create Selection", "") rm.addRoi(findmaximashow.getRoi()) rm.rename(1, "Maxima with threshold") # ---- METHOD 3-4: API getMaxima WITH THE POINTS COUNTED OR ADDED TO THE RESULTS TABLE maxima = mf.getMaxima(ip, 100.0, False) CountMethod3 = maxima.npoints print "Using the getMaxima method with no threshold , I found " + str( CountMethod3) + " maxima." rt = ResultsTable() for i in range(maxima.npoints): rt.incrementCounter() rt.addValue("X", maxima.xpoints[i])
leaf_csv_path = git_home + "/tips/ImageJ/png/maple-leaf.csv" print(leaf_path) imp_leaf = IJ.openImage(leaf_path) imp_leaf.show() channels = ChannelSplitter.split(imp_leaf) # red channels[0].show() # green channels[1].show() # blue channels[2].show() # work imp_bin = channels[2].duplicate() imp_bin.setTitle("binary") IJ.setAutoThreshold(imp_bin, "Huang") IJ.setRawThreshold(imp_bin, 0, 233, None) IJ.run(imp_bin, "Set Measurements...", "area mean perimeter shape display add redirect=None decimal=3") IJ.run(imp_bin, "Analyze Particles...", "display clear add") imp_bin.show() roi_num = 0 add_roi_and_update(channels[0], rm, roi_num) add_roi_and_update(channels[1], rm, roi_num) add_roi_and_update(channels[2], rm, roi_num) add_roi_and_update(imp_leaf, rm, roi_num) imp_leaf.show() rt = Analyzer.getResultsTable() rt.reset()
def getPixel(): # Get pixel size from user with dialog box. could return python dict or make custom class? Note user can return a NaN if doesnt enter numeric gd = GenericDialog("Pixel") gd.addNumericField("Pixel size desired (mm)", 6.4, 1) # default is 1 decimal gd.showDialog() Pixel_size = gd.getNextNumber() #6.4 # ENTER mm, remember tolerance is +/-30% return Pixel_size ######### open image using dialogue box #imp = IJ.getImage() original = IJ.openImage(getFile()) original.show() ########## Use thresholding and selection to define UFOV ################################################################################### #IJ.run("ROI Manager...", "") # not sure if I need this IJ.setRawThreshold(original, 1, 255,'') # background pixels have value 0. See IMAGE>ADJUST>THRESHOLD IJ.run(original, "Create Selection", "") # add bounding box. See EDIT>SELECTION IJ.run(original,"To Bounding Box", "") # this box defines the UFOV. See EDIT>SELECTION IJ.resetThreshold(original) # get back original now UFOV is definedthresholding UFOV = Duplicator().run(original) # duplicate the original image, only the CFOV UFOV.setTitle("UFOV") UFOV.show() CFOV_fraction = 0.75 # choose the fraction of the UFOV that defines the CFOV IJ.run(original,"Scale... ", "x="+str(CFOV_fraction)+" y="+str(CFOV_fraction)+" centered") # rescale bounding box to get CFOV CFOV = Duplicator().run(original) # duplicate the original image, only the CFOV CFOV.setTitle("CFOV") CFOV.show()