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 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
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 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 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 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 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 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 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 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 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(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 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 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 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 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 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
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 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)
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
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 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
IJ.run(impa, "Montage to Stack...", "images_per_row=1 images_per_column=%d border=0" % imp2.height) impb = IJ.getImage() IJ.run("Reslice [/]...", "output=1.000 start=Left avoid") impc = IJ.getImage() impa.close() impb.close() #calculating albedo IJ.run("Z Project...", "projection=[Max Intensity]") impd = IJ.getImage() impd.setTitle("albedo") #calculating normals N = ImageCalculator().run("Divide create 32-bit stack", impc, impd) N.show() #IJ.run("Rotate 90 Degrees Right") #IJ.run("Flip Horizontally", "stack") impf = IJ.getImage() impf.setTitle("32 bit Surface Normal Map") #converting to 8 bit color image IJ.run("Duplicate...", "duplicate") IJ.run("8-bit") impe = IJ.getImage() impe.changes = False IJ.run("Stack to RGB") impg = IJ.getImage() impg.setTitle("8 bit Surface Normal Map")
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 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)
# 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
#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: