def main(): #opens the image and gets its name # imp = open_test_img() # imp.show() imp = IJ.getImage() title = imp.getTitle() basename, extension = splitext(title) # does a minimum projection and makes a mask imp_min = ZProjector.run(imp, 'min') ip = imp_min.getProcessor() ip.setThreshold(1, 9999999999, 1) mask = ip.createMask() mask = ImagePlus("mask", mask) # fills in the holes in the mask IJ.run(mask, "Invert", "") IJ.run(mask, "Fill Holes", "") IJ.run(mask, "Invert", "") # converts to list and then finds the crop coordinates px = mask.getProcessor().getPixels() px = [-int(_) for _ in px] #for some reason the 1s are -1 here px = reshape(px, (imp.height, imp.width)) crop_top_left, crop_width, crop_height = find_largest_rectangle_2D(px) # crops the original image imp.setRoi(crop_top_left[0], crop_top_left[1], crop_width, crop_height) imp_cropped = imp.resize(crop_width, crop_height, "bilinear") imp_cropped.setTitle(basename + "_autocrop" + extension) imp_cropped.show()
def perform_cropping(imp, info, output_folder, default_path): imp.show() imp.setC(info.get_mosaic_labeled_ch()) IJ.run("Enhance Contrast", "saturated=0.35") zcrop_imp, z_lims = z_crop(imp) info.set_z_crop_frames(z_lims) info.set_mosaic_labeled_ch(imp.getC()) IJ.setTool("rect") zcrop_imp.hide() imp2 = ZProjector.run(zcrop_imp, "max") imp2.show() imp2.setC(info.get_mosaic_labeled_ch()) crop_roi = None while crop_roi is None: WaitForUserDialog("Select XY region to crop...").show() crop_roi = imp2.getRoi() if crop_roi.getType(): info.set_xy_crop_rect( str([(x, y) for x, y in zip(crop_roi.getPolygon().xpoints, crop_roi.getPolygon().ypoints)])) else: info.set_xy_crop_rect(crop_roi.getBounds().toString()) imp2.close() zcrop_imp.show() zcrop_imp.setRoi(crop_roi) IJ.run("Crop", "") if crop_roi.getType(): IJ.run(zcrop_imp, "Make Inverse", "") inv_roi = zcrop_imp.getRoi() IJ.run(zcrop_imp, "Set...", "value=0 stack") IJ.run(zcrop_imp, "Make Inverse", "") # zcrop_imp = z_crop_finetune(zcrop_imp, info); return imp, zcrop_imp, info, info.get_input_file_path()
def images_to_frames_stack(imgdir, savestack=False): ''' Method for preparing a stack of frames using images inside the input folder. When savestack is true it saves the resulting stack to the images folder while opening the stack. ''' title = "tracing_stack.tiff" # Title of the final image stack. imgdir = imgdir.getPath() imglist = buildList(imgdir, ext) if not imglist: raise IOError("No {0} were found in {0}.".format(ext, imgdir)) method = "max" implist = [] for img in imglist: imp = ImagePlus(img) if imp.isStack(): imp = ZProjector.run(imp, method) implist.append(imp) stack = ImageStack( implist[0].getWidth(), implist[0].getHeight()) [stack.addSlice(img.getProcessor()) for img in implist] stackimp = ImagePlus(title, stack) IJ.run(stackimp, "Properties...", "slices=1 frames={0}".format(stackimp.getStackSize())) if savestack: IJ.log("# Saving tracing stack...") save_string = os.path.join(imgdir, title) fs = ThreadedFileSaver.ThreadedFileSaver(stackimp, save_string, "saveAsTiff") fs.start() stackimp.show()
def stackprocessor(path, nChannels=4, nSlices=1, nFrames=1): imp = ImagePlus(path) imp = HyperStackConverter().toHyperStack(imp, nChannels, # channels nSlices, # slices nFrames) # frames imp = ZProjector.run(imp, "max") return imp
def create_and_save(imp, projections, path, filename, export_format): """Wrapper to create one or more projections and export the results. Parameters ---------- imp : ij.ImagePlus The image stack to create the projections from. projections : list(str) A list of projection types to be done, valid options are 'Average', 'Maximum' and 'Sum'. path : str The path to store the results in. Existing files will be overwritten. filename : str The original file name to derive the results name from. export_format : str The suffix to be given to Bio-Formats, determining the storage format. Returns ------- bool True in case projections were created, False otherwise (e.g. if the given ImagePlus is not a Z-stack). """ if not projections: log.debug("No projection type requested, skipping...") return False if imp.getDimensions()[3] < 2: log.error("ImagePlus is not a z-stack, not creating any projections!") return False command = { "Average": "avg", "Maximum": "max", "Sum": "sum", } for projection in projections: log.debug("Creating '%s' projection...", projection) proj = ZProjector.run(imp, command[projection]) export_using_orig_name( proj, path, filename, "-%s" % command[projection], export_format, overwrite=True, ) proj.close() return True
def average(imp): """Create an average intensity projection. Parameters ---------- imp : ij.ImagePlus The input stack to be projected. Returns ------- ij.ImagePlus The result of the projection. """ if imp.getDimensions()[3] < 2: log.warn("ImagePlus is not a z-stack, not creating a projection!") return imp log.debug("Creating average projection...") proj = ZProjector.run(imp, "avg") return proj
def extract_frame_process_roi(imp, frame, channel, process, background, roi, z_min, z_max, correct_only_xy): # extract frame and channel imp_frame = ImagePlus("", extract_frame(imp, frame, channel, z_min, z_max)).duplicate() # check for roi and crop if roi != None: #print roi.getBounds() imp_frame.setRoi(roi) IJ.run(imp_frame, "Crop", "") # subtract background if background > 0: #IJ.log("Subtracting "+str(background)); IJ.run(imp_frame, "Subtract...", "value="+str(background)+" stack"); # enhance edges if process: IJ.run(imp_frame, "Mean 3D...", "x=1 y=1 z=0"); IJ.run(imp_frame, "Find Edges", "stack"); # project into 2D if imp_frame.getNSlices() > 1: if correct_only_xy: imp_frame = ZProjector.run( imp_frame, "avg"); # return return imp_frame
def extract_frame_process_roi(imp, frame, roi, options): # extract frame and channel imp_frame = ImagePlus("", extract_frame(imp, frame, options['channel'], options['z_min'], options['z_max'])).duplicate() # check for roi and crop if roi != None: #print roi.getBounds() imp_frame.setRoi(roi) IJ.run(imp_frame, "Crop", "") # subtract background if options['background'] > 0: #IJ.log("Subtracting "+str(background)); IJ.run(imp_frame, "Subtract...", "value="+str(options['background'])+" stack"); # enhance edges if options['process']: IJ.run(imp_frame, "Mean 3D...", "x=1 y=1 z=0"); IJ.run(imp_frame, "Find Edges", "stack"); # project into 2D if we only want to correct the drift in x and y if imp_frame.getNSlices() > 1: if options['correct_only_xy']: imp_frame = ZProjector.run(imp_frame, "avg"); # return return imp_frame
def main(): root = myDir.getPath() # get the root out the java file object print(root) import os, glob # set up bioformats from loci.plugins import BF from loci.plugins.in import ImporterOptions options = ImporterOptions() options.setColorMode(ImporterOptions.COLOR_MODE_COMPOSITE) options.setGroupFiles(True) # if the files are named logically if will group them into a stack # this will do the maximum intensity projection from ij.plugin import ZProjector Zproj = ZProjector() for path, subdirs, files in os.walk(root): print(path) # just get the one of the files that matches your image pattern flist = glob.glob(os.path.join(path,"*.tif")) print(len(flist)) if( flist ): file = flist[0] print("Processing {}".format(file)) options.setId(file) imp = BF.openImagePlus(options)[0] # show the image if you want to see it IJ.run(imp, "Grays", "") imp.show() imp_max = Zproj.run(imp,'max') IJ.run(imp_max, "Grays", "") imp_max.show() # save the Z projection IJ.save(imp_max,file.rsplit('_',1)[0]+'_processed.tif')
def doprojection(self, title, onGPU=False): ''' Run ij.plugin.Zprojector on image referenced by title using self.method as projection method and saves the projection on self.savefolder. ''' IJ.log("# Processing {0}...".format(title)) imp = self.load_image(title) if onGPU: projection = self.CLIJ2_max_projection(imp) else: projection = ZProjector.run(imp, self.method) if self.savefolder: save_string = os.path.join(self.savefolder, title) try: ij.io.FileSaver(projection).saveAsTiff(save_string) IJ.log("{0}".format(save_string)) except: IJ.log( "ij.io.FileSaver raised an exception while trying to save img '{0}' as '{1}'.Skipping image." .format(title, save_string)) else: imp.close() projection.show()
def main(): check_dependencies() # setup Prefs.blackBackground = True params = Parameters() params.load_last_params() # select folders if params.last_input_path is not None: DirectoryChooser.setDefaultDirectory(params.last_input_path) dc = DirectoryChooser("Choose root folder containing data for analysis") input_folder = dc.getDirectory() params.last_input_path = input_folder if input_folder is None: print("Run canceled") return if params.last_output_path is not None: DirectoryChooser.setDefaultDirectory( os.path.dirname(params.last_output_path)) dc = DirectoryChooser("choose location to save output") output_folder = dc.getDirectory() if output_folder is None: print("Run canceled") return timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S') output_folder = os.path.join(output_folder, (timestamp + ' output')) params.last_output_path = output_folder os.mkdir(output_folder) analysis_mode, threshold_method, minimum_cell_area_um2 = choose_analysis_mode( params) if analysis_mode is None: print("Run canceled") return params.last_analysis_mode = analysis_mode do_manual_qc = "+ manual correction" in analysis_mode params.last_threshold_method = threshold_method params.last_minimum_cell_area_um2 = minimum_cell_area_um2 params.persist_parameters() # load image(s): files_lst = [ f for f in os.listdir(input_folder) if os.path.splitext(f)[1] == '.tif' ] out_statses = [] for f in files_lst: print("Working on image {}...".format(os.path.splitext(f)[0])) imp = IJ.openImage(os.path.join(input_folder, f)) metadata = import_iq3_metadata( os.path.join(input_folder, os.path.splitext(f)[0] + '.txt')) n_channels = int(metadata['n_channels']) gfp_channel_number = [ ("488" in ch) for ch in metadata['channel_list'] ].index(True) + 1 if any( [("488" in ch) for ch in metadata['channel_list']]) else None dapi_channel_number = [ ("405" in ch) for ch in metadata['channel_list'] ].index(True) + 1 if any( [("405" in ch) for ch in metadata['channel_list']]) else None red_channel_number = [ ("561" in ch) for ch in metadata['channel_list'] ].index(True) + 1 if any( [("561" in ch) for ch in metadata['channel_list']]) else None imp = HyperStackConverter.toHyperStack(imp, n_channels, imp.getNSlices() // n_channels, 1, "Color") imp = ZProjector.run(imp, "max") if dapi_channel_number is not None: imp.setC(dapi_channel_number) IJ.run(imp, "Blue", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") else: raise NotImplementedError( "Nuclear staining channel doesn't seem to exist!") if red_channel_number is not None: imp.setC(red_channel_number) IJ.run(imp, "Red", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") if gfp_channel_number is not None: imp.setC(gfp_channel_number) IJ.run(imp, "Green", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") imp.setC(gfp_channel_number) imp.show() imp.setDisplayMode(IJ.COMPOSITE) cal = imp.getCalibration() cal.setUnit(metadata["y_unit"]) cal.pixelWidth = metadata["x_physical_size"] cal.pixelHeight = metadata["y_physical_size"] imp.setCalibration(cal) min_size_pix = minimum_cell_area_um2 / (cal.pixelHeight * cal.pixelWidth) if "GFP intensity" in analysis_mode: out_stats = gfp_analysis(imp, f, output_folder, gfp_channel_number=gfp_channel_number, dapi_channel_number=dapi_channel_number, threshold_method=threshold_method, do_manual_qc=do_manual_qc, min_size_pix=min_size_pix) elif analysis_mode == "Manual": important_channel = gfp_channel_number if gfp_channel_number is not None else dapi_channel_number out_stats = manual_analysis( imp, f, output_folder, gfp_channel_number=gfp_channel_number, dapi_channel_number=dapi_channel_number, important_channel=important_channel) elif "E-cadherin watershed" in analysis_mode: out_stats = ecad_analysis(imp, f, output_folder, gfp_channel_number=gfp_channel_number, red_channel_number=red_channel_number, dapi_channel_number=dapi_channel_number, do_manual_qc=do_manual_qc) imp.close() out_statses.extend(out_stats) print("Current total number of cells identified: {}".format( len(out_statses))) # get # nuclei per "cell" params.save_parameters_to_json( os.path.join(output_folder, "parameters used.json")) WaitForUserDialog( "Done", "Done, having analysed {} cells in total!".format( len(out_statses))).show() return
def main(): # Prepare directory tree for output. indir = IJ.getDirectory("input directory") outdir = IJ.getDirectory(".csv output directory") c1dir = os.path.join(outdir, "Channel1") c2dir = os.path.join(outdir, "Channel2") c3dir = os.path.join(outdir, "Channel3") c4dir = os.path.join(outdir, "Channel4") channelsdir = os.path.join(outdir, "Channels") if not os.path.isdir(c1dir): os.mkdir(c1dir) if not os.path.isdir(c2dir): os.mkdir(c2dir) if not os.path.isdir(c3dir): os.mkdir(c3dir) if not os.path.isdir(c4dir): os.mkdir(c4dir) if not os.path.isdir(channelsdir): os.mkdir(channelsdir) # Collect all file paths in the input directory files = readdirfiles(indir) # Initialize the results tables. c1Results = ResultsTable() c2Results = ResultsTable() c3Results = ResultsTable() c4Results = ResultsTable() for file in files: IJ.log("File: {}/{}".format(files.index(file) + 1, len(files))) if file.endswith('.tif'): # Open .tiff file as ImagePlus. imp = Opener().openImage(file) imp = ZProjector.run(imp, "max") # imp = stackprocessor(file, # nChannels=4, # nSlices=7, # nFrames=1) channels = ChannelSplitter.split(imp) name = imp.getTitle() # For every channel, save the inverted channel in grayscale as .jpg. for channel in channels: IJ.run(channel, "Grays", "") IJ.run(channel, "Invert", "") jpgname = channel.getShortTitle() jpgoutfile = os.path.join(channelsdir, "{}.jpg".format(jpgname)) IJ.saveAs(channel.flatten(), "Jpeg", jpgoutfile) IJ.run(channel, "Invert", "") # OPTIONAL - Perform any other operations (e.g. crossexcitation compensation tasks) before object count. c2name = channels[2].getTitle() cal = channels[2].getCalibration() channels[2] = ImagePlus( c2name, ImageCalculator().run("divide create 32-bit", channels[2], channels[3]).getProcessor( ) # This removes AF647 bleed-through ) channels[2].setCalibration(cal) # Settings for channel1 threshold. c1 = countobjects(channels[0], c1Results, threshMethod="Triangle", subtractBackground=True, watershed=True, minSize=0.00, maxSize=100, minCirc=0.00, maxCirc=1.00) # Settings for channel2 threshold. c2 = countobjects(channels[1], c2Results, threshMethod="RenyiEntropy", subtractBackground=True, watershed=False, minSize=0.00, maxSize=30.00, minCirc=0.00, maxCirc=1.00) # Settings for channel3 threshold. c3 = countobjects(channels[2], c3Results, threshMethod="RenyiEntropy", subtractBackground=True, watershed=False, minSize=0.00, maxSize=30.00, minCirc=0.00, maxCirc=1.00) # Settings for channel4 threshold. c4 = countobjects(channels[3], c4Results, threshMethod="RenyiEntropy", subtractBackground=True, watershed=False, minSize=0.20, maxSize=100.00, minCirc=0.00, maxCirc=1.00) # Format filenames for thresholded .tiff files. outfileC1 = os.path.join(c1dir, "threshold_c1_{}".format(name)) outfileC2 = os.path.join(c2dir, "threshold_c2_{}".format(name)) outfileC3 = os.path.join(c3dir, "threshold_c3_{}".format(name)) outfileC4 = os.path.join(c4dir, "threshold_c4_{}".format(name)) # Save thresholded .tiff files. IJ.saveAs(c1.flatten(), "Tiff", outfileC1) IJ.saveAs(c2.flatten(), "Tiff", outfileC2) IJ.saveAs(c3.flatten(), "Tiff", outfileC3) IJ.saveAs(c4.flatten(), "Tiff", outfileC4) # Show results tables. # c1Results.show("channel1") # c2Results.show("channel2") # c3Results.show("channel3") # c4Results.show("channel4") # Prepare results table filenames. c1out = os.path.join(outdir, "channel1.csv") c2out = os.path.join(outdir, "channel2.csv") c3out = os.path.join(outdir, "channel3.csv") c4out = os.path.join(outdir, "channel4.csv") # Save results tables. ResultsTable.save(c1Results, c1out) ResultsTable.save(c2Results, c2out) ResultsTable.save(c3Results, c3out) ResultsTable.save(c4Results, c4out)
# manual roi copied from z-projected version of this resliced image (add roi from z-proj to ROI manager, then add # to resliced image) imp.killRoi(); IJ.run(imp, "Reslice [/]...", "output=1.000 start=Top avoid"); rot_imp = IJ.getImage(); crop_roi = Roi(10, 0, rot_imp.getWidth()-20, rot_imp.getHeight()); rot_imp.setRoi(crop_roi); rot_imp.crop(); rot_imp.show(); WaitForUserDialog("pause").show(); split_ch = ChannelSplitter().split(rot_imp); mch_imp = split_ch[0]; egfp_imp = split_ch[1]; roi_imp = split_ch[2]; zproj_imp = ZProjector.run(roi_imp, "max"); IJ.setRawThreshold(zproj_imp, 33153, 65535, None); IJ.run(zproj_imp, "Make Binary", "") zproj_imp.show(); raise error; IJ.run(zproj_imp, "Skeletonize", ""); IJ.run(zproj_imp, "Create Selection", ""); roi = zproj_imp.getRoi(); floatpoly = roi.getContainedFloatPoints(); roi = PolygonRoi(floatpoly, Roi.FREELINE); zproj_imp.setRoi(roi); WaitForUserDialog("pause").show(); #IJ.setTool("freeline"); #WaitForUserDialog("Draw a line").show(); #IJ.run(zproj_imp, "Fit Spline", "");
def main(): # setup Prefs.blackBackground = True params = Parameters() params.load_last_params() # select folders if params.last_input_path is not None: DirectoryChooser.setDefaultDirectory(params.last_input_path) dc = DirectoryChooser("Choose root folder containing data for analysis") input_folder = dc.getDirectory() params.last_input_path = input_folder if input_folder is None: raise KeyboardInterrupt("Run canceled") if params.last_output_path is not None: DirectoryChooser.setDefaultDirectory( os.path.dirname(params.last_output_path)) dc = DirectoryChooser("choose location to save output") output_folder = dc.getDirectory() timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S') output_folder = os.path.join(output_folder, (timestamp + ' output')) params.last_output_path = output_folder os.mkdir(output_folder) analysis_mode = choose_analysis_mode(params) params.last_analysis_mode = analysis_mode params.persist_parameters() # load image(s): files_lst = [ f for f in os.listdir(input_folder) if os.path.splitext(f)[1] == '.tif' ] out_statses = [] for f in files_lst: print("Working on image {}...".format(os.path.splitext(f)[0])) imp = IJ.openImage(os.path.join(input_folder, f)) metadata = import_iq3_metadata( os.path.join(input_folder, os.path.splitext(f)[0] + '.txt')) imp = HyperStackConverter.toHyperStack(imp, 3, imp.getNSlices() // 3, 1, "Color") imp = ZProjector.run(imp, "max") imp.setC(3) IJ.run(imp, "Blue", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") imp.setC(2) IJ.run(imp, "Red", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") imp.setC(1) IJ.run(imp, "Green", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") imp.show() imp.setDisplayMode(IJ.COMPOSITE) cal = imp.getCalibration() cal.setUnit(metadata["y_unit"]) cal.pixelWidth = metadata["x_physical_size"] cal.pixelHeight = metadata["y_physical_size"] imp.setCalibration(cal) if analysis_mode == "GFP intensity": out_stats = gfp_analysis(imp, f, output_folder) elif analysis_mode == "Manual": out_stats = manual_analysis(imp, f, output_folder) out_statses.extend(out_stats) print("Current total number of cells identified: {}".format( len(out_statses))) # get # nuclei per "cell" params.save_parameters_to_json( os.path.join(output_folder, "parameters used.json")) WaitForUserDialog( "Done", "Done, having analysed {} cells in total!".format( len(out_statses))).show() return
def make_projection(imp, method, slices): z_prjor = ZProjector(imp) prj_imp = z_prjor.run(imp, method, slices[0], slices[1]) return prj_imp
def project(img, method): zp = ZProjector.run(img, method) return zp
def run(): IJ.run("Close All", "") IJ.log("\\Clear") IJ.log("Find_close_peaks") imp = IJ.run("Bio-Formats Importer") imp = IJ.getImage() Channel_1, Channel_2, radius_background, sigmaSmaller, sigmaLarger, minPeakValue, min_dist = getOptions() IJ.log("option used:" \ + "\n" + "channel 1:" + str(Channel_1) \ + "\n" + "channel 2:"+ str(Channel_2) \ + "\n" + "Radius Background:"+ str(radius_background) \ + "\n" + "Smaller Sigma:"+ str(sigmaSmaller) \ + "\n" + "Larger Sigma:"+str(sigmaLarger) \ + "\n" + "Min Peak Value:"+str(minPeakValue) \ + "\n" + "Min dist between peaks:"+str(min_dist)) IJ.log("Computing Max Intensity Projection") if imp.getDimensions()[3] > 1: imp_max = ZProjector.run(imp,"max") #imp_max = IJ.run("Z Project...", "projection=[Max Intensity]") #imp_max = IJ.getImage() else: imp_max = imp ip1, ip2 = extract_channel(imp_max, Channel_1, Channel_2) imp1, imp2 = back_substraction(ip1, ip2, radius_background) imp1.show() imp2.show() IJ.log("Finding Peaks") ip1_1, ip2_1, peaks_1, peaks_2 = find_peaks(imp1, imp2, sigmaSmaller, sigmaLarger, minPeakValue) # Create a PointRoi from the DoG peaks, for visualization roi_1 = PointRoi(0, 0) roi_2 = PointRoi(0, 0) roi_3 = PointRoi(0, 0) roi_4 = PointRoi(0, 0) # A temporary array of integers, one per dimension the image has p_1 = zeros(ip1_1.numDimensions(), 'i') p_2 = zeros(ip2_1.numDimensions(), 'i') # Load every peak as a point in the PointRoi for peak in peaks_1: # Read peak coordinates into an array of integers peak.localize(p_1) roi_1.addPoint(imp1, p_1[0], p_1[1]) for peak in peaks_2: # Read peak coordinates into an array of integers peak.localize(p_2) roi_2.addPoint(imp2, p_2[0], p_2[1]) # Chose minimum distance in pixel #min_dist = 20 for peak_1 in peaks_1: peak_1.localize(p_1) for peak_2 in peaks_2: peak_2.localize(p_2) d1 = distance(p_1, p_2) if d1 < min_dist: roi_3.addPoint(imp1, p_2[0], p_2[1]) break for peak_2 in peaks_2: peak_2.localize(p_2) for peak_1 in peaks_1: peak_1.localize(p_1) d2 = distance(p_2, p_1) if d2 < min_dist: roi_4.addPoint(imp1, p_2[0], p_2[1]) break rm = RoiManager.getInstance() if not rm: rm = RoiManager() rm.reset() rm.addRoi(roi_1) rm.addRoi(roi_2) rm.addRoi(roi_3) rm.addRoi(roi_4) rm.select(0) rm.rename(0, "ROI neuron") rm.runCommand("Set Color", "yellow") rm.select(1) rm.rename(1, "ROI glioma") rm.runCommand("Set Color", "blue") rm.select(2) rm.rename(2, "ROI glioma touching neurons") rm.runCommand("Set Color", "red") rm.select(3) rm.rename(3, "ROI neurons touching glioma") rm.runCommand("Set Color", "green") rm.runCommand(imp1, "Show All") #Change distance to be in um cal = imp.getCalibration() min_distance = str(round((cal.pixelWidth * min_dist),1)) table = ResultsTable() table.incrementCounter() table.addValue("Numbers of Neuron Markers", roi_1.getCount(0)) table.addValue("Numbers of Glioma Markers", roi_2.getCount(0)) table.addValue("Numbers of Glioma within %s um of Neurons" %(min_distance), roi_3.getCount(0)) table.addValue("Numbers of Neurons within %s um of Glioma" %(min_distance), roi_4.getCount(0)) table.show("Results Analysis")
stack.size() + 1): #loop over all images in the stack if i < 20: ip = stack.getProcessor(i) avgI.append(ip.getStats().mean) #get average intensity else: avgI.append(0) if len(avgI) == dims[3]: apicalZ = avgI.index( max(avgI)) #get position of apical surface if apicalZ == False: print('Selecting default apical slice...') apicalZ = 9 #Get apical average projection of apical surface and find cell positions try: apical_detect_imp = zp.run(detect_imp, 'avg', apicalZ - 4, apicalZ + 4) apical_measure_imp = zp.run(measure_imp, 'avg', apicalZ - 4, apicalZ + 4) except: print('Projecting full apical part of stack...') apical_detect_imp = zp.run(detect_imp, 'avg', 5, stack.size()) apical_measure_imp = zp.run(measure_imp, 'avg', 5, stack.size()) apical_detect_imp.show() measured.reset() IJ.run("Find Maxima...", "noise=" + str(noise_threshold) + " output=List exclude") measured = rt.getResultsTable() centroidX = measured.getColumn(measured.getColumnIndex('X')) centroidY = measured.getColumn(measured.getColumnIndex('Y')) print 'Detected ' + str(len(centroidX)) + ' cells'
name = imp.getTitle() width = imp.width height = imp.height num_slices = imp.getNSlices() num_channels = imp.getNChannels() num_frames = imp.getNFrames() max_cycle_length = int(max_cycle_length) assert width_sub < width and width_sub < height, "Size of square must be less than dimensions of movie" assert num_channels == 1, "Image can only have one channel" #imp = process.ImageConverter.convertToGray32(original_imp) avg_img = ZProjector.run(imp,"avg"); avg_img.show() imp2 = ImageCalculator().run("Subtract create stack", imp, avg_img) imp2.show() #WindowManager.getImage("AVG_Pos0") num_window_x = int(round(width/width_sub)) #int(width-width_sub+1) num_window_y = int(round(height/width_sub)) #int(height-width_sub+1) center_px = int(round(width_sub/2)) new_rois = [] for i in range(0,num_window_x): for j in range(0,num_window_y): new_roi = Roi(i*width_sub, j*width_sub, width_sub, width_sub) new_rois.append(new_roi)
def main(): # ensure consistent preference settings Prefs.blackBackground = False; # get locations for previous and new outputs params = Parameters(); params.loadLastParams(); output_folder_old, output_folder = mbio.rerun_location_chooser(params.input_image_path); params.loadParametersFromJson(os.path.join(output_folder_old, 'parameters used.json')); params.setOutputPath(output_folder); # get original image file (for overlays etc.) if not os.path.isfile(params.input_image_path): mbui.warning_dialog(["The original data can't be found at the location specified in saved parameters. ", "(Possibly something as simple as a change in network drive mapping has occurred)", "Please specify the location of the original image file..."]); params.setInputImagePath(mbio.input_file_location_chooser(params.output_path)); import_opts, params = mbui.choose_series(params.input_image_path, params); imps = bf.openImagePlus(import_opts); imp = imps[0]; if imp.getNSlices() > 1: mbui.warning_dialog(["More than one Z plane detected.", "I will do a maximum projection before proceeding", "Continue?"]); imp = ZProjector.run(imp,"max all"); # prompt user to select ROI original_imp = Duplicator().run(imp); _, crop_params = mbui.crop_to_ROI(imp, params); imp.show(); if crop_params is not None: params.perform_spatial_crop = True; mbui.autoset_zoom(imp); imp.updateAndDraw(); review_crop = mb.check_cropping(output_folder_old, params); keep_crop = not review_crop; if review_crop: keep_crop = mbui.crop_review(); if not keep_crop: imp.changes = False; imp.close(); imp = original_imp; else: original_imp.close(); else: original_imp.close(); # prompt user to do time cropping imp, start_end_tuple = mbui.time_crop(imp, params); params.setTimeCropStartEnd(start_end_tuple); params = mbio.get_metadata(params); params.setCurvatureLengthUm(round(params.curvature_length_um / params.pixel_physical_size) * params.pixel_physical_size); params.persistParameters(); IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel"); imp.show(); if imp.getNChannels() > 1: imp.setPosition(params.membrane_channel_number, 1, 1); mbui.autoset_zoom(imp); IJ.run("Enhance Contrast", "saturated=0.35"); split_channels = mbfs.split_image_plus(imp, params); membrane_test_channel_imp = Duplicator().run(split_channels[0]); segmentation_channel_imp = split_channels[-1]; # import edges imp.hide(); membrane_edges = mbio.load_qcd_edges2(os.path.join(output_folder_old, "user_defined_edges.zip")); dummy_anchors = [params.manual_anchor_positions for _ in membrane_edges] membrane_edges, fixed_anchors = mbui.perform_user_qc(membrane_test_channel_imp, membrane_edges, membrane_edges, dummy_anchors, params); imp.show(); rgbstack = ImageStack(imp.getWidth(), imp.getHeight()); for tidx in range(imp.getNFrames()): imp.setT(tidx+1); ip = imp.getProcessor(); rgbip = ip.convertToRGB(); rgbstack.addSlice(rgbip); rgbimp = ImagePlus(("RGB " + imp.getTitle()), rgbstack); imp.close(); rgbimp.show(); IJ.run("Colors...", "foreground=yellow background=white selection=yellow"); for tidx in range(rgbimp.getNSlices()): rgbimp.setSlice(tidx+1); rgbimp.setRoi(membrane_edges[tidx]); IJ.run(rgbimp, "Draw", "slice"); IJ.run("Colors...", "foreground=red background=white selection=yellow"); for tidx in range(rgbimp.getNSlices()): rgbimp.setSlice(tidx+1); for anchor in params.manual_anchor_positions: rgbimp.setRoi(PointRoi(anchor[0], anchor[1])); IJ.run(rgbimp, "Draw", "slice"); params.saveParametersToJson(os.path.join(params.output_path, "parameters used.json")); params.persistParameters(); rgbimp.changes = False;
from loci.plugins import BF from net.imglib2.img.display.imagej import ImageJFunctions from net.imglib2.view import Views from net.imglib2.roi import Regions, Masks, BinaryMaskRegionOfInterest from net.imglib2.type.logic import BitType from net.imglib2.type.numeric.real import DoubleType from ij.plugin import Duplicator image, = BF.openImagePlus(inputFile.getAbsolutePath()) t = image.getTitle() ### SELECT REGION OF INTEREST # Z Projection from ij.plugin import ZProjector image_mip = ZProjector.run(image, "max") # ROI CREATION image_mip.show() image_mip.setRoi(image_mip.width / 2, image_mip.height / 2, regionSize, regionSize) from ij.gui import WaitForUserDialog myWait = WaitForUserDialog("Choose ROI", "Please position the ROI.. Press 'OK' when done.") myWait.show() # CROP image.setRoi(image_mip.getRoi()) from ij import IJ image = Duplicator().run(image)
def process(srcDir, dstDir, currentDir, fileName, keepDirectories, Channel_1, Channel_2, radius_background, sigmaSmaller, sigmaLarger, minPeakValue, min_dist): IJ.run("Close All", "") # Opening the image IJ.log("Open image file:" + fileName) #imp = IJ.openImage(os.path.join(currentDir, fileName)) #imp = IJ.getImage() imp = BF.openImagePlus(os.path.join(currentDir, fileName)) imp = imp[0] # getDimensions(width, height, channels, slices, frames) IJ.log("Computing Max Intensity Projection") if imp.getDimensions()[3] > 1: imp_max = ZProjector.run(imp,"max") else: imp_max = imp ip1, ip2 = extract_channel(imp_max, Channel_1, Channel_2) IJ.log("Substract background") imp1, imp2 = back_substraction(ip1, ip2, radius_background) IJ.log("Finding Peaks") ip1_1, ip2_1, peaks_1, peaks_2 = find_peaks(imp1, imp2, sigmaSmaller, sigmaLarger, minPeakValue) # Create a PointRoi from the DoG peaks, for visualization roi_1 = PointRoi(0, 0) roi_2 = PointRoi(0, 0) roi_3 = PointRoi(0, 0) roi_4 = PointRoi(0, 0) # A temporary array of integers, one per dimension the image has p_1 = zeros(ip1_1.numDimensions(), 'i') p_2 = zeros(ip2_1.numDimensions(), 'i') # Load every peak as a point in the PointRoi for peak in peaks_1: # Read peak coordinates into an array of integers peak.localize(p_1) roi_1.addPoint(imp1, p_1[0], p_1[1]) for peak in peaks_2: # Read peak coordinates into an array of integers peak.localize(p_2) roi_2.addPoint(imp2, p_2[0], p_2[1]) # Chose minimum distance in pixel #min_dist = 20 for peak_1 in peaks_1: peak_1.localize(p_1) for peak_2 in peaks_2: peak_2.localize(p_2) d1 = distance(p_1, p_2) if d1 < min_dist: roi_3.addPoint(imp1, p_2[0], p_2[1]) break for peak_2 in peaks_2: peak_2.localize(p_2) for peak_1 in peaks_1: peak_1.localize(p_1) d2 = distance(p_2, p_1) if d2 < min_dist: roi_4.addPoint(imp1, p_2[0], p_2[1]) break cal = imp.getCalibration() min_distance = str(round((cal.pixelWidth * min_dist),1)) table = ResultsTable() table.incrementCounter() table.addValue("Numbers of Neuron Markers", roi_1.getCount(0)) table.addValue("Numbers of Glioma Markers", roi_2.getCount(0)) table.addValue("Numbers of Glioma within %s um of Neurons" %(min_distance), roi_3.getCount(0)) table.addValue("Numbers of Neurons within %s um of Glioma" %(min_distance), roi_4.getCount(0)) #table.show("Results Analysis") saveDir = currentDir.replace(srcDir, dstDir) if keepDirectories else dstDir if not os.path.exists(saveDir): os.makedirs(saveDir) IJ.log("Saving to" + saveDir) table.save(os.path.join(saveDir, fileName + ".csv")) IJ.selectWindow("Log") IJ.saveAs("Text", os.path.join(saveDir, fileName + ".csv"));
def main(): ### debug ############################################################### #print (sys.version_info); #print(sys.path); #file_path = "D:\\data\\Inverse blebbing\\MAX_2dpf marcksl1b-EGFP inj_TgLifeact-mCh_movie e4_split-bleb1.tif"; #output_root = "D:\\data\\Inverse blebbing\\output"; #from datetime import datetime #timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S'); #output_folder = os.path.join(output_root, (timestamp + ' output')); #os.mkdir(output_folder); ######################################################################## # ensure consistent preference settings Prefs.blackBackground = False; # prompt user for input parameters params = mbui.analysis_parameters_gui(); # prompt user for file locations file_path, output_folder = mbio.file_location_chooser(params.input_image_path); params.setInputImagePath(file_path); params.setOutputPath(output_folder); # get image file import_opts, params = mbui.choose_series(file_path, params); imps = bf.openImagePlus(import_opts); imp = imps[0]; # catch unexpected image dimensions - for now, project in Z...: if imp.getNSlices() > 1: mbui.warning_dialog(["More than one Z plane detected.", "I will do a maximum projection before proceeding", "Continue?"]); imp = ZProjector.run(imp,"max all"); params = mbio.get_metadata(params); params.setCurvatureLengthUm(round(params.curvature_length_um / params.pixel_physical_size) * params.pixel_physical_size); params.persistParameters(); IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel"); imp.show(); if imp.getNChannels() > 1: imp.setPosition(params.membrane_channel_number, 1, 1); mbui.autoset_zoom(imp); IJ.run("Enhance Contrast", "saturated=0.35"); # prompt user to select ROI original_imp, crop_params = mbui.crop_to_ROI(imp, params); if crop_params is not None: params.perform_spatial_crop = True; mbui.autoset_zoom(imp); else: params.perform_spatial_crop = False; # prompt user to do time cropping imp, start_end_tuple = mbui.time_crop(imp, params); params.setTimeCropStartEnd(start_end_tuple); repeats = 1; inner_outer_comparisons = None; if params.inner_outer_comparison: inner_outer_comparisons = InnerOuterComparisonData(); repeats = 2; IJ.selectWindow(imp.getTitle()); IJ.run("Enhance Contrast", "saturated=0.35"); for r in range(0, repeats): calculated_objects = CalculatedObjects(); if params.time_crop_start_end[0] is not None: calculated_objects.timelist = [idx * params.frame_interval for idx in range(params.time_crop_start_end[0], params.time_crop_start_end[1]+1)] else: calculated_objects.timelist = [idx * params.frame_interval for idx in range(imp.getNFrames())]; calculated_objects, params, split_channels = mbfs.generate_edges(imp, params, calculated_objects, (r+1)/repeats); membrane_channel_imp = split_channels[0]; actin_channel_imp = split_channels[1]; segmentation_channel_imp = split_channels[2]; calculated_objects = mbfs.calculate_outputs(params, calculated_objects, split_channels, repeat_fraction=(r+1)/repeats); # output colormapped images and kymographs fig_imp_list = mbfs.generate_and_save_figures(imp, calculated_objects, params, membrane_channel_imp, segmentation_channel_imp); mbfs.save_csvs(calculated_objects, params); params.saveParametersToJson(os.path.join(params.output_path, "parameters used.json")); imp.changes = False; IJ.setTool("zoom"); if params.close_on_completion or (params.inner_outer_comparison and r!=(repeats-1)): for fig_imp in fig_imp_list: fig_imp.close(); elif params.close_on_completion and (r==(repeats-1)): imp.close(); if params.inner_outer_comparison: tname = "Time, " + params.interval_unit; output_folder = os.path.dirname(params.output_path); profile = [[((inner, outer), (float(outer)/inner)) for inner, outer in zip(calculated_objects.inner_outer_data.inner_means, calculated_objects.inner_outer_data.outer_means)]]; mbio.save_profile_as_csv(profile, os.path.join(output_folder, "Intensity ratios.csv"), "outer/inner", xname="inner", yname="outer", tname=tname, time_list=calculated_objects.timelist); sd_profile = [[((inner, outer), (float(outer)/inner)) for inner, outer in zip(calculated_objects.inner_outer_data.inner_sds, calculated_objects.inner_outer_data.outer_sds)]]; mbio.save_profile_as_csv(profile, os.path.join(output_folder, "Intensity standard deviation ratios.csv"), "outer sd/inner sd", xname="inner sd", yname="outer sd", tname=tname, time_list=calculated_objects.timelist); return;
def main(): # ensure consistent preference settings Prefs.blackBackground = False # get locations for previous and new outputs params = Parameters() params.loadLastParams() output_folder_old, output_folder = mbio.rerun_location_chooser( params.input_image_path) params.loadParametersFromJson( os.path.join(output_folder_old, 'parameters used.json')) params.setOutputPath(output_folder) # present user with the familiar setup UI, with options that don't make sense/aren't yet implemented disabled params = mbui.analysis_parameters_gui(rerun_analysis=True, params=params) # get original image file (for overlays etc.) if not os.path.isfile(params.input_image_path): mbui.warning_dialog([ "The original data can't be found at the location specified in saved parameters. ", "(Possibly something as simple as a change in network drive mapping has occurred)", "Please specify the location of the original image file..." ]) params.setInputImagePath( mbio.input_file_location_chooser(params.output_path)) import_opts, params = mbui.choose_series(params.input_image_path, params) imps = bf.openImagePlus(import_opts) imp = imps[0] if imp.getNSlices() > 1: mbui.warning_dialog([ "More than one Z plane detected.", "I will do a maximum projection before proceeding", "Continue?" ]) imp = ZProjector.run(imp, "max all") params = mbio.get_metadata(params) params.setCurvatureLengthUm( round(params.curvature_length_um / params.pixel_physical_size) * params.pixel_physical_size) params.persistParameters() IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") imp.show() if imp.getNChannels() > 1: imp.setPosition(params.membrane_channel_number, 1, 1) mbui.autoset_zoom(imp) IJ.run("Enhance Contrast", "saturated=0.35") # prompt user to select ROI original_imp = Duplicator().run(imp) _, crop_params = mbui.crop_to_ROI(imp, params) imp.show() if crop_params is not None: params.perform_spatial_crop = True mbui.autoset_zoom(imp) imp.updateAndDraw() review_crop = mb.check_cropping(output_folder_old, params) keep_crop = not review_crop if review_crop: keep_crop = mbui.crop_review() if not keep_crop: imp.changes = False imp.close() imp = original_imp else: original_imp.close() else: original_imp.close() # prompt user to do time cropping imp, start_end_tuple = mbui.time_crop(imp, params) params.setTimeCropStartEnd(start_end_tuple) # import edges membrane_edges = mbio.load_qcd_edges2( os.path.join(output_folder_old, "user_defined_edges.zip")) mbio.save_qcd_edges2(membrane_edges, params.output_path) calculated_objects = CalculatedObjects() calculated_objects.membrane_edges = membrane_edges if params.time_crop_start_end[0] is not None: calculated_objects.timelist = [ idx * params.frame_interval for idx in range(params.time_crop_start_end[0], params.time_crop_start_end[1] + 1) ] else: calculated_objects.timelist = [ idx * params.frame_interval for idx in range(imp.getNFrames()) ] split_channels = mbfs.split_image_plus(imp, params) membrane_channel_imp = split_channels[0] actin_channel_imp = split_channels[1] segmentation_channel_imp = None if params.photobleaching_correction: if os.path.isfile( os.path.join(output_folder_old, 'binary_membrane_stack.tif')): segmentation_binary_path = os.path.join( output_folder_old, 'binary_membrane_stack.tif') segmentation_channel_imp = IJ.openImage(segmentation_binary_path) else: segmentation_channel_imp = split_channels[2] segmentation_channel_imp = mb.make_and_clean_binary( segmentation_channel_imp, params.threshold_method) split_channels[2] = segmentation_channel_imp calculated_objects = mbfs.calculate_outputs(params, calculated_objects, split_channels) # output colormapped images and kymographs fig_imp_list = mbfs.generate_and_save_figures(imp, calculated_objects, params, membrane_channel_imp, segmentation_channel_imp) mbfs.save_csvs(calculated_objects, params) params.saveParametersToJson( os.path.join(params.output_path, "parameters used.json")) imp.changes = False IJ.setTool("zoom") if params.close_on_completion: for fig_imp in fig_imp_list: fig_imp.close() imp.close() return
#imp2 = HyperStackConverter.toHyperStack(imp, int(metadata['n_channels']), int(metadata['z_pixels']), 1, "Composite"); print(metadata) IJ.run( imp, "Properties...", "channels=" + str(int(metadata['n_channels'])) + " slices=" + str(int(metadata['z_pixels'])) + " frames=1 unit=" + str(metadata['x_unit']) + " pixel_width=" + str(metadata['x_physical_size']) + " pixel_height=" + str(metadata['y_physical_size']) + " voxel_depth=" + str(metadata['z_extent'] / metadata['z_pixels'])) imp.show() imp, z_lims = z_crop(imp) use_ch = imp.getC() print(use_ch) IJ.setTool("rect") imp.hide() imp2 = ZProjector.run(imp, "max") imp2.show() imp2.setC(use_ch + 1) WaitForUserDialog("Select XY region to crop...").show() crop_roi = imp2.getRoi() imp2.close() imp.show() imp.setRoi(crop_roi) IJ.run("Crop", "") frames = imp.getNFrames() slices = imp.getNSlices() imp = Duplicator().run(imp, use_ch + 1, use_ch + 1, 1, slices, 1, frames) imp.show() # now do 3d segmentation.... #histo = StackStatistics(imp).histogram;