def get_roi_manager(new=False): """ flexible ROI mgr handling, copied from Particles_From_Mask.py template in Fiji if new = True, a new blank mgr is returned if new = False (default) and the ROI manager is open, returns that mgr. if new = False and the ROI manager is NOT open, creates a new one without throwing an error """ rm = RoiManager.getInstance() if not rm: rm = RoiManager() if new: rm.runCommand("Reset") return rm
def mergeRois(components): RoiManager() roiManager = RoiManager.getRoiManager() toBeDeleted = [] for component in components: if len(component) > 1: roiManager.setSelectedIndexes(component) roiManager.runCommand("Combine") roiManager.runCommand("Update") toBeDeleted = toBeDeleted + component[1:] if len(toBeDeleted) > 0: roiManager.setSelectedIndexes(toBeDeleted) roiManager.runCommand("Delete")
def generate_limit_labels(imp, limits, cb_fraction, params): """generate text ROIs in correct positions to label colorbar""" rois = [] w = imp.getWidth() h = imp.getHeight() txt_h_px = float(h) / 15 txt_sz_pt = int(round((18.0 / 24.0) * txt_h_px)) for limit in limits: roi = TextRoi(1, 1, str(round(limit, 3)), Font("SansSerif", Font.ITALIC, txt_sz_pt)) roi.setJustification(TextRoi.RIGHT) roi.setFillColor(Color.BLACK) roi.setStrokeColor(Color.WHITE) rois.append(roi) roim = RoiManager(False) roim.reset() imp.show() mbui.autoset_zoom(imp) for fridx in range(1, imp.getNSlices() + 1): imp.setPosition(fridx) roi_uu = rois[1].clone() xpos = w - cb_fraction * w - float(w) / 100 - rois[1].getFloatWidth() roi_uu.setLocation(xpos, 1) imp.setRoi(roi_uu) roim.addRoi(roi_uu) roi_ll = rois[0].clone() roi_ll.setLocation(xpos, h - rois[0].getFloatHeight()) imp.setRoi(roi_ll) roim.addRoi(roi_ll) roim.runCommand("Show All") FileSaver(imp).saveAsTiff( os.path.join(params.output_path, "overlaid curvature nudged labels.tif")) # nudge positions roim.reset() imp.killRoi() for fridx in range(1, imp.getNSlices() + 1): imp.setPosition(fridx) roi_uu = rois[1].clone() xpos = w - cb_fraction * w - float(w) / 100 roi_uu.setLocation(xpos, 1) imp.setRoi(roi_uu) roim.addRoi(roi_uu) roi_ll = rois[0].clone() roi_ll.setLocation(xpos, h - rois[0].getFloatHeight()) imp.setRoi(roi_ll) roim.addRoi(roi_ll) roim.runCommand("Show All") FileSaver(imp).saveAsTiff( os.path.join(params.output_path, "overlaid curvature.tif")) return imp
def createROI(xy_coord, diameter): imp = WindowManager.getCurrentImage() pixelWidth = imp.getCalibration().pixelWidth pixelHeight = imp.getCalibration().pixelHeight x_diameter = diameter / pixelWidth y_diameter = diameter / pixelHeight x_coord = xy_coord[0] / pixelWidth - (0.5 * x_diameter) y_coord = xy_coord[1] / pixelHeight - (0.5 * y_diameter) rm = RoiManager.getInstance() if not rm: rm = RoiManager() roi = OvalRoi(x_coord, y_coord, x_diameter, y_diameter) rm.addRoi(roi)
def generate_cell_rois(seg_binary_imp): """generate rois from which cell shape information will be gleaned""" seg_binary_imp.killRoi() mxsz = seg_binary_imp.width * seg_binary_imp.height roim = RoiManager(False) pa_options = ParticleAnalyzer.AREA | ParticleAnalyzer.PERIMETER | ParticleAnalyzer.SHAPE_DESCRIPTORS pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, pa_options, None, 1000, mxsz) pa.setRoiManager(roim) roim.reset() pa.analyze(seg_binary_imp) rois = roim.getRoisAsArray() roim.reset() roim.close() return rois
def process(inputpath, outputpath): imp = IJ.openImage(inputpath) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) IJ.setThreshold(imp, t1, 255) #imp.show() #WaitForUserDialog("Title", "Look at image").show() IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Watershed", "") # 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, 50, 9999999999999999, 0.2, 1.0) pa.setHideOutputImage(True) pa.analyze(imp) imp.changes = False imp.close() areas = table.getColumn(0) summary = {} if areas: summary['Image'] = filename summary['Nuclei.count'] = len(areas) summary['Area.Covered'] = sum(areas) fieldnames = list(summary.keys()) with open(outputpath, '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)
def save_qc_image(imp, rois, output_path): """save rois overlaid on imp to output_path""" imp.killRoi() if len(rois) > 0: roim = RoiManager(False) for roi in rois: roim.addRoi(roi) roim.runCommand("Show All with labels") RGBStackConverter.convertToRGB(imp) roim.moveRoisToOverlay(imp) FileSaver(imp).saveAsTiff(output_path) roim.runCommand("Show None") roim.close() else: FileSaver(imp).saveAsTiff(output_path) return
def f3_clic_SaveROIs(event): RM = RoiManager() # we create an instance of the RoiManager class rm = RM.getRoiManager() pixels = gvars['eroded_pixels'] path_to_updated_ROIs = str(gvars['path_original_image'].replace(".tif", "") + "_Erosion_" +str(pixels)+ "px_" + "RoiSet.zip") rm.runCommand("Save", path_to_updated_ROIs) print("ROIs saved") print pixels #Save Outline Images imp = gvars["workingImage"] path_to_simple_outline = str(gvars['path_original_image'].replace(".tif", "") + "_Erosion_" +str(pixels)+ "px_" + "Outlines.jpg") outlines_image = imp.flatten() IJ.saveAs(outlines_image, "JPG", path_to_simple_outline) JOptionPane.showMessageDialog(None, "ROIs saved to:\n%s\nOutline image saved to:\n%s" % (path_to_updated_ROIs, path_to_simple_outline))
def get_no_nuclei_fully_enclosed(roi, full_nuclei_imp, overlap_threshold=0.65): """for a given cell roi and ImagePlus with binary nuclei, return how many nuclei lie ENTIRELY within the cell""" bbox = roi.getBounds() full_nuclei_imp.setRoi(roi) cropped_nuc_imp = full_nuclei_imp.crop() roi.setLocation(0, 0) cropped_nuc_imp.setRoi(roi) cropped_nuc_imp.killRoi() roim = RoiManager(False) mxsz = cropped_nuc_imp.getWidth() * cropped_nuc_imp.getHeight() pa = ParticleAnalyzer( ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA | ParticleAnalyzer.SLICE | ParticleAnalyzer.CENTROID, None, 0, mxsz) pa.setRoiManager(roim) pa.analyze(cropped_nuc_imp) cell_imp = IJ.createImage("Cell binary", cropped_nuc_imp.getWidth(), cropped_nuc_imp.getHeight(), 1, 8) IJ.run(cell_imp, "Select All", "") IJ.run(cell_imp, "Set...", "value=0 slice") cell_imp.setRoi(roi) IJ.run(cell_imp, "Set...", "value=255 slice") no_enclosed_nuclei = 0 for idx, nuc_roi in enumerate(roim.getRoisAsArray()): test_imp = Duplicator().run(cell_imp) test_imp.setRoi(nuc_roi) IJ.run(test_imp, "Set...", "value=255 slice") test_imp.killRoi() IJ.run(test_imp, "Create Selection", "") IJ.run(test_imp, "Make Inverse", "") test_roi = test_imp.getRoi() test_roi_stats = test_roi.getStatistics() cell_roi_stats = roi.getStatistics() nuc_roi_stats = nuc_roi.getStatistics() if test_roi_stats.area < ( cell_roi_stats.area + (1 - overlap_threshold) * nuc_roi_stats.area ): # i.e. if more than (100*overlap_threshold)% of nucleus is inside cell... no_enclosed_nuclei += 1 test_imp.changes = False test_imp.close() roi.setLocation(bbox.getX(), bbox.getY()) cropped_nuc_imp.changes = False cropped_nuc_imp.close() cell_imp.changes = False cell_imp.close() return no_enclosed_nuclei
def RoiEroder(pixels): RM = RoiManager() # we create an instance of the RoiManager class rm = RM.getRoiManager() # "activate" the RoiManager otherwise it can behave strangely rm.reset() # Re-open temporary original ROIs temp_roi_path = gvars['tempFile'] rm.runCommand("Open", temp_roi_path) print "Temp ROIs OPENED" for i in range(0, rm.getCount()): roi = rm.getRoi(i) new_roi = RoiEnlarger.enlarge(roi, -pixels) # Key to use this instead of the IJ.run("Enlarge... much faster!! rm.setRoi(new_roi,i) gvars['eroded_pixels'] = pixels # Store globally the amount of pixels used to later save them in the ROI file name
def roiprocess(imp, filename): # get the ROI manager instance rm = RoiManager.getInstance() if rm is None: rm = RoiManager() rm.runCommand(imp, "Select All") # rm.runCommand("Deselect"); # deselect ROIs to save them all rm.runCommand(imp, 'Show All') # define the path to save the rois as azip file roisavelocation = os.path.splitext(filename)[0] + '_RoiSet.zip' # log.info('ROISs saved: ' + roisavelocation) # print('ROIs saved: ', roisavelocation) rm.runCommand("Save", roisavelocation) return roisavelocation
def analyzeTUB(): rm = RoiManager().getInstance() #Set imageJ preference meassurements to "area" IJ.run("Set Measurements...", "area display redirect=None decimal=3") #Variable used for iteration counter = 0 #Clear previous resuslts IJ.run("Clear Results") # Make library, to be iterated through. Room for improvement lis_dic = [{'path': sub[i]} for i in range(len(sub))] if not lis_dic: sys.exit('Did you check the right box?') # Calculate area of channel #1 (Calculation requires that area is chosen as measured value) for i in lis_dic: print i for p in data[counter][::-1]: print p if '_' + channel1 + '_' in p: imp1 = IJ.openImage(i['path'] + '/' + p) IJ.setThreshold(imp1, lowth1, 255) IJ.run(imp1, "Create Selection", "") roi = rm.getRoi(imp1) #rm.runCommand(imp1, 'Add') IJ.run(imp1, "Measure", "") if '_' + channel2 + '_' in p: imp2 = IJ.openImage(i['path'] + '/' + p) IJ.setThreshold(imp2, lowth2, 255) rm.runCommand(imp1, 'Select') IJ.run(imp2, "Analyze Particles...", "size=0-4000 summarize") counter += 1 # Reset counter counter = 0 IJ.renameResults(channel2)
def Weka_Segm(dirs): """ Loads trained classifier and segments cells """ """ in aligned images according to training. """ # Define reference image for segmentation (default is timepoint000). w_train = os.path.join(dirs["Composites_Aligned"], "Timepoint000.tif") trainer = IJ.openImage(w_train) weka = WekaSegmentation() weka.setTrainingImage(trainer) # Select classifier model. weka.loadClassifier(str(classifier)) weka.applyClassifier(False) segmentation = weka.getClassifiedImage() segmentation.show() # Convert image to 8bit ImageConverter(segmentation).convertToRGB() ImageConverter(segmentation).convertToGray8() # Threshold segmentation to soma only. hist = segmentation.getProcessor().getHistogram() lowth = Auto_Threshold.IJDefault(hist) segmentation.getProcessor().threshold(lowth) segmentation.getProcessor().setThreshold(0, 0, ImageProcessor.NO_LUT_UPDATE) segmentation.getProcessor().invert() segmentation.show() # Run Watershed Irregular Features plugin, with parameters. IJ.run(segmentation, "Watershed Irregular Features", "erosion=20 convexity_treshold=0 separator_size=0-Infinity") # Make selection and add to RoiManager. RoiManager() rm = RoiManager.getInstance() rm.runCommand("reset") roi = ThresholdToSelection.run(segmentation) segmentation.setRoi(roi) rm.addRoi(roi) rm.runCommand("Split")
def save_roi_set(imp=IJ.getImage()): img_dir, name = get_file_info() roi_dir = make_roi_dir(img_dir, name) roi_path = make_roi_path(roi_dir, name) Roi.setColor(Color.blue) rm = RoiManager().getInstance() rm.deselect() rm.runCommand("Save", roi_path) ol = imp.getOverlay() if ol is None: ol = Overlay() for roi in rm.getRoisAsArray(): ol.add(roi) imp.setOverlay(ol) rm.runCommand("delete") ol.setStrokeColor(Color.blue) Roi.setColor(Color.yellow)
def manual_analysis(imp, file_name, output_folder): """perform analysis based on manually drawn cells""" cal = imp.getCalibration() channel_imps = ChannelSplitter.split(imp) gfp_imp = channel_imps[0] IJ.setTool("freehand") proceed = False roim = RoiManager() roim.runCommand("Show all with labels") dialog = NonBlockingGenericDialog("Perform manual segmentation") dialog.setOKLabel("Proceed to next image...") dialog.addMessage("Perform manual segmentation: ") dialog.addMessage( "Draw around cells and add to the region of interest manager (Ctrl+T)") dialog.addMessage( "You can see what you've added so far if you check \"show all\" on the ROI manager" ) dialog.addMessage( "Then press \"proceed to next image\" when all cells have been added") dialog.showDialog() if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled") elif dialog.wasOKed(): rois = roim.getRoisAsArray() roim.reset() roim.close() out_stats = generate_cell_shape_results(rois, gfp_imp, cal, file_name) print("Number of cells identified = {}".format(len(out_stats))) # save output save_qc_image( imp, rois, "{}_plus_overlay.tiff".format( os.path.join(output_folder, os.path.splitext(file_name)[0]))) save_cell_rois(rois, output_folder, os.path.splitext(file_name)[0]) imp.changes = False imp.close() save_output_csv(out_stats, output_folder) return out_stats return None
def AnalyzeParticle(IMP): rm = RoiManager().getInstance2() rt = ResultsTable() #再現性確保のために最終的には実装 #IJ.run("Set Measurements...","area centroid fit redirect=None decimal=3") #https://imagej.nih.gov/ij/developer/api/constant-values.html#ij.plugin.filter.ParticleAnalyzer.SHOW_RESULTS #表示オプション無し、resultは全部選択 PA = ParticleAnalyzer(0 , 1043199 , rt, 10000, 300000, 0.2, 1.0) PA.setRoiManager(rm) PA.analyze(IMP) #IJ.run(IMP, "Analyze Particles...", "display clear include add") rm.runCommand("Save", "C:/Users/For Programming/Documents/Python Scripts/OutletHDD/aaa.zip") rt.saveAs("C:/Users/For Programming/Documents/Python Scripts/OutletHDD/aaa.csv") #最後に全ての結果をCloseする。 #写真を先に消さないとバグる。 IMP.close() rm.close() rt.reset()
def process(srcDir, dstDir, currentDir, fileName, keepDirectories): print "Processing:" ROIpath, V1S1RL = os.path.split(currentDir) # Opening the image print "Open image file", fileName imp = IJ.openImage(os.path.join(currentDir, fileName)) imp.show() print "Compute F/F0" IJ.run(imp, "F div F0", "6") imp.close() V1S1RL = "RoiSet " + V1S1RL + ".zip" # Put your processing commands here! ROIPath = ROIpath + "/" + V1S1RL print "Open ROIS", ROIPath rm = RoiManager.getInstance() if not rm: rm = RoiManager() rm.reset() rm.runCommand("open", ROIPath) rm.runCommand("Show All") print "Multi Measure" imp = IJ.getImage() rt = rm.multiMeasure(imp) imp.close() imp = IJ.getImage() imp.close() # Saving the image saveDir = currentDir.replace(srcDir, dstDir) if keepDirectories else dstDir if not os.path.exists(saveDir): os.makedirs(saveDir) print "Saving to", saveDir rt.save(os.path.join(saveDir, fileName + '.csv')) # IJ.saveAs(imp, "Tiff", os.path.join(saveDir, fileName)); imp.close()
def main(parentpath, cellNo): rootname = "cell" + str(cellNo) roizipname = 'RoiSet_' + rootname + '.zip' imagename = rootname + '_virus_median.tif' #pp = '/Users/miura/Desktop/161122 ctrl croped and 16 frames/RoiSet_cell5.zip' # unzipping http://stackoverflow.com/questions/3451111/unzipping-files-in-python #pp = '/Users/miura/Desktop/161122 ctrl croped and 16 frames/RoiSet_cell5/0005-0419-0327.roi' zippp = os.path.join(parentpath, roizipname) rm = RoiManager(False) rm.runCommand("Open", zippp) cellroi = rm.getRoi(2) if cellroi.getType() != 3: print "ROI type mismatch! ... ABORT" sys.exit() #imagepath = '/Users/miura/Desktop/161122 ctrl croped and 16 frames/cell1_virus_median.tif' imagepath = os.path.join(parentpath, imagename) tracks, cellarea, postcounts, postcounts2, precounts, imp, reallength, secondFrameVirusCounts = core(cellroi, imagepath) return tracks, cellarea, postcounts, postcounts2, precounts, imp, reallength, secondFrameVirusCounts
def runScript(nCols, nRows, circRad): print('___Running Blobber___') circXUpLeft = 33. circYUpLeft = 915. circXUpRight = 1033. circYUpRight = 627. circXLowLeft = 95. circYLowLeft = 1125. imp = IJ.getImage() nSlices = imp.getNSlices() print('The image has {} slices'.format(nSlices)) circXUpLeft, circYUpLeft = getEdgeCoord(circXUpLeft, circYUpLeft, circRad, imp, 'Upper Left') print('upper left x,y: {},{}'.format(circXUpLeft, circYUpLeft)) circXUpRight, circYUpRight = getEdgeCoord(circXUpRight, circYUpRight, circRad, imp, 'Upper Right') print('upper right x,y: {},{}'.format(circXUpRight, circYUpRight)) circXLowLeft, circYLowLeft = getEdgeCoord(circXLowLeft, circYLowLeft, circRad, imp, 'Lower Left') print('lower left x,y: {},{}'.format(circXLowLeft, circYLowLeft)) hOffsetY = (circYUpRight - circYUpLeft) / (nCols - 1) hOffsetX = (circXUpRight - circXUpLeft) / (nCols - 1) vOffsetY = (circYLowLeft - circYUpLeft) / (nRows - 1) vOffsetX = (circXLowLeft - circXUpLeft) / (nRows - 1) x, y = createArrayCoord(hOffsetX, hOffsetY, vOffsetX, vOffsetY, nCols, nRows, circXUpLeft, circYUpLeft) RM = RoiManager() rm = RM.getRoiManager() imp, rm = makeSelections(x, y, rm, imp, circRad) imp, rm = measureSelections(imp, rm, nCols, nRows) IJ.run(imp, "Select None", "")
def keep_largest_blob(imp): """remove all blobs other than the largest by area""" rt = ResultsTable(); mxsz = imp.width * imp.height; roim = RoiManager(False); pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA | ParticleAnalyzer.SLICE, rt, 0, mxsz); pa.setRoiManager(roim); for idx in range(1, imp.getImageStackSize()+1): roim.reset(); rt.reset(); imp.setPosition(idx); pa.analyze(imp); rt_areas = rt.getColumn(rt.getColumnIndex("Area")).tolist(); mx_ind = rt_areas.index(max(rt_areas)) indices_to_remove = [a for a in range(0,len(rt_areas)) if a != mx_ind]; indices_to_remove.reverse(); for rem_idx in indices_to_remove: roim.select(imp, rem_idx); IJ.run(imp, "Set...", "value=0 slice"); imp.killRoi(); roim.reset(); roim.close(); return imp;
def analyze_homogeneity(image_title): IJ.selectWindow(image_title) raw_imp = IJ.getImage() IJ.run(raw_imp, "Duplicate...", "title=Homogeneity duplicate") IJ.selectWindow('Homogeneity') hg_imp = IJ.getImage() # Get a 2D image if hg_imp.getNSlices() > 1: IJ.run(hg_imp, "Z Project...", "projection=[Average Intensity]") hg_imp.close() IJ.selectWindow('MAX_Homogeneity') hg_imp = IJ.getImage() hg_imp.setTitle('Homogeneity') # Blur and BG correct the image IJ.run(hg_imp, 'Gaussian Blur...', 'sigma=' + str(HOMOGENEITY_RADIUS) + ' stack') # Detect the spots IJ.setAutoThreshold(hg_imp, HOMOGENEITY_THRESHOLD + " dark") rm = RoiManager(True) table = ResultsTable() pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES, Measurements.AREA, # measurements table, # Output table 0, # MinSize 500, # MaxSize 0.0, # minCirc 1.0) # maxCirc pa.setHideOutputImage(True) pa.analyze(hg_imp) areas = table.getColumn(table.getHeadings().index('Area')) median_areas = compute_median(areas) st_dev_areas = compute_std_dev(areas, median_areas) thresholds_areas = (median_areas - (2 * st_dev_areas), median_areas + (2 * st_dev_areas)) roi_measurements = {'integrated_density': [], 'max': [], 'area': []} IJ.setForegroundColor(0, 0, 0) for roi in rm.getRoisAsArray(): hg_imp.setRoi(roi) if REMOVE_CROSS and hg_imp.getStatistics().AREA > thresholds_areas[1]: rm.runCommand('Fill') else: roi_measurements['integrated_density'].append(hg_imp.getStatistics().INTEGRATED_DENSITY) roi_measurements['max'].append(hg_imp.getStatistics().MIN_MAX) roi_measurements['integrated_densities'].append(hg_imp.getStatistics().AREA) rm.runCommand('Delete') measuremnts = {'mean_integrated_density': compute_mean(roi_measurements['integrated_density']), 'median_integrated_density': compute_median(roi_measurements['integrated_density']), 'std_dev_integrated_density': compute_std_dev(roi_measurements['integrated_density']), 'mean_max': compute_mean(roi_measurements['max']), 'median_max': compute_median(roi_measurements['max']), 'std_dev_max': compute_std_dev(roi_measurements['max']), 'mean_area': compute_mean(roi_measurements['max']), 'median_area': compute_median(roi_measurements['max']), 'std_dev_area': compute_std_dev(roi_measurements['max']), } # generate homogeinity image # calculate interpoint distance in pixels nr_point_columns = int(sqrt(len(measuremnts['mean_max']))) # TODO: This is a rough estimation that does not take into account margins or rectangular FOVs inter_point_dist = hg_imp.getWidth() / nr_point_columns IJ.run(hg_imp, "Maximum...", "radius="+(inter_point_dist*1.22)) # Normalize to 100 IJ.run(hg_imp, "Divide...", "value=" + max(roi_measurements['max'] / 100)) IJ.run(hg_imp, "Gaussian Blur...", "sigma=" + (inter_point_dist/2)) hg_imp.getProcessor.setMinAndMax(0, 255) # Create a LUT based on a predefined threshold red = zeros(256, 'b') green = zeros(256, 'b') blue = zeros(256, 'b') acceptance_threshold = HOMOGENEITY_ACCEPTANCE_THRESHOLD * 256 / 100 for i in range(256): red[i] = (i - acceptance_threshold) green[i] = (i) homogeneity_LUT = LUT(red, green, blue) hg_imp.setLut(homogeneity_LUT) return hg_imp, measuremnts
elif template.height > image.height or template.width > image.width: raise Exception( 'The template is larger in width and/or height than the searched image' ) ### Initialise outputs ### if show_table: from ij.measure import ResultsTable from utils import AddToTable Table = ResultsTable().getResultsTable( ) # allows to append to an existing table if add_roi: from ij.plugin.frame import RoiManager RM = RoiManager() rm = RM.getInstance() # Convert method string to the opencv corresponding index Dico_Method = { "Square difference": 0, "Normalised Square Difference": 1, "Cross-Correlation": 2, "Normalised cross-correlation": 3, "0-mean cross-correlation": 4, "Normalised 0-mean cross-correlation": 5 } Method = Dico_Method[method] # Loop over the images in the stack (or directly process if unique) ImageStack = image.getStack()
#convert to RGB IC(imp).convertToRGB() #show image imp.show() #Define ROI of whole image (basically) imp.setRoi(1,1,478,479) ######OPTIONAL############## IJ.run("Brightness/Contrast...") IJ.run(imp, "Enhance Contrast", "saturated=.8") #open and clear ROI manager rm = RoiManager.getInstance() if not rm: rm = RoiManager() rm.reset() #If want to choose regions #IJ.setTool("rectangle") #waiting = WaitForUserDialog("Action required","Draw a single ROI with all puncta of interest inside! Then hit OK") #waiting.show() #set title variable of image Title=imp.getTitle() #make output as outpath and title outdir=os.path.join(outdir,Title) #run puncta analyzer IJ.run(imp, "Puncta Analyzer", "condition=1 red green subtract save rolling=50 light"); #save results IJ.selectWindow("Results")
def analyzeParticles(imp, minsize, maxsize, mincirc, maxcirc, #filename='Test.czi', addROIManager=False, #headless=False, exclude=True): if GraphicsEnvironment.isHeadless(): print('Headless Mode detected. Do not use ROI Manager.') addROIManager = False if addROIManager: # get the ROI manager instance rm = RoiManager.getInstance() if rm is None: rm = RoiManager() rm.runCommand("Associate", "true") if not exclude: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_MANAGER \ + PA.ADD_TO_OVERLAY \ if exclude: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_MANAGER \ + PA.ADD_TO_OVERLAY \ + PA.EXCLUDE_EDGE_PARTICLES if not addROIManager: if not exclude: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_OVERLAY \ if exclude: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_OVERLAY \ + PA.EXCLUDE_EDGE_PARTICLES measurements = PA.STACK_POSITION \ + PA.LABELS \ + PA.AREA \ + PA.RECT \ + PA.PERIMETER \ + PA.SLICE \ + PA.SHAPE_DESCRIPTORS \ + PA.CENTER_OF_MASS \ + PA.CENTROID results = ResultsTable() p = PA(options, measurements, results, minsize, maxsize, mincirc, maxcirc) p.setHideOutputImage(True) particlestack = ImageStack(imp.getWidth(), imp.getHeight()) for i in range(imp.getStackSize()): imp.setSliceWithoutUpdate(i + 1) ip = imp.getProcessor() # convert to a mask for the particle analyzer ip.invert() # do the particle analysis p.analyze(imp, ip) mmap = p.getOutputImage() # add the slide to the full stack particlestack.addSlice(mmap.getProcessor()) return particlestack, results
IJ.run("Threshold...") WaitForUserDialog("Title", "Adjust threshold for " + color[i]).show() #Get the threshold you've used summary[color[i] + "-threshold-used"] = ImageProcessor.getMinThreshold(channel.getProcessor()) #Threshold and watershed IJ.run(channel, "Convert to Mask", "") IJ.run(channel, "Watershed", "") table = ResultsTable() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim) #Analyses particles: finds all the objects that match criteria pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES, Measurements.AREA, table, minimum_size, maximum_size, 0.1, 1.0) pa.setHideOutputImage(True) pa.analyze(channel) if thresholdMode: channel.show() WaitForUserDialog("Title", "Look at threshold for" + color[i]).show() #adds count to summary
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)
# return # Prevent further propagation of the key event: keyEvent.consume() # MAIN code imp = IJ.getImage() killIt = False if imp.getHeight() == 1024: # half-chip size hOffset = 512 elif imp.getHeight() == 2048: #full-chip image hOffset = 0 else: gdGoodBye = GenericDialog("Dimensions error") gdGoodBye.addMessage( 'Image must be 2048x2048, or 2048x1024 pixels! \n I retire!') gdGoodBye.showDialog() killIt = True if not killIt: IJ.setTool(Toolbar.RECTANGLE) manager = RoiManager.getInstance() if manager is None: manager = RoiManager() reset() listener = ML() keyLis = ListenToKey() win = imp.getWindow() win.getCanvas().addMouseListener(listener) win.getCanvas().addKeyListener(keyLis)
def process(subFolder, outputDirectory, filename): imp = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", ".tif")) 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, 2, 255) 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") imp.getProcessor().invert() rm = RoiManager(True) imp.getProcessor().setThreshold(0, 0, ImageProcessor.NO_LUT_UPDATE) boundroi = ThresholdToSelection.run(imp) rm.addRoi(boundroi) if not displayImages: imp.changes = False imp.close() images = [None] * 5 intensities = [None] * 5 blobsarea = [None] * 5 blobsnuclei = [None] * 5 bigAreas = [None] * 5 for chan in channels: v, x = chan images[x] = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", "_ch0" + str(x) + ".tif")) imp = images[x] for roi in rm.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA) intensities[x] = stats.mean bigAreas[x] = stats.area rm.close() # Opens the ch00 image and sets default properties imp = IJ.openImage(inputDirectory + subFolder + '/' + filename) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 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) blobsnuclei[x] = len(blobs) if not displayImages: imp.changes = False imp.close() roim.reset() roim.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)
import os import shutil import csv blinded_base = "/Users/nick/Desktop/em-round-2/calibrated-blinded" data = "/Users/nick/Desktop/em-round-2/done" img = WindowManager.getCurrentImage() image_title = img.getShortTitle() # make paths for moving when done. full_img_path_orig = os.path.join(blinded_base, image_title + ".tif") full_img_path_done = os.path.join(data, image_title + ".tif") # get roi manager roim = RoiManager().getRoiManager() # make savepaths for csv and rois roimsave = os.path.join(data, image_title + "_rois.zip") csvsave = os.path.join(data, image_title + "_data.csv") csv_ = [["image", "roi_name", "uncalibrated_length"]] for roi, _ in enumerate(roim.getRoisAsArray()): target = roim.getRoi(roi) csv_.append([image_title, target.getName(), target.getLength()]) # write and save csv with open(csvsave, "w") as c: writer = csv.writer(c) for l in csv_:
], ) writer.writeheader() writer.writerows(current) print("wrote results to {}".format(out_path)) # imp = IJ.openImage(th_files[0]) # imp.show() # get open image imp = IJ.getImage() image_name = imp.getShortTitle() # get roi manager roi_manager = RoiManager().getInstance() all_rois = roi_manager.getRoisAsArray() csv_name = make_path(out_dir, image_name, ".csv") roi_name = make_path(out_dir, image_name, "_rois.zip") old_name = make_path(target_dir, image_name, ".tif") new_name = make_path(out_dir, image_name, ".tif") current = [] for roi in all_rois: res = get_stats(2, roi, imp) current.append(res) # write csv write_csv(current, csv_name) # save all rois