def make_mask_file(p, imp): x_min = p['mask_roi'][0] y_min = p['mask_roi'][1] z_min = p['mask_roi'][2] x_width = p['mask_roi'][3] y_width = p['mask_roi'][4] z_width = p['mask_roi'][5] imp_mask = imp.duplicate() IJ.setBackgroundColor(0, 0, 0); IJ.run(imp_mask, "Select All", ""); IJ.run(imp_mask, "Clear", "stack"); IJ.run(imp_mask, "Select None", ""); #IJ.run(imp_mask, "8-bit", ""); for iSlice in range(z_min, z_min+z_width): imp_mask.setSlice(iSlice) ip = imp_mask.getProcessor() ip.setColor(1) ip.setRoi(x_min, y_min, x_width, y_width) ip.fill() mask_filepath = os.path.join(p['output_folder'],'mask.tif') IJ.saveAs(imp_mask, 'TIFF', mask_filepath) return mask_filepath
def run(): global srcFile, ext, numberOfWidthMeasurements IJ.run("Set Measurements...", "area mean standard modal min centroid center perimeter bounding fit shape feret's integrated median skewness kurtosis area_fraction display redirect=None decimal=3"); IJ.setForegroundColor(255,255,255); IJ.setBackgroundColor(0,0,0); IJ.run("Options...", "iterations=1 count=1 black"); table = ResultsTable() srcDir = srcFile.getAbsolutePath() for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Check for file extension if not filename.endswith(ext): continue # Check for file name pattern process(srcDir, root, filename, table, numberOfWidthMeasurements) table.save(os.path.join(srcDir, 'Results.xls'))
if not cellOverlap(xcenter, ycenter, celldiam, centers): centers.append([xcenter, ycenter]) # print("Spot "+str(count)+" center: "+str(centers[count])) count += 1 # work on a copy of the image from ij.plugin import Duplicator imp2 = Duplicator().run(imp, 1, channels, 1, 1, 1, 1) # clear the existing channel imp2.setDisplayMode(IJ.COLOR) imp2.setC(targetChannel) IJ.run(imp2, "Select All", "") IJ.setBackgroundColor(0, 0, 0) IJ.run(imp2, "Clear", "slice") # draw white circles to simulate cells IJ.setForegroundColor(255, 255, 255) for point in centers: drawSpot(point, celldiam) # save the simulated image IJ.saveAs(imp2, "Tiff", os.path.join(srcDir, basename + " sim " + str(trial) + ".tif")) imp2.close() # print("Finished simulations.") # close the original
anno_width, anno_height, t_a + t_b + t_c) # Add leading texts labelTextAll(start=0, interval=1, x=10, y=40, fontsize=36, text='[Flow:L--->R]') # Add timestamps for each segment x_ts, y_ts, fs_ts = 325, 30, 36 # x, y, and font_size labelTimestamps(start=0, interval=sample_rate, x=x_ts, y=y_ts, fontsize=fs_ts, range0=1, range1=t_a) labelTimestamps(start=int(t0_b - t0_a), interval=sample_rate, x=x_ts, y=y_ts, fontsize=fs_ts, range0=(t_a + 1), range1=(t_a + t_b)) labelTimestamps(start=int(t0_c - t0_a), interval=sample_rate, x=x_ts, y=y_ts, fontsize=fs_ts, range0=(t_a + t_b + 1), range1=(t_a + t_b + t_c)) # Add scale bar labelTextAll(start=0, interval=1, x=700, y=20, fontsize=36, text=(str(sbar_um) + um)) IJ.setBackgroundColor(255, 255, 255) for i in range(1, t_a + t_b + t_c + 1): IJ.setSlice(i) IJ.makeRectangle(anno_width - 120 - sbar_px, 14, sbar_px, 16) IJ.run('Cut') # Save annotation banner path = SaveDialog(title, title, '.tif').getDirectory() IJ.run('Save', 'save=[' + path + title + ']')
def process_image(imps, rois, ais_chno, nucleus_chno, bg_roino=3, sample_width=3, method='mean', dilations=3, average=1, threshold=0.1): """Opens a file and applies a Gaussian filter.""" orig_title = imps[ais_chno-1].getTitle() print ",".join([i.getTitle() for i in imps]) print "Processing", orig_title options = IS.MEAN | IS.MEDIAN # many others nucleus_imp = imps[nucleus_chno-1].duplicate() IJ.run(nucleus_imp, "Median...", "radius=10") IJ.setAutoThreshold(nucleus_imp, "Default"); IJ.run(nucleus_imp, "Make Binary", "") IJ.run(nucleus_imp, "Invert", "") IJ.run(nucleus_imp, "Options...", "iterations=1 count=1 black do=Nothing"); IJ.run(nucleus_imp, "Watershed", ""); IJ.run(nucleus_imp, "Analyze Particles...", "size=20-Infinity clear add"); rm = RoiManager.getInstance2() nuclei = rm.getRoisAsArray() ais_imp = imps[ais_chno-1].duplicate() print ais_imp.getTitle() IJ.run(ais_imp, "8-bit","") IJ.run(ais_imp, "Median...", "radius=1") bg = 0 for i in range(bg_roino): bg_roi = rois[i] ais_imp.setRoi(bg_roi) stats = ais_imp.getStatistics(options) bg += stats.mean print "Bg Roi %s, %s: %s" % (bg_roi.getName(), bg_roi, stats) background = (int)(bg / bg_roino) results = [] for i in range(bg_roino, len(rois)): roiresult = {} print i, rois[i].getName() mimp = ais_imp.duplicate() mimp.setTitle("%s-%s-AIS-Skeleton" % (orig_title, rois[i].getName())) # IJ.run(mimp, "Median...", "radius=3") mimp.setRoi(rois[i]) # IJ.setAutoThreshold(mimp, "Huang dark") IJ.run(mimp, "Auto Local Threshold", "method=Phansalkar radius=15 parameter_1=0 parameter_2=0 white") IJ.setBackgroundColor(0,0,0) IJ.run(mimp, "Clear Outside", "") Prefs.blackBackground = True for j in range(dilations): IJ.run(mimp, "Dilate", "") IJ.run(mimp, "Skeletonize", "") #IJ.run(mimp, "Analyze Skeleton (2D/3D)", "prune=none prune_0 calculate show display"); ais_skeleton, ais_points, points, orthogonals, ais_roi, nucleus_roi = create_skeleton(mimp, '%s-%s-AIS' % (orig_title, rois[i].getName()), nuclei_rois=nuclei, sample_width=sample_width) if ais_skeleton is None: print "Skipping -- AIS skeleton segmentation failed for ROI", rois[i].getName() continue #images['ais-skeleton-' + rois[i].getName()] = ais_skeleton # subtract background print "Subtracting background: bg=%d" % background IJ.run(ais_imp, "Subtract...", "value=%d" % int(background)) ais_imp.setRoi(ais_roi) ip = Straightener().straightenLine(ais_imp, sample_width) straight_imp = ImagePlus('%s-%s-AIS-Straight' % (orig_title, rois[i].getName()), ip) straight_imp.setCalibration(imps[ais_chno-1].getCalibration().copy()) IJ.run(straight_imp, "Green Fire Blue", "") roiresult = { 'roi-name': rois[i].getName(), 'ais-image': straight_imp, 'ais-roi': ais_roi, 'nucleus-roi': nucleus_roi, } # plot if len(points) > 1: if method == 'sum': threshold *= sample_width plot, rt = create_plot(straight_imp, method, average, threshold=threshold) roiresult['plot'] = plot roiresult['table'] = rt results.append(roiresult) return results, background
def setBackgroundColor(r, g, b): IJ.setBackgroundColor(r, g, b)
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 NND(imp, mapC, compareC): cal = imp.getCalibration() title = imp.getTitle() impZ = imp.getNSlices() dup = Duplicator() compare = dup.run(imp, compareC, compareC, 1, impZ, 1, 1) compare = reslice(compare, cal.pixelWidth) IJ.run(compare, "Gaussian Blur 3D...", "x=3 y=3 z=3") Z = compare.getNSlices() IJ.setAutoThreshold(compare, THRESHOLD + " dark stack") Prefs.blackBackground = True IJ.run(compare, "Convert to Mask", "method=" + THRESHOLD + " background=Dark black") IJ.run(compare, "Exact Signed Euclidean Distance Transform (3D)", "") edtcompare = WindowManager.getImage("EDT") edtcompare.getWindow().setVisible(False) mapp = dup.run(imp, mapC, mapC, 1, impZ, 1, 1) mapp = reslice(mapp, cal.pixelWidth) IJ.run(mapp, "Gaussian Blur 3D...", "x=3 y=3 z=3") IJ.setAutoThreshold(mapp, THRESHOLD + " dark stack") Prefs.blackBackground = True IJ.run(mapp, "Convert to Mask", "method=" + THRESHOLD + " background=Dark black") dists = [] rt = ResultsTable() ol = Overlay() row = 0 for z in range(Z): mapp.setPosition(z + 1) IJ.run(mapp, "Create Selection", "") if mapp.getStatistics().mean == 0: IJ.run(mapp, "Make Inverse", "") roi = mapp.getRoi() if roi is None: continue edtcompare.setPosition(z + 1) edtcompare.setRoi(roi) IJ.setBackgroundColor(0, 0, 0) IJ.run(edtcompare, "Clear Outside", "slice") ip = edtcompare.getProcessor() roiList = ShapeRoi(roi).getRois() #split roi to limit bounds for sr in roiList: bounds = sr.getBounds() for y in range(0, bounds.height): for x in range(0, bounds.width): if sr.contains(bounds.x + x, bounds.y + y): d = ip.getf(bounds.x + x, bounds.y + y) * cal.pixelWidth * 1000 rt.setValue("C" + str(mapC) + " X", row, (bounds.x + x) * cal.pixelWidth) rt.setValue("C" + str(mapC) + " Y", row, (bounds.y + y) * cal.pixelHeight) rt.setValue("C" + str(mapC) + " Z", row, z * cal.pixelDepth) rt.setValue("Distance to C" + str(compareC) + " (nm)", row, d) row += 1 histD = d if histD >= 0: #set all overlapping voxel distances to 0 histD = 0 dists.append( -histD) #invert to positive for outside distance posZ = int(((z + 1) / float(Z)) * impZ) + 1 roi.setPosition(0, posZ, 1) roi.setStrokeColor(Colour.MAGENTA) ol.add(roi) compare.setPosition(z + 1) IJ.run(compare, "Create Selection", "") if compare.getStatistics().mean == 0: IJ.run(compare, "Make Inverse", "") compareRoi = compare.getRoi() if compareRoi is not None: compareRoi.setPosition(0, posZ, 1) compareRoi.setStrokeColor(Colour.CYAN) ol.add(compareRoi) edtcompare.killRoi() histogram(title + " C" + str(mapC) + "-C" + str(compareC) + " Distance", dists) rt.show(title + " C" + str(mapC) + "-C" + str(compareC) + " Distance") imp.setOverlay(ol) compare.close() edtcompare.changes = False edtcompare.close() mapp.close()
def clearOutsideRoi(imp, roi): imp.setRoi(roi) IJ.setBackgroundColor(0, 0, 0); IJ.run(imp, "Clear Outside", "");
else: bck_int.append(low()) # background mean_int.append(selection_mean()) maximum_int.append(high(bit_depth)) IJ.run("Select None") to_transport_channel() if always_select is True: to_golgi_channel() IJ.setTool("polygon") region = 'Select Golgi' selection(region) to_transport_channel() average_max = high(bit_depth) IJ.setForegroundColor(255, 255, 255) IJ.setBackgroundColor(1, 1, 1) imp2 = IJ.getImage() IJ.run(imp2, "Draw", "slice") IJ.run("Select None") if always_auto is True: to_transport_channel() average_max = high(bit_depth) if always_auto is False: if always_select is False: nbgd = NonBlockingGenericDialog("Golgi_selection") Methods = ['Automatic Selection', 'Manual Selection'] nbgd.addRadioButtonGroup("Methods", Methods, 2, 1, Methods[0]) nbgd.hideCancelButton() nbgd.showDialog()
def clearOutsideRoi(imp, roi): imp.setRoi(roi) IJ.setBackgroundColor(0, 0, 0) IJ.run(imp, "Clear Outside", "")
import re # Sometimes JAVA/ImageJ has a problem with file names. Changing default coding should help. reload(sys) sys.setdefaultencoding('UTF8') #Bring up roimanager rm = RoiManager().getInstance() #Set some defaults IJ.run( "Set Measurements...", "area integrated area_fraction limit display scientific redirect=None decimal=3" ) IJ.setForegroundColor(0, 0, 0) IJ.setBackgroundColor(255, 255, 255) #User Input Dialoge analyses = ["Counts", "ATP"] yn = ["YES", "NO"] gdp = GenericDialogPlus("Ex Vivo Granule Analysis") gdp.addMessage("Choose a UNIQUE directory to save analysis files") gdp.addDirectoryOrFileField("Output Directory", "D:/Samantha/") gdp.addMessage("IMPORTANT: Files are tracked based on input order") gdp.addMessage("Select input files (.tiff)...") gdp.addFileField("Wildtype", "D:/Samantha/test/VLEwt.tif") gdp.addFileField("DIC", "D:/Samantha/test/dic.tif") gdp.addFileField("Mutant", "D:/Samantha/test/ddmut.tif") gdp.addFileField("Background (DAPI)", "D:/Samantha/test/bg.tif") gdp.addChoice("Select analysis type", analyses, "Counts")