def pre_process_images(image_input, timepoints): #correct drift IJ.run( image_input, "Properties...", "channels=2 slices=1 frames=" + str(timepoints) + " unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000" ) corrected_img = run_3d_drift_correct(image_input) #split channels red_corrected_img, phase_corrected_img = ChannelSplitter.split( corrected_img) #get image dimensions, set ROI remove part of flouresncent ring x_size = ImagePlus.getDimensions(red_corrected_img)[0] y_size = ImagePlus.getDimensions(red_corrected_img)[1] x_start = 0 y_start = 0 red_corrected_img.setRoi(OvalRoi(x_start, y_start, x_size, y_size)) IJ.run(red_corrected_img, "Make Inverse", "") IJ.setForegroundColor(0, 0, 0) IJ.run(red_corrected_img, "Fill", "stack") red_corrected_img.killRoi() #correcting background IJ.run( red_corrected_img, "Properties...", "channels=1 slices=" + str(timepoints) + " frames=1 unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000" ) #red_corrected_background_img = apply_rollingball(red_corrected_img, 7.0, False, False,False, False, False) testset = basic.BaSiCSettings() testset.imp = red_corrected_img testset.myShadingEstimationChoice = "Estimate shading profiles" testset.myShadingModelChoice = "Estimate both flat-field and dark-field" testset.myParameterChoice = "Manual" testset.lambda_flat = 2.0 testset.lambda_dark = 2.0 testset.myDriftChoice = "Replace with zero" testset.myCorrectionChoice = "Compute shading and correct images" test = basic.BaSiC(testset) test.run() red_corrected_background_img = test.getCorrectedImage() #change properties back and perform bleach correction IJ.run( red_corrected_background_img, "Properties...", "channels=1 slices=1 frames=" + str(timepoints) + " unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000" ) red_corrected_background_img_dup = red_corrected_background_img.duplicate() corrected_bleach = BleachCorrection_MH(red_corrected_background_img) corrected_bleach.doCorrection() return (red_corrected_background_img_dup, red_corrected_background_img)
def run(): roidir = '/Volumes/TRANSCEND/LauraLeopold/Rois/' maskdir = '/Volumes/TRANSCEND/LauraLeopold/Mask/' originaldir = '/Volumes/TRANSCEND/LauraLeopold/Original/' Raw_path = os.path.join(originaldir, '*tif') X = glob.glob(Raw_path) axes = 'YX' for fname in X: print(fname) IJ.open(fname) imp = IJ.getImage() Name = os.path.basename(os.path.splitext(fname)[0]) RoiName = roidir + Name + '.roi' Roi = IJ.open(RoiName) rm = RoiManager.getInstance() if (rm == None): rm = RoiManager() rm.addRoi(Roi) print(fname, RoiName) if not rm: print "Please first add some ROIs to the ROI Manager" return impMask = IJ.createImage("Mask", "8-bit grayscale-mode", imp.getWidth(), imp.getHeight(), imp.getNChannels(), imp.getNSlices(), imp.getNFrames()) IJ.setForegroundColor(255, 255, 255) rm.runCommand(impMask, "Deselect") rm.runCommand(impMask, "Fill") rm.runCommand('Delete') IJ.saveAs(impMask, '.tif', maskdir + Name) imp.close()
def createOutputImg(image, rois, particle, ptsFcs=None): """create an output image which as overlay of channel""" IJ.setForegroundColor(255, 0, 0) IJ.run(image, "Enhance Contrast", "saturated=0") IJ.run(image, "RGB Color", "") IJ.setForegroundColor(255, 0, 0) ip = image.getProcessor() ip.setColor(Color.red) for roi in rois: ip.draw(roi) ip.setColor(Color.green) if particle is not None: for part in particle: ip.draw(rois[part]) ip.setLineWidth(2) ip.setColor(Color.white) if ptsFcs is not None: print "Some fcs points" for i, pt in enumerate(ptsFcs): drawCross(ip, pt, 8) ip.drawString(str(i + 1), pt[0] + 1, pt[1] - 1) image.setProcessor(ip) return image
def particleRemover(image, minArea): '''Send in a thresholded image, remove the small spots''' numSlices = image.getImageStackSize() particleRoiM = RoiManager(True) ParticleAnalyzer.setRoiManager(particleRoiM) IJ.run(image, "Analyze Particles...", "size=0-" + str(minArea) + " circularity=0.00-1.00 include show=Nothing add stack"); # Set the fill color to black before filling IJ.setForegroundColor(0, 0, 0); particleRoiM.runCommand("Fill"); particleRoiM.runCommand("Reset");
def doInBackground(self): imp = self.imp print "started" ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') print st # Disable frame3 buttons in GUI while loading ROIs f2_btn_original.setEnabled( 0 ) f2_btn_label.setEnabled( 0 ) f2_btn_prev.setEnabled( 0 ) f2_btn_next.setEnabled( 0 ) RM = RoiManager() # we create an instance of the RoiManager class rm = RM.getRoiManager() # "activate" the RoiManager otherwise it can behave strangely rm.reset() rm.runCommand(imp,"Show All without labels") # we make sure we see the ROIs as they are loading imp2 = imp.duplicate() ip = imp2.getProcessor() width = imp2.getWidth() height = imp2.getHeight() - 1 max_label = int(imp2.getStatistics().max) max_digits = int(math.ceil(math.log(max_label,10))) # Calculate the number of digits for the name of the ROI (padding with zeros) IJ.setForegroundColor(0, 0, 0) # We pick black color to delete the label already computed for j in range(height): for i in range(width): current_pixel_value = ip.getValue(i,j) if current_pixel_value > 0: IJ.doWand(imp2, i, j, 0.0, "Legacy smooth"); # We add this ROI to the ROI manager roi = imp2.getRoi() roi.setName(str(int(current_pixel_value)).zfill(max_digits)) rm.addRoi(roi) ip.fill(roi) # Much faster than IJ.run(imp2, "Fill", .... # Update ProgressBar progress = int((current_pixel_value / max_label) * 100) self.super__setProgress(progress) rm.runCommand(imp,"Sort") # Sort the ROIs in the ROI manager rm.runCommand(imp,"Show All without labels") ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') print st print "Finished"
def run(): rm = RoiManager.getInstance() if not rm: print "Please first add some ROIs to the ROI Manager" return impMask = IJ.createImage("Mask", "8-bit grayscale-mode", imp.getWidth(), imp.getHeight(), imp.getNChannels(), imp.getNSlices(), imp.getNFrames()) IJ.setForegroundColor(255, 255, 255) rm.runCommand(impMask, "Deselect") rm.runCommand(impMask, "Fill") impMask.show()
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'))
def testRectangle(self): image = IJ.createImage("test", "8-bit black", 255, 255, 1) image.show() IJ.setForegroundColor(255,255,255); image.getProcessor().fillRect(10, 10, 100, 100) findEdges(image); v1 = image.getPixel(8,8)[0] v2 = image.getPixel(9,9)[0] v3 = image.getPixel(10,10)[0] v4 = image.getPixel(11,11)[0] self.assertEquals(v1, 0) self.assertEquals(v2, 255) self.assertEquals(v3, 255) self.assertEquals(v4, 0)
fileout = os.path.join(analyzeDir, os.path.basename(filepath)) IJ.saveAs(impOut, "Jpeg", fileout) def createOutputImg(image, roim, centPart, metaphase): #maximal projection imp = image if image.getNSlices() > 1: zp = ZProjector() zp.setMethod(zp.MAX_METHOD) zp.setImage(image) zp.doProjection() imp = zp.getProjection() else: imp = image IJ.run(imp,"Enhance Contrast", "saturated=0.35") IJ.setForegroundColor(255,0,0) #need to show the image to draw overlay imp.show() IJ.run(imp,"RGB Color", ""); for i in range(roim.getCount()): roim.select(imp, i) roim.runCommand("Draw") if metaphase: IJ.setForegroundColor(0,255,255) else: IJ.setForegroundColor(0,255,0) roim.select(imp, centPart)
def locateTumors(imp): '''Locates the tumors in an image; white is location, black is not''' # Determine if the tumor is black on a white background or white # on a black background ip = imp.getProcessor() stats = IS.getStatistics(ip, IS.MEAN, imp.getCalibration()) mean = stats.mean if mean >= 20: # Black tumor on white background IJ.run(imp, 'Subtract Background...', 'rolling=' + str(backgroundRadius) + ' light sliding stack'); IJ.run(imp, "Invert", "stack") else: IJ.run(imp, 'Subtract Background...', 'rolling=' + str(backgroundRadius) + ' sliding stack'); IJ.run(imp, 'Median...', 'radius=' + str(medianSmoothing)) IJ.run(imp, 'Auto Threshold', 'method=MaxEntropy white stack') # Remove small IJ.setForegroundColor(0, 0, 0); IJ.run(imp, 'ParticleRemoverPy ', 'enter=' + str(minimumCancerArea)); IJ.run(imp, "Close-", "stack") # Make sure black background binary is set! IJ.run(imp, "Options...", "iterations=1 count=1 black edm=Overwrite"); IJ.run(imp, 'Fill Holes', "stack") IJ.run(imp, 'Watershed', "stack") IJ.run(imp, 'ParticleRemoverPy ', 'enter=' + str(minimumCancerArea));
def batch_open_images(pathImage, pathRoi, pathMask, file_typeImage=None, name_filterImage=None, recursive=False): '''Open all files in the given folder. :param path: The path from were to open the images. String and java.io.File are allowed. :param file_type: Only accept files with the given extension (default: None). :param name_filter: Only accept files that contain the given string (default: None). :param recursive: Process directories recursively (default: False). ''' # Converting a File object to a string. if isinstance(pathImage, File): pathImage = pathImage.getAbsolutePath() def check_type(string): '''This function is used to check the file type. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the check on. ''' if file_typeImage: # The first branch is used if file_type is a list or a tuple. if isinstance(file_typeImage, (list, tuple)): for file_type_ in file_typeImage: if string.endswith(file_type_): # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if file_type is a string. elif isinstance(file_typeImage, string): if string.endswith(file_typeImage): return True else: return False return False # Accept all files if file_type is None. else: return True def check_filter(string): '''This function is used to check for a given filter. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the filtering on. ''' if name_filterImage: # The first branch is used if name_filter is a list or a tuple. if isinstance(name_filterImage, (list, tuple)): for name_filter_ in name_filterImage: if name_filter_ in string: # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if name_filter is a string. elif isinstance(name_filterImage, string): if name_filterImage in string: return True else: return False return False else: # Accept all files if name_filter is None. return True # We collect all files to open in a list. path_to_Image = [] # Replacing some abbreviations (e.g. $HOME on Linux). path = os.path.expanduser(pathImage) path = os.path.expandvars(pathImage) # If we don't want a recursive search, we can use os.listdir(). if not recursive: for file_name in os.listdir(pathImage): full_path = os.path.join(pathImage, file_name) if os.path.isfile(full_path): if check_type(file_name): if check_filter(file_name): path_to_Image.append(full_path) # For a recursive search os.walk() is used. else: # os.walk() is iterable. # Each iteration of the for loop processes a different directory. # the first return value represents the current directory. # The second return value is a list of included directories. # The third return value is a list of included files. for directory, dir_names, file_names in os.walk(pathImage): # We are only interested in files. for file_name in file_names: # The list contains only the file names. # The full path needs to be reconstructed. full_path = os.path.join(directory, file_name) # Both checks are performed to filter the files. if check_type(file_name): if check_filter(file_name) is False: # Add the file to the list of images to open. path_to_Image.append([full_path, os.path.basename(os.path.splitext(full_path)[0])]) # Create the list that will be returned by this function. Images = [] Rois = [] for img_path, file_name in path_to_Image: # IJ.openImage() returns an ImagePlus object or None. imp = IJ.openImage(img_path) print(img_path) if check_filter(file_name): continue; else: print(file_name , pathRoi) RoiName = str(pathRoi) + '/'+ file_name + '.roi' Roi = IJ.open(RoiName) # An object equals True and None equals False. rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.addRoi(Roi) impMask = IJ.createImage("Mask", "8-bit grayscale-mode", imp.getWidth(), imp.getHeight(), imp.getNChannels(), imp.getNSlices(), imp.getNFrames()) IJ.setForegroundColor(255, 255, 255) rm.runCommand(impMask,"Deselect") rm.runCommand(impMask,"Fill") rm.runCommand('Delete') IJ.saveAs(impMask, '.tif', str(pathMask) + "/" + file_name); imp.close(); #print(img_path, RoiName) Images.append(imp) Rois.append(Roi) return Images, Rois
gd.setCancelLabel("Quit") gd.setOKLabel("Define column") gd.addCheckbox("First segment is injury?",injuryfirst) gd.showDialog() if (gd.wasOKed()): roi = theImage.getRoi() if roi is None: IJ.error("No ROI selected") else: polygon = roi.getFloatPolygon() # if len(polygon.xpoints) % 2 == 0 and is_monotonic_increasing(polygon.ypoints): if is_monotonic_increasing(polygon.ypoints): xset = average(polygon.xpoints) IJ.setForegroundColor(255,255,0) IJ.run("Draw","stack") IJ.makeLine(xset,0,xset,theImage.getHeight()) IJ.setForegroundColor(0,255,255) IJ.run("Draw","stack") injuryfirst = gd.getNextBoolean() if injuryfirst: countidx = range(0,len(polygon.xpoints)-1,2) else: countidx = range(1,len(polygon.xpoints)-1,2) injuryLength = 0.0 for idx in countidx: injuryLength = injuryLength + (polygon.ypoints[idx+1]-polygon.ypoints[idx]) totalLength = polygon.ypoints[-1]-polygon.ypoints[0]
import re from ij import IJ from ij.io import Opener from ij.plugin import Concatenator from jarray import array import ij.gui.GenericDialog as GenericDialog import java.awt.Font as Font import java.awt.Color as Color import ij.plugin.Duplicator as dup import re from ij.io import TiffDecoder import time from ij.io import Opener import gc gc.collect() IJ.setForegroundColor(254, 254, 254); IJ.run("Line Width...", "line=14"); IJ.run("Collect Garbage"); #inputDir1 = IJ.getDirectory("Choose image directory! ") inputDir1 = "/home/mt/Downloads/1/" fileList1 = os.listdir(inputDir1); ###tilestring=getString("Which Tilescan", "1") RGB=os.path.join(inputDir1,'RGB.png') FileList=sorted(os.listdir(inputDir1)) print(FileList) stitchedFiles=[x for x in FileList if "stitched.TIF" in x] stitchedNames=[x.split('_')[0] for x in stitchedFiles] mergedFiles=[x for x in FileList if "merged.TIF" in x]
def track_cells(folder_w, filename, imp, correction): #imp = IJ.openImage(os.path.join(folder,filename)) #imp.show() #get image dimensions, set ROI remove part of flouresncent ring x_size = ImagePlus.getDimensions(imp)[0] y_size = ImagePlus.getDimensions(imp)[1] x_start = 0 y_start = 0 #calculate alternative ROI if crop_ring: x_start = 170 / 2 y_start = 170 / 2 x_size = x_size - 170 y_size = y_size - 170 print( str(x_start) + ", " + str(y_start) + ", " + str(x_size) + ", " + str(y_size)) imp.setRoi(OvalRoi(x_start, y_start, x_size, y_size)) #imp_dup = imp.duplicate() #imp_dup.show() #red_corrected_img.show() IJ.run(imp, "Make Inverse", "") IJ.setForegroundColor(0, 0, 0) IJ.run(imp, "Fill", "stack") imp.killRoi() #imp.show() #sys.exit() #img_filename = filename+"_corrected_red_stack.tif" #folder_filename= os.path.join(well_folder,img_filename) #IJ.save(imp, folder_filename) #---------------------------- # Create the model object now #---------------------------- # Some of the parameters we configure below need to have # a reference to the model at creation. So we create an # empty model now. model = Model() # Send all messages to ImageJ log window. model.setLogger(Logger.IJ_LOGGER) #------------------------ # Prepare settings object #------------------------ settings = Settings() settings.setFrom(imp) # Configure detector - We use the Strings for the keys settings.detectorFactory = LogDetectorFactory() settings.detectorSettings = { 'DO_SUBPIXEL_LOCALIZATION': SUBPIXEL_LOCALIZATION, 'RADIUS': RADIUS, 'TARGET_CHANNEL': TARGET_CHANNEL, 'THRESHOLD': THRESHOLD, 'DO_MEDIAN_FILTERING': MEDIAN_FILTERING, } # Configure spot filters - Classical filter on quality settings.initialSpotFilterValue = SPOT_FILTER settings.addSpotAnalyzerFactory(SpotIntensityAnalyzerFactory()) settings.addSpotAnalyzerFactory(SpotContrastAndSNRAnalyzerFactory()) settings.addSpotAnalyzerFactory(SpotMorphologyAnalyzerFactory()) settings.addSpotAnalyzerFactory(SpotRadiusEstimatorFactory()) filter1 = FeatureFilter('QUALITY', QUALITY, True) filter2 = FeatureFilter('CONTRAST', CONTRAST, True) filter2a = FeatureFilter('ESTIMATED_DIAMETER', MAX_ESTIMATED_DIAMETER, False) filter2b = FeatureFilter('MEDIAN_INTENSITY', MAX_MEDIAN_INTENSITY, False) settings.addSpotFilter(filter1) settings.addSpotFilter(filter2) settings.addSpotFilter(filter2a) settings.addSpotFilter(filter2b) print(settings.spotFilters) # Configure tracker - We want to allow merges and fusions settings.trackerFactory = SparseLAPTrackerFactory() settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap( ) # almost good enough ##adapted from https://forum.image.sc/t/trackmate-scripting-automatically-exporting-spots-in-tracks-links-in-tracks-tracks-statistics-and-branching-analysis-to-csv/6256 #linking settings settings.trackerSettings['LINKING_MAX_DISTANCE'] = LINKING_MAX_DISTANCE if LINKING_FEATURE_PENALTIES == True: settings.trackerSettings['LINKING_FEATURE_PENALTIES'] = { LINKING_FEATURE_PENALTIES_TYPE: LINKING_FEATURE_PENALTIES_VALUE } else: settings.trackerSettings['LINKING_FEATURE_PENALTIES'] = {} #gap closing settings settings.trackerSettings['ALLOW_GAP_CLOSING'] = ALLOW_GAP_CLOSING if ALLOW_GAP_CLOSING == True: settings.trackerSettings[ 'GAP_CLOSING_MAX_DISTANCE'] = GAP_CLOSING_MAX_DISTANCE settings.trackerSettings['MAX_FRAME_GAP'] = MAX_FRAME_GAP if GAP_CLOSING_FEATURE_PENALTIES == True: settings.trackerSettings['GAP_CLOSING_FEATURE_PENALTIES'] = { GAP_CLOSING_FEATURE_PENALTIES_TYPE: GAP_CLOSING_FEATURE_PENALTIES_VALUE } else: settings.trackerSettings['GAP_CLOSING_FEATURE_PENALTIES'] = {} #splitting settings settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = ALLOW_TRACK_SPLITTING if ALLOW_TRACK_SPLITTING == True: settings.trackerSettings[ 'SPLITTING_MAX_DISTANCE'] = SPLITTING_MAX_DISTANCE if SPLITTING_FEATURE_PENALTIES == True: settings.trackerSettings['SPLITTING_FEATURE_PENALTIES'] = { SPLITTING_FEATURE_PENALTIES_TYPE: SPLITTING_FEATURE_PENALTIES_VALUE } else: settings.trackerSettings['SPLITTING_FEATURE_PENALTIES'] = {} #merging settings settings.trackerSettings['ALLOW_TRACK_MERGING'] = ALLOW_TRACK_MERGING if ALLOW_TRACK_MERGING == True: settings.trackerSettings['MERGING_MAX_DISTANCE'] = MERGING_MAX_DISTANCE if MERGING_FEATURE_PENALTIES == True: settings.trackerSettings['MERGING_FEATURE_PENALTIES'] = { MERGING_FEATURE_PENALTIES_TYPE: MERGING_FEATURE_PENALTIES_VALUE } else: settings.trackerSettings['MERGING_FEATURE_PENALTIES'] = {} print(settings.trackerSettings) # Configure track analyzers - Later on we want to filter out tracks # based on their displacement, so we need to state that we want # track displacement to be calculated. By default, out of the GUI, # not features are calculated. # The displacement feature is provided by the TrackDurationAnalyzer. settings.addTrackAnalyzer(TrackDurationAnalyzer()) settings.addTrackAnalyzer(TrackSpotQualityFeatureAnalyzer()) # Configure track filters - We want to get rid of the two immobile spots at # the bottom right of the image. Track displacement must be above 10 pixels. filter3 = FeatureFilter('TRACK_DISPLACEMENT', TRACK_DISPLACEMENT, True) filter4 = FeatureFilter('TRACK_START', TRACK_START, False) #filter5 = FeatureFilter('TRACK_STOP', float(imp.getStack().getSize())-1.1, True) settings.addTrackFilter(filter3) settings.addTrackFilter(filter4) #settings.addTrackFilter(filter5) #------------------- # Instantiate plugin #------------------- trackmate = TrackMate(model, settings) #-------- # Process #-------- ok = trackmate.checkInput() if not ok: sys.exit(str(trackmate.getErrorMessage())) ok = trackmate.process() # if not ok: #sys.exit(str(trackmate.getErrorMessage())) #---------------- # Display results #---------------- #Set output folder and filename and create output folder well_folder = os.path.join(folder_w, filename) output_folder = os.path.join(well_folder, "Tracking") create_folder(output_folder) xml_file_name = filename + "_" + correction + "_trackmate_analysis.xml" folder_filename_xml = os.path.join(output_folder, xml_file_name) #ExportTracksToXML.export(model, settings, File(folder_filename_xml)) outfile = TmXmlWriter(File(folder_filename_xml)) outfile.appendSettings(settings) outfile.appendModel(model) outfile.writeToFile() # Echo results with the logger we set at start: #model.getLogger().log(str(model)) #create araray of timepoint length with filled 0 cell_counts = zerolistmaker(imp.getStack().getSize()) if ok: for id in model.getTrackModel().trackIDs(True): # Fetch the track feature from the feature model. track = model.getTrackModel().trackSpots(id) for spot in track: # Fetch spot features directly from spot. t = spot.getFeature('FRAME') print(t) cell_counts[int(t)] = cell_counts[int(t)] + 1 else: print("No spots detected!") if HEADLESS == False: selectionModel = SelectionModel(model) displayer = HyperStackDisplayer(model, selectionModel, imp) displayer.render() displayer.refresh() del imp return (cell_counts + [len(model.getTrackModel().trackIDs(True))])
from ij.text import TextWindow 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")
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
for i in range(1, n_slicesa + 1): imp.setSlice(i) n = imp.getProcessor().getPixels() n2 = [int(val) for val in n] L.append(n2) imp.changes = False imp.close() #get initial dictionary D and construct matrix imp2 = IJ.getImage() IJ.run("Enhance Contrast...", "saturated=0 normalize process_all use") IJ.run("Multiply...", "value=" + str(500) + " stack") #IJ.run("Add...", "value="+str(10)+" stack") n_slices = imp2.getStack().getSize() X = [] for i in range(1, n_slices + 1): imp2.setSlice(i) n = imp2.getProcessor().getPixels() n2 = [val for val in n] X.append(n2) IJ.newImage("Untitled", "RGB white", 512, 512, 1) IJ.run("Select All") IJ.setForegroundColor(bc, bc, bc) IJ.run("Fill", "slice") imp3 = IJ.getImage() for i in range(0, len(X[0])): IJ.makeRectangle(X[0][i] + 4, X[1][i] + 4, px, px) IJ.setForegroundColor(L[0][i], L[1][i], L[2][i]) IJ.run("Fill", "slice")
def generate_background_rois(input_mask_imp, params, membrane_edges, dilations=5, threshold_method=None, membrane_imp=None): """automatically identify background region based on auto-thresholded image, existing membrane edges and position of midpoint anchor""" if input_mask_imp is None and membrane_imp is not None: segmentation_imp = Duplicator().run(membrane_imp) # do thresholding using either previous method if threhsold_method is None or using (less conservative?) threshold method if (threshold_method is None or not (threshold_method in params.listThresholdMethods())): mask_imp = make_and_clean_binary(segmentation_imp, params.threshold_method) else: mask_imp = make_and_clean_binary(segmentation_imp, threshold_method) segmentation_imp.close() else: input_mask_imp.killRoi() mask_imp = Duplicator().run(input_mask_imp) rois = [] IJ.setForegroundColor(0, 0, 0) roim = RoiManager(True) rt = ResultsTable() for fridx in range(mask_imp.getNFrames()): mask_imp.setT(fridx + 1) # add extra bit to binary mask from loaded membrane in case user refined edges... # flip midpoint anchor across the line joining the two extremes of the membrane, # and fill in the triangle made by this new point and those extremes poly = membrane_edges[fridx].getPolygon() l1 = (poly.xpoints[0], poly.ypoints[0]) l2 = (poly.xpoints[-1], poly.ypoints[-1]) M = (0.5 * (l1[0] + l2[0]), 0.5 * (l1[1] + l2[1])) Mp1 = (params.manual_anchor_midpoint[0][0] - M[0], params.manual_anchor_midpoint[0][1] - M[1]) p2 = (M[0] - Mp1[0], M[1] - Mp1[1]) new_poly_x = list(poly.xpoints) new_poly_x.append(p2[0]) new_poly_y = list(poly.ypoints) new_poly_y.append(p2[1]) mask_imp.setRoi(PolygonRoi(new_poly_x, new_poly_y, PolygonRoi.POLYGON)) IJ.run(mask_imp, "Fill", "slice") mask_imp.killRoi() # now dilate the masked image and identify the unmasked region closest to the midpoint anchor ip = mask_imp.getProcessor() dilations = 5 for d in range(dilations): ip.dilate() ip.invert() mask_imp.setProcessor(ip) mxsz = mask_imp.getWidth() * mask_imp.getHeight() pa = ParticleAnalyzer( ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.SHOW_PROGRESS, ParticleAnalyzer.CENTROID, rt, 0, mxsz) pa.setRoiManager(roim) pa.analyze(mask_imp) ds_to_anchor = [ math.sqrt((x - params.manual_anchor_midpoint[0][0])**2 + (y - params.manual_anchor_midpoint[0][1])**2) for x, y in zip( rt.getColumn(rt.getColumnIndex("X")).tolist(), rt.getColumn(rt.getColumnIndex("Y")).tolist()) ] if len(ds_to_anchor) > 0: roi = roim.getRoi(ds_to_anchor.index(min(ds_to_anchor))) rois.append(roi) else: rois.append(None) roim.reset() rt.reset() roim.close() mask_imp.close() return rois
def save_membrane_edge_image(membrane_channel_imp, fixed_anchors_list, membrane_edges, area_rois, params): """Save an image with the membrane channel overlaid with original anchor positions, fixed anchor positions, and membrane edge""" IJ.run(membrane_channel_imp, "RGB Color", "") anchors = params.manual_anchor_positions midpoint = params.manual_anchor_midpoint[0] #print("membrane_edges = " + str(len(membrane_edges))); #print("membrane_channel_imp = " + str(membrane_channel_imp)); #print("fixed_anchors_list = " + str(len(fixed_anchors_list))); #print("area_rois = " + str(len(area_rois))); if fixed_anchors_list is None: fixed_anchors_list = [] # not pythonic, but never mind... for edge in membrane_edges: poly = edge.getPolygon() xs = poly.xpoints ys = poly.ypoints fixed_anchors_list.append([(xs[0], ys[0]), (xs[-1], ys[-1])]) try: for fridx in range(0, membrane_channel_imp.getNFrames()): membrane_channel_imp.setPosition(fridx + 1) membrane_channel_imp.setRoi(membrane_edges[fridx]) IJ.setForegroundColor(0, 255, 255) IJ.run(membrane_channel_imp, "Draw", "slice") membrane_channel_imp.setRoi(area_rois[fridx]) IJ.setForegroundColor(0, 255, 0) IJ.run(membrane_channel_imp, "Draw", "slice") for p in anchors: roi = PointRoi(p[0], p[1]) membrane_channel_imp.setRoi(roi) IJ.setForegroundColor(255, 0, 0) IJ.run(membrane_channel_imp, "Draw", "slice") roi = PointRoi(midpoint[0], midpoint[1]) membrane_channel_imp.setRoi(roi) IJ.setForegroundColor(255, 0, 0) IJ.run(membrane_channel_imp, "Draw", "slice") for p in fixed_anchors_list[fridx]: roi = PointRoi(p[0], p[1]) membrane_channel_imp.setRoi(roi) IJ.setForegroundColor(255, 255, 0) IJ.run(membrane_channel_imp, "Draw", "slice") # TODO: if coincidence between anchors and fixed anchors, or indeed with edge, consider # rendering in secondary colours (magenta = (255,0,255), orange = (255,200,0), green = (0,255,0)? except: pass FileSaver(membrane_channel_imp).saveAsTiff( os.path.join(params.output_path, "membrane identification check.tif")) IJ.setForegroundColor(255, 255, 255) #from ij import WindowManager as WM #import membrane_blebbing_fileio as mbio; #from ij.plugin import ChannelSplitter #folder = "D:\\data\\Inverse blebbing\\output\\2018-10-29 17-06-15 output"; #curvature_overlay = IJ.openImage(os.path.join(folder, "raw curvature.tif")); #curvature_profiles = mbio.load_csv_as_profile(os.path.join(folder, "curvatures.csv")); #imp = IJ.openImage("D:\\data\\Inverse blebbing\\MAX_2dpf marcksl1b-EGFP inj_TgLifeact-mCh_movie e4_split-bleb1.tif"); #intensity_channel_imp = ChannelSplitter.split(imp)[1]; #intensity_channel_imp.show(); #colormap_string = "physics" #generate_intensity_weighted_curvature(curvature_overlay, curvature_profiles, intensity_channel_imp, colormap_string);
def setForegroundColor(r, g, b): IJ.setForegroundColor(r, g, b)
gd = GenericDialog("?") gd.addChoice("Would you like to adjust this one?", ["No", "Yes"], "No") gd.showDialog() if gd.getNextChoice() == "Yes": imp2.close() IJ.run("Brightness/Contrast...") WaitForUserDialog("Title", "Adjust intensities").show() IJ.run("Stack to Images", "") IJ.run(imp, "Merge Channels...", "c2=Green c3=Blue c6=Magenta c7=Yellow create keep") imp = WindowManager.getCurrentImage() IJ.run(imp, "RGB Color", "") IJ.run(imp, "Images to Stack", "name=Stack title=[] use") #WaitForUserDialog("Title", "Now you should have a stack check it out ").show() imp = WindowManager.getCurrentImage() # the Stack imp.show() IJ.setForegroundColor(255, 255, 255) IJ.run( imp, "Make Montage...", "columns=5 rows=1 scale=0.5 borderWidth = 2 useForegroundColor = True" ) #WaitForUserDialog("Title", "Now we should have the montage").show() IJ.run( "Save", "save=" + outputDirectory + '/' + image.replace("stack", "newmontage")) IJ.run("Close All", "") print("Done!")
def doInBackground(self): try: # In case there is an error, so that FIJI doesn't crash print "INICIO" print self.files print self.pix_erosion_mult label_files = [f for f in self.files if f.endswith('_label.png') or f.endswith('_label.tif') or f.endswith('_label.jpg')] total_label_files = len(label_files) print "total label files:" print total_label_files gvars["total label files"] = total_label_files for filenum, f in enumerate(label_files): # Loop through the files in the directory self.label_update(filenum+1, total_label_files) label_file = f print "----" print label_file original_name = re.sub(r"_label.*", "",f) # get name of the original image without extension if (original_name+".tif") in self.files: # for an original image with extension .tif original_file = original_name+".tif" print original_file elif (original_name+".tiff") in self.files: # for an original image with extension .tiff (with double f) original_file = original_name+".tiff" print original_file else: # If there is no original image original_file = "None" print original_file path_multiple = gvars['path_multiple_image_directory'] print path_multiple ########### Section Label To Roi ########### RM = RoiManager() rm = RM.getRoiManager() label_image = IJ.openImage(path_multiple + "\\" + label_file) rm.reset() rm.runCommand(label_image,"Show All without labels") # we make sure we see the ROIs as they are loading imp2 = label_image.duplicate() ip = imp2.getProcessor() width = imp2.getWidth() height = imp2.getHeight() - 1 max_label = int(imp2.getStatistics().max) max_digits = int(math.ceil(math.log(max_label,10))) # Calculate the number of digits for the name of the ROI (padding with zeros) IJ.setForegroundColor(0, 0, 0) # We pick black color to delete the label already computed for j in range(height): for i in range(width): current_pixel_value = ip.getValue(i,j) if current_pixel_value > 0: IJ.doWand(imp2, i, j, 0.0, "Legacy smooth"); # We add this ROI to the ROI manager roi = imp2.getRoi() roi.setName(str(int(current_pixel_value)).zfill(max_digits)) rm.addRoi(roi) ip.fill(roi) # Much faster than IJ.run(imp2, "Fill", .... # Update ProgressBar progress = int((current_pixel_value / max_label) * 100) self.super__setProgress(progress) rm.runCommand(label_image,"Sort") # Sort the ROIs in the ROI manager rm.runCommand(label_image,"Show All without labels") ######### Section ROI erotion ######### for i in range(0, rm.getCount()): roi = rm.getRoi(i) new_roi = RoiEnlarger.enlarge(roi, -self.pix_erosion_mult) # Important to use this instead of the IJ.run("Enlarge... much faster!! rm.setRoi(new_roi,i) ####### Section Save ROIs ############## print original_name path_to_multiple_ROIs = str(gvars['path_multiple_image_directory']) + "\\" + original_name + "_Erosion_" +str(self.pix_erosion_mult)+ "px_" + "RoiSet.zip" print path_to_multiple_ROIs rm.runCommand("Save", path_to_multiple_ROIs) print("ROIs saved") ####### Section open Original Image ############## if original_file != "None": # If there is an original image file besides the label image, we'll measure and generate table of measurements print "There is an original image associated to this label" original_image = IJ.openImage(path_multiple + "\\" + original_file) IJ.run(original_image, "Enhance Contrast", "saturated=0.35") rm.runCommand(original_image,"Show All without labels") #original_image.show() table_message = [] is_scaled = original_image.getCalibration().scaled() if is_scaled: spatial_cal = "True" else: spatial_cal = "False" nChannels = original_image.getNChannels() print "Total channels:" print nChannels for current_channel in range(1,nChannels+1): print "Current channel:" print current_channel original_image.setSlice(current_channel) current_slice = str(original_image.getCurrentSlice()) #Get current slice for saving into filename print "Current slice:" print current_slice IJ.run("Clear Results", "") rm.runCommand(original_image,"Select All"); rm.runCommand(original_image,"Measure") table = ResultsTable.getResultsTable().clone() IJ.selectWindow("Results") IJ.run("Close") for i in range(0, table.size()): table.setValue('File', i, str(original_name)) table.setValue('Channel', i, current_channel) table.setValue('Pixels_eroded', i, str(self.pix_erosion_mult)) table.setValue('Spatial_calibration', i, spatial_cal) table.show("Tabla actualizada") path_to_multiple_Tables = str(gvars['path_multiple_image_directory']) + "\\" + original_name + "_Erosion_" +str(self.pix_erosion_mult)+ "px_Channel_" + str(current_channel) + ".csv" IJ.saveAs("Results", path_to_multiple_Tables) # Section Save jpg with outlines path_to_multiple_outline = str(gvars['path_multiple_image_directory']) + "\\" + original_name + "_Erosion_" +str(self.pix_erosion_mult)+ "px_" + "Outlines.jpg" outlines_image = original_image.flatten() IJ.saveAs(outlines_image, "JPG", path_to_multiple_outline) IJ.run("Close") else: print "There is NOT an original image associated to this label" label_image.close() ####### Section ending ############## except Exception as e: print e