def doGaussianFilter(imp, radius=30): """This function takes an input stack, and subtracts a gaussian filtered image from each individual frame. Thereby, everything that is not moving in a timeseries is filtered away. Args: imp (ImagePlus): An input stack as ImagePlus object. projectionMethod (str, optional): Choose the projection method. Options are 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median'. Defaults to "Median". Returns: ImagePlus: The resulting stack. """ #Start by getting the active image window and get the current active channel and other stats cal = imp.getCalibration() title = imp.getTitle() # Make gaussian filtered image. gaussian = IJ.run(imp, "Gaussian Blur...", "sigma=30 stack") # Subtract Z-Projection and return output ImagePlus. impout = ImageCalculator().run("Subtract create 32-bit stack", imp, gaussian) impout.setCalibration(cal) return impout
def cross_planes_approx_median_filter(stack_imp, filter_radius_um=5.0): """relatively computationally cheap, slightly crude approximation of median filter""" title = stack_imp.getTitle(); xy_imp = Duplicator().run(stack_imp); xy_imp.setTitle("xy {}".format(title)); xz_imp = Duplicator().run(stack_imp); xz_imp.setTitle("xz {}".format(title)); xz_imp = rot3d(xz_imp, 'x'); zy_imp = Duplicator().run(stack_imp); zy_imp.setTitle("zy {}".format(title)); zy_imp = rot3d(zy_imp, 'y'); stack_imp.changes = False; stack_imp.close(); xy_imp = stack_median_filter(xy_imp, radius_um=filter_radius_um); xz_imp = stack_median_filter(xz_imp, radius_um=filter_radius_um); zy_imp = stack_median_filter(zy_imp, radius_um=filter_radius_um); xz_imp = rot3d(xz_imp, 'x'); zy_imp = rot3d(zy_imp, '-y'); ic = ImageCalculator(); dummy = ic.run("Add create 32-bit stack", xy_imp, xz_imp); xz_imp.close(); xy_imp.close(); output_imp = ic.run("Add create 32-bit stack", dummy, zy_imp); zy_imp.close(); dummy.close(); output_imp.show(); IJ.run(output_imp, "Divide...", "value=3 stack"); output_imp.setTitle("Cross-plane median filtered {} (r={} um)".format(title, filter_radius_um).replace(".tif", "")); print("Image size after applying approx median filter = ({}x{}x{})".format(output_imp.getWidth(), output_imp.getHeight(), output_imp.getNSlices())); return output_imp;
def exportSegmentation(evt=None): display = Display.getFront() canvas = display.getCanvas() numLayer = display.getLayerSet().size(); exportMask(evt) files = [] for l in display.getLayerSet().getLayers(): for p in l.getDisplayables(Patch): files.append(p.getFilePath()) # Create virtual stack 'vs' vs = None for f in files: # if first image... if vs is None: imp = IJ.openImage(f) vs = VirtualStack(imp.width, imp.height, None, "/") vs.addSlice(f) ImagePlus("VSeg", vs).show() IJ.run("Duplicate...", "title=Segmentation duplicate range=1-30"); WindowManager.getImage("VSeg").close() ic = ImageCalculator() ic.run("Multiply stack", WindowManager.getImage("Segmentation"), WindowManager.getImage("Labels")); WindowManager.getImage("Labels").close()
def divide_img_by_bkg(impImg, impBkg, name): """ divide_img_by_bkg(impImg, impBkg, title) Divide an image by its background and set title Parameters ========== impImg: ImagePlus An 8 bit image from a channel impBkg: ImagePlus An 8-bit image of the background title: A string for the image title Return ====== impRet: ImagePlus The ImagePlus containing a 32 bit/px background subtracted image """ ic = ImageCalculator() impRet = ic.run("Divide create 32-bit", impImg, impBkg) impRet.setTitle(name) return impRet
def Multiply(imp1, imp2): ic = ImageCalculator() imp = ic.run("Multiply create stack", imp1, imp2) stats = StackStatistics(imp) IJ.setMinAndMax(imp, stats.min, stats.max) print stats imp.setTitle("Multiply") imp.show() return imp
def DoG(imp0, kernel1, kernel2): """Thresholds image and returns thresholded image, merge code still quite clumsy but functional""" imp1 = imp0.duplicate() imp2 = imp0.duplicate() IJ.run(imp1, "Gaussian Blur...", "sigma=" + str(kernel1) + " stack") IJ.run(imp2, "Gaussian Blur...", "sigma=" + str(kernel2) + " stack") ic = ImageCalculator() imp3 = ic.run("Subtract create stack", imp1, imp2) return imp3
def filter_diff_gauss_3d(imp,dx1,dy1,dz1,dx2,dy2,dz2): imp_1 = imp.duplicate() GaussianBlur3D().blur(imp_1, dx1, dy1, dz1) imp_2 = imp.duplicate() GaussianBlur3D().blur(imp_2, dx2, dy2, dz2) ic = ImageCalculator() imp_diff = ic.run("Subtract stack create", imp_1, imp_2) imp_diff.show() return imp_diff
def make_outline_image(imp): imp.show() # one needs to display it, otherwise below function cannot find it IJ.run("3D Fast Filters","filter=Minimum radius_x_pix=1.0 radius_y_pix=1.0 radius_z_pix=1.0"); imp.hide() imp_minimum = WindowManager.getImage("3D_Minimum") imp_outlines = imp.duplicate() calc = ImageCalculator() calc.calculate("Subtract stack", imp_outlines, imp_minimum) # clean up imp_minimum.close() imp_outlines.setTitle("Outlines") return imp_outlines
def make_outline_image(imp): #imp.show() # one needs to display it, otherwise below function cannot find it IJ.run(imp, "3D Fast Filters", "filter=Minimum radius_x_pix=1.0 radius_y_pix=1.0 radius_z_pix=1.0"); #imp.hide() imp_minimum = WindowManager.getImage("3D_Minimum") imp_outlines = imp.duplicate() ic = ImageCalculator() imp_outlines = ic.run("Subtract stack", imp_outlines, imp_minimum) # clean up imp_minimum.close() imp_outlines.setTitle("Outlines") return imp_outlines
def run(): leftdir = '/Users/rando/Downloads/NLM-MontgomeryCXRSet/MontgomerySet/ManualMask/leftMask/' rightdir = '/Users/rando/Downloads/NLM-MontgomeryCXRSet/MontgomerySet/ManualMask/rightMask/' savedir = '/Users/rando/Downloads/NLM-MontgomeryCXRSet/MontgomerySet/ManualMask/BinaryMask/' Raw_path = os.path.join(leftdir, '*png') X = glob.glob(Raw_path) axes = 'YX' for fname in X: print(fname) IJ.open(fname); imp = IJ.getImage() width = imp.width height = imp.height title_left = imp.getTitle(); print(title_left) Name = os.path.basename(os.path.splitext(fname)[0]) RightName = rightdir + title_left IJ.open(RightName) imp_right = IJ.getImage() title_right = imp_right.getTitle() print(title_right) imp_res = ImageCalculator.run(imp, imp_right, "add create 8-bit"); title = imp_res.getTitle() IJ.saveAs(imp_res, '.tif', savedir + Name); imp.close(); imp_right.close(); imp_res.close();
def GlidingSubtracter(imp): name = imp.getTitle() width, height, nChannels, nSlices, nFrames = imp.getDimensions() IJ.log("nFrames: {}".format(nFrames)) # Catch wrong input dimensions. if nChannels != 1: IJ.log("GlidingSubtracter only takes single channel images.") return None if nFrames <= 1: IJ.log("Stack has <= 1 frame. Perhaps switch Frames and Slices?") return None instack = imp.getImageStack() outstack = ImageStack() frame1 = instack.getProcessor(1) frame1 = ImagePlus("frame1", frame1) for i in range(1, nFrames): frame2 = instack.getProcessor(i) frame2 = ImagePlus("frame2", frame2) subtracted = ImageCalculator().run("subtract create 32-bit", frame1, frame2).getProcessor() # ImagePlus("slice", subtracted).show() outstack.addSlice(subtracted) outname = "subtract-" + name outstack = ImagePlus(outname, outstack) return outstack
def identifyTunicate(imp): # Clear ROI manager rm = RoiManager.getInstance() if rm is not None: rm.reset() # Get hue from HSB stack impHue = ProcessHSB.getHue(imp) width = impHue.width height = impHue.height # Get processor ipHue = impHue.getProcessor().convertToFloat() huePixels = ipHue.getPixels() # Get macro hue because it is the same color newPixels = map(ProcessHSB.macroHue, huePixels) ipNew = FloatProcessor(width, height, newPixels) impTunicate = ImagePlus("MacroHue", ipNew) # Bring brightness into the equation impBrightness = ProcessHSB.getBrightness(imp) IJ.run(impBrightness, "Auto Threshold", "method=MaxEntropy white") #IJ.run(impBrightness, "Analyze Particles...", "size=10000-Infinity circularity=0.10-1.00 show=Masks in_situ") # "add" right after "include" to include roi to manager # Logic AND pictures together ic = ImageCalculator() impTunicateMask = ic.run("AND create", impTunicate, impBrightness) IJ.run(impTunicateMask, "8-bit", "") # convert to 8-bit impTunicate.close() impBrightness.close() IJ.run(impTunicateMask, "Analyze Particles...", "size=10000-Infinity circularity=0.50-1.00 show=Masks add in_situ" ) # "add" right after "include" to include roi to manager impTunicateMask.close() #imp.show() #rm = RoiManager.getInstance() #return rm #testImp = IJ.getImage() #result = identifyTunicate(testImp) #print type(result)
def preprocess(self): IJ.run(self.imp, "Gaussian Blur...", "sigma=" + str(gaussianVal)) IJ.run(self.imp, "8-bit", "") imp_tmp = self.imp.duplicate() IJ.run(self.imp, "Gray Morphology", "radius=" + str(tophatSize) + " type=circle operator=open") ImageCalculator().run("Subtract", imp_tmp, self.imp) self.imp.changes = False self.imp.close() self.imp = imp_tmp
def make_and_clean_binary(imp, threshold_method): """convert the membrane identification channel into binary for segmentation""" if "Local: " in threshold_method: dup = Duplicator() imp1 = dup.run(imp) imp2 = dup.run(imp) imp.changes = False imp.close() threshold_method = threshold_method.split("Local: ")[1] IJ.run(imp1, "8-bit", "") IJ.run( imp1, "Auto Local Threshold", "method=" + threshold_method + " radius=15 parameter_1=0 parameter_2=0 white stack") IJ.run(imp2, "Make Binary", "method=MinError background=Dark calculate") ic = ImageCalculator() imp = ic.run("AND create stack", imp1, imp2) IJ.run(imp, "Invert", "stack") IJ.run(imp, "Make Binary", "method=Default background=Default calculate") elif "Edge" in threshold_method: IJ.run(imp, "Find Edges", "stack") IJ.run(imp, "Make Binary", "method=Mean background=Dark calculate") else: IJ.run(imp, "Make Binary", "method=" + threshold_method + " background=Dark calculate") # "calculate" ensures that threshold is calculated image-wise IJ.run(imp, "Open", "stack") IJ.run(imp, "Close-", "stack") IJ.run(imp, "Close-", "stack") IJ.run(imp, "Open", "stack") IJ.run(imp, "Fill Holes", "stack") IJ.run(imp, "Erode", "stack") IJ.run(imp, "Erode", "stack") keep_largest_blob(imp) IJ.run(imp, "Dilate", "stack") IJ.run(imp, "Dilate", "stack") IJ.run(imp, "Open", "stack") if "Edge" in threshold_method: IJ.run(imp, "Erode", "stack") IJ.run(imp, "Erode", "stack") return imp
def ThresholdMaxEntropy(imp0): """Thresholds image and returns thresholded image, merge code still quite clumsy but functional""" imp0 = IJ.getImage() impthres = imp0.duplicate() imp01 = ImagePlus("Channel1", ChannelSplitter.getChannel(imp0, 1)) imp02 = ImagePlus("Channel2", ChannelSplitter.getChannel(imp0, 2)) imp001 = imp01.duplicate() imp002 = imp02.duplicate() IJ.setAutoThreshold(imp001, "MaxEntropy dark") IJ.run(imp001, "Convert to Mask", "") IJ.run(imp001, "Divide...", "value=255") IJ.setAutoThreshold(imp002, "MaxEntropy dark") IJ.run(imp002, "Convert to Mask", "") IJ.run(imp002, "Divide...", "value=255") ic = ImageCalculator() imp0001 = ic.run("Multiply create", imp01, imp001) ic2 = ImageCalculator() imp0002 = ic2.run("Multiply create", imp02, imp002) imp0001.copy() impthres.setC(1) impthres.paste() imp0002.copy() impthres.setC(2) impthres.paste() imp01.close() imp02.close() imp001.close() imp002.close() imp0001.close() imp0002.close() return impthres
def subtractzproject(imp, projectionMethod="Median"): """This function takes an input stack, and subtracts a projection from the whole stack from each individual frame. Thereby, everything that is not moving in a timeseries is filtered away. Args: imp (ImagePlus): An input stack as ImagePlus object. projectionMethod (str, optional): Choose the projection method. Options are 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median'. Defaults to "Median". Returns: ImagePlus: The resulting stack. """ #Start by getting the active image window and get the current active channel and other stats cal = imp.getCalibration() title = imp.getTitle() # Define a dictionary containg method_name:const_fieled_value pairs for the projection methods. methods_as_strings = [ 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median' ] methods_as_const = [ ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD, ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD ] method_dict = dict(zip(methods_as_strings, methods_as_const)) # Run Z-Projection. zp = ZProjector(imp) zp.setMethod(method_dict[projectionMethod]) zp.doProjection() impMedian = zp.getProjection() # Subtract Z-Projection and return output ImagePlus. impout = ImageCalculator().run("Subtract create 32-bit stack", imp, impMedian) impout.setCalibration(cal) return impout
def identifyRed(imp): # Clear ROI manager rm = RoiManager.getInstance() if rm is not None: rm.reset() # Get hue from HSB stack impHue = ProcessHSB.getHue(imp) width = impHue.width height = impHue.height # Get processor for hue ipHue = impHue.getProcessor().convertToFloat() huePixels = ipHue.getPixels() # Bring brightness into the equation impBrightness = ProcessHSB.getBrightness(imp) IJ.run(impBrightness, "Auto Threshold", "method=Default white") #IJ.run(impBrightness, "Analyze Particles...", "size=10000-Infinity circularity=0.00-1.00 show=Masks in_situ") # If hue < 30 and hue > 225, True newPixels = map(ProcessHSB.redHue, huePixels) # Pause: Do this later ipNew = FloatProcessor(width, height, newPixels) impRed = ImagePlus("RedHue", ipNew) IJ.run(impRed, "8-bit", "") # convert to 8-bit # Logic AND pictures together ic = ImageCalculator() impRedMask = ic.run("AND create", impRed, impBrightness) IJ.run(impRedMask, "8-bit", "") # convert to 8-bit IJ.run(impRedMask, "Analyze Particles...", "size=10000-Infinity circularity=0.00-1.00 show=Masks add in_situ") # "add" right after "include" to include roi to manager impHue.close() impBrightness.close() impRed.close() impRedMask.close()
def open_fli(filepth): # load the dataset options = ImporterOptions() options.setId(filepth) options.setOpenAllSeries(1) imps = BF.openImagePlus(options) for imp in imps: title = imp.getTitle() if title.find("Background Image")==-1: img = imp imp.close() else: bkg = imp imp.close() ic = ImageCalculator() img2 = ic.run("Subtract create 32-bit stack",img,bkg) #copy the metadata props = img.getProperties() for prop in props: img2.setProperty(prop,props.getProperty(prop)) img.close() bkg.close() return img2
def maskFromOverlay(imp): ''' TODO Documentation ''' overlay = imp.getOverlay(); img = ImageJFunctions.wrap(imp); emptyImg = ops.create().img(img); if overlay is None: return emptyImg; emptyImp = ImageJFunctions.wrap(emptyImg, "mask"); for roi in overlay.toArray(): imp.setRoi(roi); IJ.run(imp, "Create Mask", ""); manualMaskImp = IJ.getImage(); ic = ImageCalculator(); ic.run("OR", emptyImp, manualMaskImp); manualMask = ImageJFunctions.wrap(manualMaskImp); manualMaskImp.close(); #imp.setRoi(None); return manualMask;
def create(imp): # Prep Roi Manager rm = RoiManager.getInstance() if rm is not None: rm.reset() # Get current image imp2 = imp.duplicate() IJ.run(imp2, "8-bit", "") # convert to 8-bit IJ.run(imp2, "Auto Threshold", "method=Shanbhag white") IJ.run(imp2, "Analyze Particles...", "size=10000-Infinity circularity=0-1.00 show=Masks add in_situ") # "add" right after "include" to include roi to manager # Remove background ic = ImageCalculator() imp3 = ic.run("AND create", imp, imp2) imp.close() imp2.close() ### Begin manipulating ROIs ### rm = RoiManager.getInstance() # Get number of objects found roiCount = rm.getCount() print "Number of Particles found:" + str(roiCount)
def mousePressed(self, event): from ij import IJ, ImagePlus from ij.process import FloatProcessor import math from ij.plugin import ImageCalculator imp = IJ.getImage() imp.setSlice(3) ip = imp.getProcessor().convertToFloat() # as a copy pixels = ip.getPixels() imp.setSlice(2) ip1 = imp.getProcessor().convertToFloat() # as a copy pixels1 = ip1.getPixels() imp.setSlice(1) ip2 = imp.getProcessor().convertToFloat() # as a copy pixels2 = ip2.getPixels() canvas = event.getSource() p = canvas.getCursorLoc() imp = canvas.getImage() x = p.x * 1.0000 y = p.y * 1.0000 nx = x - imp.width / 2 ny = y - imp.height / 2 n_y = ny * -1 n_xx = nx / imp.width / 2 n_yy = n_y / imp.height / 2 z = math.sqrt(n_xx * n_xx + n_yy * n_yy) z1 = math.sqrt(1 - z * z) Xdir = map(lambda x: x * n_xx, pixels2) Ydir = map(lambda x: x * n_yy, pixels1) Zdir = map(lambda x: x * z1, pixels) ip3 = FloatProcessor(ip.width, ip.height, Xdir, None) imp3 = ImagePlus("", ip3) ip4 = FloatProcessor(ip.width, ip.height, Ydir, None) imp4 = ImagePlus("", ip4) ip5 = FloatProcessor(ip.width, ip.height, Zdir, None) imp5 = ImagePlus("", ip4) imp6 = ImageCalculator().run("Add create 32-bit stack", imp3, imp4) imp7 = ImageCalculator().run("Add create 32-bit stack", imp5, imp6) imp7.setTitle("Lighting Direction") imp7.show()
def BackgroundFilter(imp, projection_method = "Median"): title = imp.getTitle() #Make a dict containg method_name:const_fieled_value pairs for the projection methods methods_as_strings=['Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median'] methods_as_const=[ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD, ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD] method_dict=dict(zip(methods_as_strings, methods_as_const)) #The Z-Projection magic happens here through a ZProjector object zp = ZProjector(imp) zp.setMethod(method_dict[projection_method]) zp.doProjection() outstack = imp.createEmptyStack() outstack.addSlice(zp.getProjection().getProcessor()) imp2 = ImagePlus(title+'_'+projection_method, outstack) out = ImageCalculator().run("Subtract create 32-bit stack", imp, imp2) return out
def process_caspase_signal(path_signal, path_imp, path_imp_out): path_imp = path_signal + path_imp imp = IJ.openImage(path_imp) imp.show() zp = ZProjector(imp) zp.setMethod(ZProjector.AVG_METHOD) zp.doProjection() zpimp = zp.getProjection() imp_sub = ImageCalculator().run("Subtract create stack", imp, zpimp) imp_sub.show() IJ.saveAs(imp_sub, "Tiff", path_signal + path_imp_out) imp.changes = False imp.close() imp_sub.changes = False imp_sub.close()
def generate_r_image(imp, ring_rois, centres, unwrap_axis, threshold_val): """for each point in the projection, calculate the distance to the vessel axis and present as an image""" fp = imp.getProcessor() fp.setThreshold(threshold_val, fp.maxValue(), FloatProcessor.NO_LUT_UPDATE) bp = fp.createMask() bp.dilate() bp.erode() mask_imp = ImagePlus("Mask", bp) tile_mask = make_tiled_imp(mask_imp) #tile_mask.show(); #WaitForUserDialog("pasue - generated mask").show(); mask_imp = do_unwrap(tile_mask, unwrap_axis, imp_title=mask_imp.getTitle()) #mask_imp.show(); roi = PolygonRoi([x for (x, y) in unwrap_axis], [y for (x, y) in unwrap_axis], PolygonRoi.POLYLINE) mask_imp.setRoi(roi) #WaitForUserDialog("pasue - unwrapped").show(); IJ.run(mask_imp, "Fill Holes", "") #WaitForUserDialog("pasue - filled holes").show(); IJ.run(mask_imp, "Divide...", "value=255") #WaitForUserDialog("pasue - scaled to 0-1").show(); #mask_imp.show(); r_list = [] for lidx, (roi, centre) in enumerate(zip(ring_rois, centres)): r_sublist = [ math.sqrt((x - centre[0])**2 + (y - centre[1])**2) for x, y in zip(roi.getPolygon().xpoints, roi.getPolygon().ypoints) ] r_list.append(r_sublist) r_imp = ImagePlus("Radii", FloatProcessor([list(x) for x in zip(*r_list)])) tile_r_imp = make_tiled_imp(r_imp) r_imp = do_unwrap(tile_r_imp, unwrap_axis, imp_title=r_imp.getTitle()) r_imp = ImageCalculator().run("Multiply create", r_imp, mask_imp) IJ.run(r_imp, "Cyan Hot", "") return r_imp, mask_imp
#imp.getCalibration().getUnit() # should return 'micron' #imp.getCalibration() # DBG if crop_image: imp.setRoi(int(xLoc-math.floor(winCrop/2)),int(yLoc-math.floor(winCrop/2)),winCrop,winCrop) # Create a ROI and crop it. else: imp.setRoi(0,0,imp.width,imp.height) # Create a ROI and crop it. crop = imp.crop("stack") ij.process.ImageConverter(crop).convertToGray32() tmp1 = Duplicator().run(crop, chDNA, chDNA, 1, crop.getNSlices(), 1, crop.getNFrames()) #Stack.setChannel(chDNA); run("Duplicate...", "channels=2 title=cropDNA duplicate"); tmp2 = Duplicator().run(crop, chDNA, chDNA, 1, crop.getNSlices(), 1, crop.getNFrames()) #run("Duplicate...", "title=tmp2 duplicate"); # === Band pass filtering IJ.run(tmp1, "Gaussian Blur...", "sigma=%f stack" % sd1) #selectWindow("tmp1"); run("Gaussian Blur...", "sigma="+sd1+" stack"); IJ.run(tmp2, "Gaussian Blur...", "sigma=%f stack" % sd2) #selectWindow("tmp2"); run("Gaussian Blur...", "sigma="+sd2+" stack"); cropDNA_bPass = ImageCalculator().run("Subtract create 32-bit stack", tmp1, tmp2) #imageCalculator("Subtract create 32-bit stack", "tmp1","tmp2"); rename("cropDNA_bPass"); tmp1.close() tmp2.close() # === Create stack to be processed # From https://stackoverflow.com/questions/48213759/combine-channels-in-imagej-jython crop_channels = ij.plugin.ChannelSplitter.split(crop) # selectWindow("crop"); run("Split Channels"); if len(crop_channels)>=2: res_st = ij.plugin.RGBStackMerge().mergeHyperstacks([cropDNA_bPass, ]+[c for c in crop_channels], True) #run("Merge Channels...", "c1=cropDNA_bPass c2=C1-crop c3=C2-crop create") else : IJ.log("NOT IMPLEMENTED ERROR") raise NotImplementedError # === 3D drift correction (we are working with res_st as input image) res_st.setRoi(int(winCrop/2)-int(winDrift/2), int(winCrop/2)-int(winDrift/2), winDrift, winDrift) if run_DC:
def process(dirIn, dirOut, expName, ps, pe, ts, te): jobid = commands.getoutput("echo $PBS_JOBID").split('.')[0] jobid = jobid.replace("[","_").replace("]","") # because the jobids look like 2356385[1] which causes problems print "job id: "+jobid jobdir = os.path.join("/tmp",str(jobid)+"_fiji") print "job dir: "+jobdir for p in range(ps,pe+1): pID = str(p); for t in range(ts,te+1): print "TIMEPOINT STARTING ***************" tID = "t"+str(t); print "time-point: "+tID; if os.path.isdir(jobdir): print "removing "+jobdir shutil.rmtree(jobdir) print "creating "+jobdir os.mkdir(jobdir) if stitching: fileOut = "rescaled_flipped_"; for z in range(zs,ze+1): zID = "z"+str(z); print "z-plane: "+zID; if bandpass: IJ.log("bandpass....") # load all images from same time point and same z-position fileID = expName+pID+"_b0"+tID+zID+"m.*"; IJ.log("opening images: "+os.path.join(dirIn,fileID)) IJ.run("Image Sequence...", "open=["+dirIn+"] starting=1 increment=1 scale=100 file=[] or=["+fileID+"] sort"); #selectWindow("im-2012-0007_Position35.tif_Files"); imp = IJ.getImage(); #imp.show(); imp.setTitle("Stack"); # illumination correction IJ.log("computing FFT..."); # run("Flip Horizontally", "stack"); impFFT = Duplicator().run(imp); for i in range(1, impFFT.getNSlices()+1): print "FFT of slice "+str(i) impFFT.setSlice(i) IJ.run(impFFT, "Bandpass Filter...", "filter_large=10000 filter_small=200 suppress=None tolerance=5 "); #impFFT.show() #stats = imp.getStatistics(Measurements.MEAN) #IJ.log("stats.mean = "+str(stats.mean)); # this is only the mean of one slice...is this a problem? print "dividing image stack by FFT stack..."; ic = ImageCalculator() impCorr = ic.run("Divide create 32-bit stack", imp, impFFT); #impCorr.show() def computeMean(pixels): return sum(pixels) / float(len(pixels)) print "multiplying each image by 128/mean for going back to 8 bit space..." stack = impCorr.getStack() for i in range(1, impCorr.getNSlices()+1): ip = stack.getProcessor(i).convertToFloat() mean = computeMean(ip.getPixels()) print "multiplying slice "+str(i)+" by "+str(float(128/mean)) ip.multiply(float(128/mean)) IJ.log("converting from 32-bit to 8-bit...") IJ.setMinAndMax(impCorr, 0, 255); IJ.run(impCorr,"8-bit",""); #IJ.saveAs(impCorr, "Tiff", "/Users/tischi/Documents/processed.tif"); #ff #impCorr.show() # save images IJ.log("saving bandpass corrected image sequence: "+os.path.join(jobdir,fileOut)) IJ.run(impCorr, "Image Sequence... ", "format=TIFF name=["+fileOut+"] start=1 digits=4 save=["+jobdir+"]"); if check: IJ.run(impCorr, "Image Sequence... ", "format=TIFF name=["+fileOut+"] start=1 digits=4 save=["+dirOut+"]"); #impCorr.close(); imp.close(); impFFT.hide(); # stitching IJ.log("STITCHING START **********") layoutFile = copyStitchingLayoutFile(dirIn,expName,jobdir,ps) ###layoutFile = makeStitchingLayoutFile(jobdir) createPreview = 0 computeOverlap = 0 fusion_method="Linear Blending" handleRGB = "Red, Green and Blue" showImage = 0 #fusion=1 regression=0.30 max/avg=2.50 absolute=3.50" st = Stitch_Image_Collection() st.alpha = 1 IJ.log("layout file: "+str(layoutFile)) impStitched = st.work(layoutFile, createPreview, computeOverlap, fusion_method, handleRGB, showImage) stitchedFile = os.path.join(jobdir,tID+zID+"_stitched.tif"); #impStitched.show() IJ.saveAs(impStitched,"Tiff", stitchedFile); if check: print os.path.join(dirOut,tID+zID+"_stitched.tif") stitchedFile = os.path.join(dirOut,tID+zID+"_stitched.tif"); IJ.saveAs(impStitched,"Tiff", stitchedFile); IJ.log("STITCHING END **********") if combine_z: IJ.log("combine z.....") ######### IJ.log("load stitched images into a stack...") for z in range(zs,ze+1): zID = "z"+str(z); stitchedFile = os.path.join(jobdir,tID+zID+"_stitched.tif"); IJ.log("opening "+stitchedFile) imp = IJ.openImage(stitchedFile) if z==zs: stack = ImageStack(imp.width,imp.height) stack.addSlice(imp.getProcessor()) imp = ImagePlus("stack", stack) #imp.show() ######## ######## IJ.log("cropping...") imp.setRoi(xs, ys, xe, ye); IJ.run(imp, "Crop", ""); #imp.show() ######## # the following normalisation should not be necessary, because they are already all 128/mean normalised #IJ.log("-- normalise intensity of all slices...") #stats = imp.getStatistics(Measurements.MEAN) #IJ.log("stats.mean = "+str(stats.mean)); # this is only the mean of one slice...is this a problem? #stack = imp.getStack() #for i in range(1, impFFT.getNSlices()+1): # ip = stack.getProcessor(i).convertToFloat() # ip.multiply(128/stats.mean) # #stack.setSlice(stack.getSliceLabel(i), ip) #run("Set Slice...", "slice="+1); #run("Set Measurements...", " mean redirect=None decimal=9"); #run("Select None"); #setBatchMode(true); #setMinAndMax(0, 255); run("32-bit"); #for(l=0; l<nSlices+1; l++) { ## run("Select All"); # run("Clear Results"); # run("Measure"); # picsum=getResult("Mean",0); # //if(l==0){picsum1=picsum;} # //int_ratio=picsum1/picsum; # int_ratio=128/picsum; # run("Select None"); # IJ.log("ratio ="+int_ratio); # run("Multiply...", "slice value="+int_ratio); # run("Next Slice [>]"); #} #setBatchMode(false); # stop here and try by hand #... #dfgfd #//stack-reg #//IJ.log("register xy...") #//run("StackReg", "transformation=Translation"); #// project into 1 plane .... #// run("Extended Depth of Field (Easy mode)..."); #//run("Z Project...", "start=["+1+"] stop=["+ze+"] projection=[Standard Deviation]"); doEDF = True if doEDF: IJ.log("EDF: start...") parameters = Parameters() parameters.setQualitySettings(1) parameters.setTopologySettings(0) parameters.show3dView = False parameters.showTopology = False edfh = ExtendedDepthOfFieldHeadless(imp, parameters) imp = edfh.processHeadless() IJ.log("EDF: done.") #imp.show() IJ.log("EDF: converting from 32-bit to 8-bit...") IJ.setMinAndMax(imp, 0, 255); IJ.run(imp,"8-bit",""); edfFile = os.path.join(dirOut,expName+pID+"-"+tID+"_EDOF_noTimeNorm.tif"); IJ.log("EDF save: "+edfFile) IJ.saveAs(imp,"Tiff", edfFile); IJ.log("EDF save: done.") #close(); // projection #close(); // stack print "TIMEPOINT FINISHED ***************" if os.path.isdir(jobdir): print "removing "+jobdir shutil.rmtree(jobdir)
if doCorrectRefraction: params = ("reference_channel=2 application_channel=1 automatic_operation generate_log " + "max_slice=43 surface_slice=87") IJ.run(nextStepImage,"Refractive Signal Loss Correction",params) mergingImages = [WindowManager.getImage("App Corrected"),WindowManager.getImage("Ref Corrected")] next2StepImage = RGBStackMerge.mergeChannels(mergingImages,True) for img in mergingImages: img.close() #next2StepImage.show() nextStepImage.close() else: next2StepImage = nextStepImage nextStepImage.close() ## Makes the amplified composite image ic = ImageCalculator() indChannels = ChannelSplitter.split(next2StepImage) sourceDataImage = indChannels[0].duplicate() for sl in range(1,sourceDataImage.getNSlices()+1): sourceDataImage.setSliceWithoutUpdate(sl) ip = sourceDataImage.getProcessor() ip.multiply(ampFactor) ratedRefImage = ic.run("Subtract create stack",indChannels[1],sourceDataImage) mergingImages = [indChannels[0],ratedRefImage] outputImage = RGBStackMerge.mergeChannels(mergingImages,True) for img in mergingImages: img.close() for img in indChannels: img.close() next2StepImage.close() sourceDataImage.close()
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)
def process_pi_signal(path, position, unsynchronized=True): if unsynchronized: path_signal = path + "\\pi" path_signal_before = path_signal + "\\before" path_signal_after = path_signal + "\\after" path_signal_merged = path_signal + "\\merged" path_imp_before = path_signal_before + "\\pi_in-focusxy%sc1.tif" % position path_imp_after = path_signal_after + "\\pixy%sc1.tif" % position path_imp_merged = path_signal_merged + "\\merged.tif" path_imp_merged_sub = path_signal_merged + "\\merged_sub.tif" imp1 = IJ.openImage(path_imp_before) imp1.show() imp2 = IJ.openImage(path_imp_after) imp2.show() zp1 = ZProjector(imp1) zp1.setMethod(ZProjector.AVG_METHOD) zp1.doProjection() zpimp1 = zp1.getProjection() zp2 = ZProjector(imp2) zp2.setMethod(ZProjector.AVG_METHOD) zp2.doProjection() zpimp2 = zp2.getProjection() imp_sub1 = ImageCalculator().run("Subtract create stack", imp1, zpimp1) imp_sub1.show() imp_sub2 = ImageCalculator().run("Subtract create stack", imp2, zpimp2) imp_sub2.show() concatenate_files(imp1, imp2, path_imp_merged) concatenate_files(imp_sub1, imp_sub2, path_imp_merged_sub) else: path_signal = path + "\\pi\\seq0002xy%sc1.tif" % position path_sub = path + "\\pi\\sub.tif" imp = IJ.openImage(path_signal) imp.show() zp = ZProjector(imp) zp.setMethod(ZProjector.AVG_METHOD) zp.doProjection() zpimp = zp.getProjection() imp_sub = ImageCalculator().run("Subtract create stack", imp, zpimp) imp_sub.show() IJ.saveAs(imp_sub, "Tiff", path_sub) imp.changes = False imp.close() zpimp.changes = False zpimp.close() imp_sub.changes = False imp_sub.close()
def track(): imp = IJ.getImage() nChannels = imp.getNChannels() # Get the number of channels orgtitle = imp.getTitle() IJ.run("Subtract Background...", "rolling=50 sliding stack") IJ.run("Enhance Contrast...", "saturated=0.3") IJ.run("Multiply...", "value=10 stack") IJ.run("Subtract Background...", "rolling=50 sliding stack") IJ.run("Set Scale...", "distance=0") channels = ChannelSplitter.split(imp) imp_GFP = channels[0] imp_RFP = channels[1] IJ.selectWindow(orgtitle) IJ.run("Close") ic = ImageCalculator() imp_merge = ic.run("Add create stack", imp_GFP, imp_RFP) imp_merge.setTitle("add_channels") imp_merge.show() imp_RFP.show() imp_GFP.show() imp5 = ImagePlus() IJ.run(imp5, "Merge Channels...", "c1=[" + imp_merge.title + "] c2=" + imp_GFP.title + ' c3=' + imp_RFP.title + " create") print("c1=[" + imp_merge.title + "] c2=" + imp_GFP.title + ' c3=' + imp_RFP.title + " create") imp5.show() imp5 = IJ.getImage() nChannels = imp5.getNChannels() # Setup settings for TrackMate settings = Settings() settings.setFrom(imp5) # Spot analyzer: we want the multi-C intensity analyzer. settings.addSpotAnalyzerFactory(SpotMultiChannelIntensityAnalyzerFactory()) # Spot detector. settings.detectorFactory = LogDetectorFactory() settings.detectorSettings = settings.detectorFactory.getDefaultSettings() settings.detectorSettings['TARGET_CHANNEL'] = 1 settings.detectorSettings['RADIUS'] = 24.0 settings.detectorSettings['THRESHOLD'] = 0.0 # Spot tracker. # Configure tracker - We don't want to allow merges or splits settings.trackerFactory = SparseLAPTrackerFactory() settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap() # almost good enough settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = False settings.trackerSettings['ALLOW_TRACK_MERGING'] = False settings.trackerSettings['LINKING_MAX_DISTANCE'] = 8.0 settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = 8.0 settings.trackerSettings['MAX_FRAME_GAP'] = 1 # Configure track filters settings.addTrackAnalyzer(TrackDurationAnalyzer()) settings.addTrackAnalyzer(TrackSpotQualityFeatureAnalyzer()) filter1 = FeatureFilter('TRACK_DURATION', 20, True) settings.addTrackFilter(filter1) # Run TrackMate and store data into Model. model = Model() trackmate = TrackMate(model, settings) ok = trackmate.checkInput() if not ok: sys.exit(str(trackmate.getErrorMessage())) ok = trackmate.process() if not ok: sys.exit(str(trackmate.getErrorMessage())) selectionModel = SelectionModel(model) displayer = HyperStackDisplayer(model, selectionModel, imp5) displayer.render() displayer.refresh() IJ.log('TrackMate completed successfully.') IJ.log('Found %d spots in %d tracks.' % (model.getSpots().getNSpots(True) , model.getTrackModel().nTracks(True))) # Print results in the console. headerStr = '%10s %10s %10s %10s %10s %10s' % ('Spot_ID', 'Track_ID', 'Frame', 'X', 'Y', 'Z') rowStr = '%10d %10d %10d %10.1f %10.1f %10.1f' for i in range( nChannels ): headerStr += (' %10s' % ( 'C' + str(i+1) ) ) rowStr += ( ' %10.1f' ) #open a file to save results myfile = open('/home/rickettsia/Desktop/data/Clamydial_Image_Analysis/EMS_BMECBMELVA_20X_01122019/data/'+orgtitle.split('.')[0]+'.csv', 'wb') wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(['Spot_ID', 'Track_ID', 'Frame', 'X', 'Y', 'Z', 'Channel_1', 'Channel_2']) IJ.log('\n') IJ.log(headerStr) tm = model.getTrackModel() trackIDs = tm.trackIDs(True) for trackID in trackIDs: spots = tm.trackSpots(trackID) # Let's sort them by frame. ls = ArrayList(spots) for spot in ls: values = [spot.ID(), trackID, spot.getFeature('FRAME'), \ spot.getFeature('POSITION_X'), spot.getFeature('POSITION_Y'), spot.getFeature('POSITION_Z')] for i in range(nChannels): values.append(spot.getFeature('MEAN_INTENSITY%02d' % (i+1))) IJ.log(rowStr % tuple(values)) l1 = (values[0], values[1], values[2], values[3], values[4], values[5], values[7], values[8]) wr.writerow(l1) myfile.close() IJ.selectWindow("Merged") IJ.run("Close")
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters): # set calibration detectionParameters.setCalibration(inputImp); # calculate area of roi stats=inputImp.getStatistics() inputRoiArea=stats.area # 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 # crop the roi interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') ) #cropped=ops.image().crop(interval, None, inputDataset.getImgPlus() ) cropped=ops.image().crop(inputDataset.getImgPlus() , interval) datacropped=data.create(cropped) display.createDisplay("cropped", datacropped) croppedPlus=IJ.getImage() # instantiate the duplicator and the substackmaker classes duplicator=Duplicator() substackMaker=SubstackMaker() # duplicate the roi duplicate=duplicator.run(croppedPlus) # 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)) # convert to lab IJ.run(croppedPlus, "Color Transformer", "colour=Lab") IJ.selectWindow('Lab') labPlus=IJ.getImage() croppedPlus.changes=False croppedPlus.close() # 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"); labPlus.close() fast=True # threshold the spots from the red channel if (fast==False): thresholdedred=SpotDetectionGray(red, data, display, ops, "triangle") impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped") else: impthresholdedred=SpotDetection2(redPlus) # threshold the spots from the brightness channel if (fast==False): thresholded=SpotDetectionGray(brightness, data, display, ops, "triangle") impthresholded=ImageJFunctions.wrap(thresholded, "wrapped") else: impthresholded=SpotDetection2(brightnessPlus) # or the thresholding results from red and brightness channel impthresholded = ic.run("OR create", impthresholded, impthresholdedred); roim=RoiManager(True) # convert to mask Prefs.blackBackground = True IJ.run(impthresholded, "Convert to Mask", "") def isRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.porphyrinRedPercentage): return True else: return False def notRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.porphyrinRedPercentage): return False else: return True roiClone=inputRoi.clone() roiClone.setLocation(0,0) Utility.clearOutsideRoi(impthresholded, roiClone) impthresholded.show() countParticles(impthresholded, roim, detectionParameters.porphyrinMinSize, detectionParameters.porphyrinMaxSize, \ detectionParameters.porphyrinMinCircularity, detectionParameters.porphyrinMaxCircularity) uvPoreList=[] for roi in roim.getRoisAsArray(): uvPoreList.append(roi.clone()) #allList=uvPoreList+closedPoresList+openPoresList # count particles that are porphyrins (red) porphyrinList=CountParticles.filterParticlesWithFunction(redMask, uvPoreList, isRed) # count particles that are visible on uv but not porphyrins sebumList=CountParticles.filterParticlesWithFunction(redMask, uvPoreList, notRed) # 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 uvPoreList] # draw the ROIs on to the image inputImp.getProcessor().setColor(Color.green) IJ.run(inputImp, "Line Width...", "line=3"); inputImp.getProcessor().draw(inputRoi) IJ.run(inputImp, "Line Width...", "line=1"); [CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in porphyrinList] [CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumList] inputImp.updateAndDraw() # calculate stats for the UV visible particles detectionParameters.setCalibration(APlus) statsDictUV=CountParticles.calculateParticleStatsUV(APlus, BPlus, redMask, roim.getRoisAsArray()) totalUVPoreArea=0 for area in statsDictUV['Areas']: totalUVPoreArea=totalUVPoreArea+area averageUVPoreArea=totalUVPoreArea/len(statsDictUV['Areas']) poreDiameter=0 for diameter in statsDictUV['Diameters']: poreDiameter=poreDiameter+diameter poreDiameter=poreDiameter/len(statsDictUV['Diameters']) redTotal=0 for red in statsDictUV['redPercentage']: redTotal=redTotal+red redAverage=redTotal/len(statsDictUV['redPercentage']) statslist=[len(porphyrinList), 100*redAverage]; statsheader=[Messages.Porphyrins, Messages.PercentageRedPixels] print("Roi Area: "+str(inputRoiArea)) print("Total Pore Area: "+str(totalUVPoreArea)) print("Average Pore Area: "+str(averageUVPoreArea)) print str(len(uvPoreList))+" "+str(len(porphyrinList))+" "+str(len(sebumList))+" "+str(100*totalUVPoreArea/inputRoiArea)+" "+str(100*redAverage) print "cp min circularity"+str(detectionParameters.closedPoresMinCircularity)+":"+str(detectionParameters.closedPoresMinSize) # close the thresholded image impthresholded.changes=False impthresholded.close() return uvPoreList, statslist, statsheader
def addImages(self,img1, img2): ic = ImageCalculator() sumImage = ic.run("Add create stack",img1,img2) return(sumImage)
gd.showDialog() ## Does simple interpolation of the ROIs through the stack if len(sliceList)>0: sliceList.sort(reverse=True) for sl in range(theImage.getNSlices()): if (sl+1) < sliceList[-1]: maskImage.setSliceWithoutUpdate(sliceList[-1]) activeIp = maskImage.getProcessor().duplicate() elif (sl+1) > sliceList[0]: maskImage.setSliceWithoutUpdate(sliceList[0]) activeIp = maskImage.getProcessor().duplicate() else: isFound = False for mark in sliceList: dist = sl+1 - mark if dist >= 0 and not isFound: isFound = True refSlice = mark maskImage.setSliceWithoutUpdate(refSlice) activeIp = maskImage.getProcessor().duplicate() maskImage.setSliceWithoutUpdate(sl+1) maskImage.setProcessor(activeIp) ## Computes the overlay image ic = ImageCalculator() resultImage = ic.run("AND create stack",theImage,maskImage) resultImage.show() maskImage.close()
# Get parameters from dialog options = getOptions() if options is not None: lowerThreshold, upperThreshold, stepNumber, stepThreshold, p3DOCmin, p3DOCmax = options #lowerThreshold, upperThreshold, stepNumber, stepThreshold, p3DOCThreshold, p3DOCmin, p3DOCmax = options #p3DOCSlice = 1 #genero duplicados de x1 para efectuar umbralización en cada uno list_x2 = [] #guarda las imagenes umbralizadas list_x3 = []#guarda las mascaras list_x4 = []#guarda los esqueletos ic = ImageCalculator() #para hacer llamadas más cortas de la clase #UMBRALIZACION for i in range(stepNumber):#hacer tantas veces como diga stepNumber x2= x1.duplicate() x2.setTitle('x2_'+repr(i)) #x2.show() #efectúo la umbralización con OTSU #IJ.run("Threshold...")#si se quiere correr las opciones Fiji IJ.setThreshold(x2, (lowerThreshold +stepThreshold*i) , upperThreshold, "Black & White") IJ.run(x2, "Convert to Mask", "method=Otsu background=Dark black" ) #se guarda resultado umbralización en list_x2 list_x2.append( x2 ) # #
goRun = True rt = ResultsTable() while goRun: wfud = WaitForUserDialog("Pick freehand ROI, then hit OK to analyze") wfud.show() roi = theImage.getRoi() if roi is None: goRun = False else: dataImage.setRoi(roi) subImage = dataImage.duplicate() dataIp = dataImage.getProcessor() dataIp.setRoi(roi) maskIp = dataIp.getMask() maskImage = ImagePlus("Mask Image",maskIp) ic = ImageCalculator() countingImage = ic.run("AND create stack",subImage,maskImage) pixelCount = 0 for i in range(1,countingImage.getNSlices()+1): countingImage.setSlice(i) countingIp = countingImage.getProcessor() for x in range(0,countingImage.getWidth()): for y in range(0,countingImage.getHeight()): if (countingIp.getPixel(x,y) >= intensityThreshold): pixelCount = pixelCount + 1 totAvailablePixels = countingImage.getWidth() * countingImage.getHeight() * countingImage.getNSlices() #IJ.log("Pixel count: " + str(pixelCount) + " of " + str(totAvailablePixels)) countingImage.close() rt.incrementCounter() rt.addValue("PosPixels",pixelCount) rt.addValue("TotPixels",totAvailablePixels)
val_high = rt.getValueAsDouble(1,0) val_bleed = rt.getValueAsDouble(1,1) val_low = rt.getValueAsDouble(1,2) val_zero = rt.getValueAsDouble(1,3) val_target = val_high - val_low # scale_target = val_target / val_bleed scale_target = val_target / (val_bleed - val_zero) print scale_target gd = GenericDialog("Scale factor") gd.addNumericField("Scale factor on subtraction:",scale_target,3) gd.showDialog() if (gd.wasCanceled()): quit() scale = gd.getNextNumber() tempImage = image2.duplicate() for i in range(tempImage.getNSlices()): tempImage.setSliceWithoutUpdate(i+1) ip = tempImage.getProcessor() ip.subtract(val_zero) ip.multiply(scale) ic = ImageCalculator() newImage = ic.run("Subtract create stack",image1,tempImage) newImage.show() else: IJ.error("No images are open.")
def analyze(iDataSet, tbModel, p, output_folder): # # LOAD FILES # filepath = tbModel.getFileAPth(iDataSet, "RAW", "IMG") filename = tbModel.getFileName(iDataSet, "RAW", "IMG") print("Analyzing: "+filepath) IJ.run("Bio-Formats Importer", "open=["+filepath+"] color_mode=Default view=Hyperstack stack_order=XYCZT"); imp = IJ.getImage() # # INIT # IJ.run("Options...", "iterations=1 count=1"); # # SCALING # IJ.run(imp, "Scale...", "x="+str(p["scale"])+" y="+str(p["scale"])+" z=1.0 interpolation=Bilinear average process create"); imp = IJ.getImage() # save output file output_file = filename+"--downscale_input.tif" IJ.saveAs(IJ.getImage(), "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "INPUT","IMG") # # CONVERSION # #IJ.run(imp, "8-bit", ""); # # CROPPING # #imp.setRoi(392,386,750,762); #IJ.run(imp, "Crop", ""); # # BACKGROUND SUBTRACTION # # IJ.run(imp, "Subtract...", "value=32768 stack"); IJ.run(imp, "Z Project...", "projection=[Average Intensity]"); imp_avg = IJ.getImage() ic = ImageCalculator(); imp = ic.run("Subtract create 32-bit stack", imp, imp_avg); # # REGION SEGMENTATION # imp1 = Duplicator().run(imp, 1, imp.getImageStackSize()-1) imp2 = Duplicator().run(imp, 2, imp.getImageStackSize()) imp_diff = ic.run("Subtract create 32-bit stack", imp1, imp2); #imp_diff.show() IJ.run(imp_diff, "Z Project...", "projection=[Standard Deviation]"); imp_diff_sd = IJ.getImage() # save IJ.run(imp_diff_sd, "Gaussian Blur...", "sigma=5"); output_file = filename+"--sd.tif" IJ.saveAs(imp_diff_sd, "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "SD","IMG") IJ.run(imp_diff_sd, "Enhance Contrast", "saturated=0.35"); IJ.run(imp_diff_sd, "8-bit", ""); IJ.run(imp_diff_sd, "Properties...", "unit=p pixel_width=1 pixel_height=1 voxel_depth=1"); IJ.run(imp_diff_sd, "Auto Local Threshold", "method=Niblack radius=60 parameter_1=2 parameter_2=0 white"); rm = ROIManipulator.getEmptyRm() IJ.run(imp_diff_sd, "Analyze Particles...", "add"); # select N largest Rois diameter_roi = [] for i in range(rm.getCount()): roi = rm.getRoi(i) diameter_roi.append([roi.getFeretsDiameter(), roi]) diameter_roi = sorted(diameter_roi, reverse=True) #print diameter_roi rm.reset() for i in range(min(len(diameter_roi), p["n_rois"])): rm.addRoi(diameter_roi[i][1]) # save output_file = filename+"--rois" ROIManipulator.svRoisToFl(output_folder, output_file, rm.getRoisAsArray()) tbModel.setFileAPth(output_folder, output_file+".zip", iDataSet, "REGIONS","ROI") # # FFT in each region # IJ.run(imp, "Variance...", "radius=2 stack"); output_file = filename+"--beats.tif" IJ.saveAs(imp, "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "BEATS","IMG") n = rm.getCount() for i_roi in range(n): imp_selection = Duplicator().run(imp) rm.select(imp_selection, i_roi) IJ.run(imp_selection, "Clear Outside", "stack"); imp_selection.show() # FFT using Parallel FFTJ transformer = FloatTransformer(imp_selection.getStack()) transformer.fft() imp_fft = transformer.toImagePlus(SpectrumType.FREQUENCY_SPECTRUM) imp_fft.show() # Analyze FFt IJ.run(imp_fft, "Gaussian Blur 3D...", "x=0 y=0 z=1.5"); IJ.run(imp_fft, "Plot Z-axis Profile", ""); output_file = filename+"--Region"+str(i_roi+1)+"--fft.tif" IJ.saveAs(IJ.getImage(), "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "FFT_R"+str(i_roi+1),"IMG") IJ.run(imp_fft, "Select All", ""); rm.addRoi(imp_fft.getRoi()) rm.select(rm.getCount()) rt = ResultsTable() rt = rm.multiMeasure(imp_fft); #print(rt.getColumnHeadings); x = rt.getColumn(rt.getColumnIndex("Mean1")) #rm.runCommand("delete") peak_height_pos = [] x_min = 10 for i in range(x_min,len(x)/2): before = x[i-1] center = x[i] after = x[i+1] if (center>before) and (center>after): peak_height_pos.append([float(x[i]),i]) if len(peak_height_pos)>0: peak_height_pos = sorted(peak_height_pos, reverse=True) n_max = 3 for i_max in range(min(len(peak_height_pos),n_max)): tbModel.setNumVal(round(float(len(x))/float(peak_height_pos[i_max][1]),2), iDataSet, "F"+str(i_max+1)+"_R"+str(i_roi+1)) tbModel.setNumVal(int(peak_height_pos[i_max][0]), iDataSet, "A"+str(i_max+1)+"_R"+str(i_roi+1))
def run_script(): '''Function to be run when this file is used as a script''' selected_mode, img1_in, img2_in = get_setup() if not selected_mode: return corrected_stack = drift.get_corrected_stack((img1_in, img2_in), mode=selected_mode) img1, img2 = tools.stack_to_list_of_imp(corrected_stack) img_ratio = ImageCalculator().run('Divide create', img2, img1) img_ratio.setTitle('Jump-ratio [%s divided by %s]' % (img2.getShortTitle(), img1.getShortTitle()) ) img_ratio.changes = True img_ratio.copyScale(img1_in) img_ratio.show() IJ.run(img_ratio, 'Enhance Contrast', 'saturated=0.35') # We want to optimise the lower displaylimit: minimum = img_ratio.getProcessor().getMin() maximum = img_ratio.getProcessor().getMax() stat = img_ratio.getStatistics(Stats.MEAN + Stats.STD_DEV) mean = stat.mean stdv = stat.stdDev if minimum < mean - stdv: if mean - stdv >= 0: img_ratio.getProcessor().setMinAndMax(mean - stdv, maximum) else: img_ratio.getProcessor().setMinAndMax(0, maximum) img_ratio.updateAndDraw()
IJ.selectWindow("pore_image") IJ.run("Convert Stack to Images"); win = w.getWindow("Blue") win.removeNotify() IJ.selectWindow("Red") IJ.run("16-bit"); red=IJ.getImage() IJ.selectWindow("Green") IJ.run("16-bit") green=IJ.getImage() calc = ImageCalculator() calc.calculate("Add create", red,green); IJ.run("Subtract Background...", "rolling=50"); IJ.run("LoG 3D"); imp = IJ.getImage() pix = imp.getProcessor().convertToFloat().getPixels() # find out the minimal pixel value min = reduce(Math.min, pix) # create a new pixel array with the minimal value subtracted pix2 = map(lambda x: x - min, pix) name="log"
binner.run(ip) binner.setup("fill", None) binner.run(ip) EDM().toEDM(ip) segip = MaximumFinder().findMaxima( ip, 10, ImageProcessor.NO_THRESHOLD, MaximumFinder.SEGMENTED , False, False) #imp.show() segimp = ImagePlus("regions", segip) segimp.show() segimps, info, perRegionlist = getNucLabels(segimp) segimps.show() numregions = len(perRegionlist) print numregions ic = ImageCalculator() stack = ImageStack(impcentSeg.getWidth(), impcentSeg.getHeight()) for amask in perRegionlist: masked = ic.run("AND create", amask, impcentSeg) stack.addSlice(masked.getProcessor()) regionedimp = ImagePlus("regioned", stack) #regionedimp.show() resrt = ResultsTable() for i in range(regionedimp.getStackSize()): aregion = regionedimp.getStack().getProcessor(i+1) particleAnalysis(i, ImagePlus("extract", aregion), resrt) #resrt.show("data") rm = RoiManager()
def startTracking(filepath, fdir, ffile, filename): outpath = fdir troutpath = fdir + separator + ffile + separator + "tracked" + separator stackoutpath = fdir + separator + ffile + separator + "stacks" + separator pixwidth = 0.647 interval_sec = 600 #pr if "141006" in fdir: interval_sec = 600 elif "141117" in fdir: interval_sec = 300 elif "141215" in fdir: interval_sec = 300 if not os.path.isdir(outpath): os.mkdir(outpath) if not os.path.isdir(troutpath): os.mkdir(troutpath) if not os.path.isdir(stackoutpath): os.mkdir(stackoutpath) print 'filepath: ', filepath #pr print 'fdir: ', fdir #pr print 'ffile: ', ffile #pr IJ.run("Image Sequence...", "open=" + filepath + " file=" + filename + " sort") #pr #IJ.run("Image Sequence...", "open=" + filepath + " file=molm sort"); #pr imp = WindowManager.getCurrentImage() imptitle = imp.getTitle() nframes = imp.getNSlices() IJ.run( imp, "Properties...", "channels=1 slices=1 frames=" + str(nframes) + " unit=inch pixel_width=" + str(pixwidth) + " pixel_height=" + str(pixwidth) + " voxel_depth=1.0000 frame=[" + str(interval_sec) + " sec]") IJ.run(imp, "Duplicate...", "title=" + imptitle + "_dup duplicate") imp_dup = WindowManager.getImage(imptitle + "_dup") IJ.run(imp_dup, "Gaussian Blur...", "sigma=50 stack") ic = ImageCalculator() imp_corr = ic.run("Divide create 32-bit stack", imp, imp_dup) imp_corr.setTitle(imptitle + "_corrected") imp_corr.show() imp.changes = False imp.close() imp_dup.changes = False imp_dup.close() IJ.run(imp_corr, "8-bit", "") IJ.run( imp_corr, "Normalize Local Contrast", "block_radius_x=100 block_radius_y=100 standard_deviations=1 stretch stack" ) IJ.saveAs(imp_corr, "Tiff", stackoutpath + separator + imptitle + "_corrected.tif") IJ.run(imp_corr, "Duplicate...", "title=" + imptitle + "_bg duplicate") imp_bg = WindowManager.getImage(imptitle + "_bg") #Prefs.blackBackground = True; IJ.setAutoThreshold(imp_bg, "MinError dark") IJ.run(imp_bg, "Convert to Mask", "stack") IJ.run(imp_bg, "Analyze Particles...", "size=10000-Infinity show=Masks stack") imp_bg.changes = False imp_bg.close() imp_bgmask = WindowManager.getImage("Mask of " + imptitle + "_bg") ic = ImageCalculator() imp_corr_wobg = ic.run("Subtract create stack", imp_corr, imp_bgmask) imp_corr_wobg.setTitle(imptitle + "_corrected_womask") imp_corr_wobg.show() IJ.saveAs(imp_corr_wobg, "Tiff", stackoutpath + separator + imptitle + "_corrected_womask.tif") #pr # pr: substract average frames zp = ZProjector(imp_corr_wobg) zp.setMethod(ZProjector.AVG_METHOD) zp.doProjection() zpimp = zp.getProjection() zpimp.show() imp_corr_wobg_sub = ImageCalculator().run("Subtract create stack", imp_corr_wobg, zpimp) imp_corr_wobg_sub.show() #imp_corr_wobg.changes = False #imp_corr_wobg.close() # pr: subtract average frames (END) IJ.saveAs( imp_corr_wobg_sub, "Tiff", stackoutpath + separator + imptitle + "_corrected_womask_substracted.tif") #pr IJ.saveAs( zpimp, "Tiff", stackoutpath + separator + imptitle + "_corrected_womask_avg.tif") #commented out: pr #IJ.saveAs(imp_corr_wobg, "Tiff", stackoutpath+separator+imptitle+"_corrected_womask.tif"); IJ.saveAs(imp_bgmask, "Tiff", stackoutpath + separator + imptitle + "_bgmask.tif") print(stackoutpath + separator + imptitle + "_corrected_womask_substracted.tif") print(stackoutpath + separator + imptitle + "_corrected_womask_avg.tif") print(stackoutpath + separator + imptitle + "_bgmask.tif") imp_corr.changes = False imp_corr.close() imp_bgmask.changes = False imp_bgmask.close() imp_corr_wobg.changes = False imp_corr_wobg.close() #imp_corr_wobg_sub.changes = False #imp_corr_wobg_sub.close() zpimp.changes = False zpimp.close() #IJ.log(System.getProperty("os.name")) #IJ.log(fdir) return imp_corr_wobg_sub
# Example 1: with ImageCalculator from ij.process import ImageProcessor from ij.plugin import ChannelSplitter, ImageCalculator # Split color channels red, green, blue = ChannelSplitter().split(imp_rgb) # 3 ImagePlus # Set threshold for each slice for index in xrange(1, red.getNSlices() + 1): bp = red.getStack().getProcessor(index) #bp.setThreshold(threshold, 255, ImageProcessor.BLACK_AND_WHITE_LUT) bp.threshold(threshold) # mask is 0, background is 255 # Apply threshold: convert each slice to a mask (only 0 or 255 pixel values) #IJ.run(red, "Convert to Mask", "method=Default background=Dark black") red.show() green_under_red_mask = ImageCalculator().run("and create stack", red, green) green_under_red_mask.show() """ # Example 2: with ImgLib2 LoopBuilder from net.imglib2.img.display.imagej import ImageJFunctions as IL from net.imglib2.converter import Converters from net.imglib2.img.array import ArrayImgs from net.imglib2.util import Intervals from net.imglib2.loops import LoopBuilder img = IL.wrap(imp_rgb) # an ARGBType Img red = Converters.argbChannel(img, 1) # a view of the ARGB red channel green = Converters.argbChannel(img, 2) # a view of the ARGB green channel img_sub = ArrayImgs.unsignedBytes(Intervals.dimensionsAsLongArray(img)) # the img to store the result
image_orig.show() directory = os.path.dirname(str(srcFile)) #directory = image.getFileInfo() print(directory) #IJ.run(image, "Duplicate...", "duplicate") #image_orig = IJ.getImage() #IJ.run(image, "Convert to Mask", "method=Default background=Default calculate black"); for i in range(erosions): IJ.run(image, "Erode", "stack") for i in range(erosions): IJ.run(image, "Dilate", "stack") calc = ImageCalculator() print(image, image_orig) result = calc.run("Subtract create stack", image_orig, image) #IJ.run(result, "Invert", "stack") result.show() image.changes = False image.close() image_orig.close() IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") IJ.run( result, "Analyze Particles...", "size=" + str(min_size) + "-Infinity show=Masks display clear add stack") #result.close()
def ReturnColorThresholdedPicture(PICPATH, L_min, L_max, a_min, a_max, b_min, b_max): imp = IJ.openImage(PICPATH) imp.show() ImageTitle = imp.getTitle() LabThresold_List = [[L_min, L_max], [a_min, a_max], [b_min, b_max]] Filt_List = ["pass", "pass", "pass"] ColorThresholder.RGBtoLab() IJ.run(imp, "RGB Stack", "") IJ.run("Stack to Images", "") IJ.selectWindow("Red") IJ.run('Rename...', 'title=0') #title=hoge =(equal)の間にスペースを入れてならない。 imp0 = IJ.getImage() IJ.selectWindow("Green") IJ.run('Rename...', 'title=1') imp1 = IJ.getImage() IJ.selectWindow("Blue") IJ.run('Rename...', 'title=2') imp2 = IJ.getImage() for i in range(3): WindowTitle = str(i) MinValue = float(LabThresold_List[i][0]) MaxValue = float(LabThresold_List[i][1]) IJ.selectWindow(WindowTitle) IJ.setThreshold(MinValue, MaxValue) IJ.run(IJ.getImage(), "Convert to Mask", "") if Filt_List[i] == "stop": ImageProcessor.invert() #コメントアウトした、imgculcは動かなくなくなった,謎 #imp3 = ImageCalculator.run(imp0, imp1, "and create") #imp4 = ImageCalculator.run(imp3,imp2, "and create") imp3 = ImageCalculator().run("and create", imp0, imp1) imp4 = ImageCalculator().run("and create", imp3, imp2) imp3.show() imp4.show() ResultTitle = imp4.getTitle() IJ.selectWindow(ResultTitle) imp4.setTitle(ImageTitle) #Saveした時点で画像の情報が失われる. imp.close() imp0.close() imp1.close() imp2.close() imp3.close() return imp4
import os from ij import IJ # we will need this to read in files among other things. from ij import WindowManager as wm from ij.plugin import ImageCalculator # create an instance of image calculator so we can use it in dot notation ic = ImageCalculator() in_folder = "E:/DataBinge_ImageJ/ImageJ DB/5 files tiff - Copy/" out_folder = "E:/DataBinge_ImageJ/ImageJ DB/Claire Output/" the_files = os.listdir(in_folder) print(the_files) the_file = the_files[0] print(the_file) # open the_file inside in_folder. dat = IJ.open( in_folder + the_file ) # Note that strings (string = "stuff") are joined by concatenation # select the active window imp = IJ.getImage() # use the same renaming trick as for the macro recorder imp.setTitle("current") # IJ.run executes commands from the macro recorder
from ij import IJ; from ij.plugin import ImageCalculator; imp1 = IJ.getImage(); imp2 = imp1.duplicate(); IJ.run(imp2, "Minimum...", "radius=10"); IJ.run(imp2, "Maximum...", "radius=10"); ic = ImageCalculator(); imp3 = ic.run("Subtract create", imp1, imp2); imp3.show();