Beispiel #1
0
def main():
  if IJ.isResultsWindow():
    IJ.selectWindow("Results")
    IJ.run("Close")
  if (WindowManager.getImageCount() > 0):
    #IJ.run("Save")
    Commands.closeAll()

  selected_dir = str(myDir)
  if not selected_dir.endswith(os.path.sep):
    selected_dir = selected_dir + os.path.sep
  dir_list = list()
  file_type = "stitched_images"
  if selected_dir.endswith(file_type + os.path.sep):
    dir_list.append(selected_dir)
    #print(dir_list)
  else:
    dir_list = listDir(selected_dir, file_type, recursive = True)
#  print(dir_list)

  if len(dir_list) > 0:
    for dir in dir_list:
      image_list = listDir(dir, file_type = ".tiff", recursive = False)
      remove_marker_dir(dir)
      for image in image_list:
        IJ.open(image)
        processImage()
  else:
    image_list = listDir(selected_dir, file_type = ".tiff", recursive = False)
    remove_marker_dir(selected_dir)
    for image in image_list:
      IJ.open(image)
      processImage()
def run(in_dir, ou_dir, extension, minimum, maximum):
    extension = extension.strip()
    extension = "*" + extension

    for path in glob(os.path.join(in_dir, '*.tif')):
        print path + ':',
        IJ.open(path)
        imp = IJ.getImage()
        minima = [x.strip() for x in ch_min.split(';')]
        maxima = [x.strip() for x in ch_max.split(';')]
        for c in range(0, imp.getNChannels()):
            imp.setC(c + 1)
            ip = imp.getProcessor()
            stats = ip.getStats()
            M = 2**ip.getBitDepth()
            if minima[c] == '-1':
                mi = stats.min
            else:
                mi = Double.parseDouble(minima[c])
            if maxima[c] == '-1':
                ma = stats.max
            else:
                ma = Double.parseDouble(maxima[c])
            scale = M / (ma - mi)
            ip.subtract(mi)
            ip.multiply(scale)
            print ' ch' + str(c) + '=[' + str(mi) + ' ... ' + str(ma) + ']',

        print ' '
        IJ.run('Make Composite')
        IJ.run('RGB Color')
        IJ.run('Save',
               'save=[' + os.path.join(ou_dir, os.path.basename(path)) + ']')
        IJ.run('Close All')
Beispiel #3
0
def run_it():
    #Runs microscope_check and defines the scanList accordingly
    microscopeType = microscope_check(experimentFolder)

    # Call list_scans and pass it the microscopeType variable. Gets the scanList
    if microscopeType == "Olympus":
        scanList = list_scans(experimentFolder, microscopeType)
        print "The returned scanList is", len(scanList), "item(s) long"

    elif microscopeType == "Bruker":
        scanList = list_scans(experimentFolder, microscopeType)
        print "The returned scanList is", len(scanList), "item(s) long"

    # For each scan in the scanList, call the following functions
    for scan in scanList:
        directories = define_directories(scan)  # get paths to the directories
        basename = os.path.basename(scan)  # get the scan name (basename)
        print "Opening " + basename
        files = os.listdir(
            directories[4]
        )  # makes a list of all the files in rawMAX directory
        for f in files:  # finds the MAX projections and only opens them (skips merged)
            if fnmatch.fnmatch(
                    f, myChoice
            ):  #finds whatever string you specify in the param box
                IJ.open(os.path.join(directories[4], f))
                IJ.run("Out [-]", f)  #zoom out one level
Beispiel #4
0
def run():

    # ensure no other windows are open and clear resultstable
    IJ.run("Close All")
    IJ.run("Clear Results", "")
    #Ask user for file to be converted
    srcDir = IJ.getFilePath("Select file to analyse")
    if not srcDir:
        return

    #open file
    IJ.open(srcDir)
    dstDir = os.path.dirname(srcDir)
    print("dstDir = " + dstDir)
    #open ROI manager, save ROI names as labels in measurements
    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()
    rm.runCommand("UseNames", "true")

    # set parameters to be measured
    IJ.run("Set Measurements...",
           "area mean integrated limit display redirect=None decimal=3")

    FOVlist = WindowManager.getIDList()
    chnls = IJ.getString(
        "Please enter which channels you would like to analyse. Example: 123 analyses channels 1, 2 and 3",
        '123')

    for FOV in FOVlist:
        imp = WindowManager.getImage(FOV)
        IJ.run(imp, "Arrange Channels...", "new=" + chnls)
        imp.close()
        imp2 = WindowManager.getCurrentImage()

        imageTitle = WindowManager.getImage(FOV).getTitle()
        newDir = imageTitle + ' ROIs'

        dirPath = os.path.join(dstDir, newDir)

        if not os.path.exists(dirPath):
            try:
                os.makedirs(dirPath)
            except OSError as e:
                if e.errno != errno.EEXIST:
                    raise
        # clear ROI list before analysis
        rm.runCommand(imp2, "Deselect")
        rm.runCommand(imp2, "Delete")

        TMdata, nFrames = runTrackMate(imp2)
        if TMdata:
            iterateCoords(TMdata, nFrames, dirPath, imp2)
        imp2.changes = 0
        imp2.close()
    #relabel()
    resultsDir = os.path.splitext(srcDir)[0] + ".csv"
    #while os.path.exists(resultsDir):
    #resultsDir = resultsDir+"_1"+".csv"
    IJ.saveAs("Results", resultsDir)
def run():
    roidir = '/Volumes/TRANSCEND/LauraLeopold/Rois/'
    maskdir = '/Volumes/TRANSCEND/LauraLeopold/Mask/'
    originaldir = '/Volumes/TRANSCEND/LauraLeopold/Original/'
    Raw_path = os.path.join(originaldir, '*tif')
    X = glob.glob(Raw_path)
    axes = 'YX'
    for fname in X:
        print(fname)
        IJ.open(fname)
        imp = IJ.getImage()
        Name = os.path.basename(os.path.splitext(fname)[0])
        RoiName = roidir + Name + '.roi'
        Roi = IJ.open(RoiName)
        rm = RoiManager.getInstance()
        if (rm == None):
            rm = RoiManager()
        rm.addRoi(Roi)
        print(fname, RoiName)
        if not rm:
            print "Please first add some ROIs to the ROI Manager"
            return
        impMask = IJ.createImage("Mask", "8-bit grayscale-mode",
                                 imp.getWidth(), imp.getHeight(),
                                 imp.getNChannels(), imp.getNSlices(),
                                 imp.getNFrames())
        IJ.setForegroundColor(255, 255, 255)
        rm.runCommand(impMask, "Deselect")
        rm.runCommand(impMask, "Fill")
        rm.runCommand('Delete')
        IJ.saveAs(impMask, '.tif', maskdir + Name)
        imp.close()
Beispiel #6
0
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();
Beispiel #7
0
def straighten(stackName):
    '''
    IJ.run("Set Measurements...", "area mean min center redirect=None decimal=3")
    IJ.open(stackName)
    imp = IJ.getImage()
    stack = imp.getImageStack()

    for i in xrange(1, imp.getNSlices()+1):
        image = ImagePlus(str(i), stack.getProcessor(i))
        xvals = []
        yvals = []
        maxvals = []
        j = 0

        for k in xrange(0, 512, 2):
            IJ.makeRectangle(k, 0, 4, 512)
            IJ.run("Measure")
            table = RT.getResultsTable()

            x = table.getValue("XM", 0)
            y = table.getValue("YM", 0)
            #maxi = IJ.getResult("Max")
            table = []

            xvals.append(k)
            yvals.append(y)
            #maxvals.append(maxi)

            #if maxvals[j] == 0 and j > 0:
                #yvals[j] = yvals[j-1]

            j += 1

        print "xvals:", xvals
        print "yvals:", yvals
        mr = MR()
        IJ.run("Make Selection...", "freeline, "+str(xvals)+" ,"+ str(yvals))

        #IJ.runMacro("makeSelection...", "freeline, "+str(xvals)+" ,"+ str(yvals));

        #IJ.run("makeSelection(\"freeline\", xvals, yvals);")
        #IJ.run("Straighten...", "line = 80")
    '''
    IJ.open(stackName)
    imp = IJ.getImage()
    stack = imp.getImageStack()
    print imp.getNSlices()
    for i in range(1, imp.getNSlices() + 1):
        image = ImagePlus(str(i), stack.getProcessor(i))
        IJ.runMacroFile(
            "/Users/juliansegert/repos/Bio119_root_tracking/straightenOneImage.ijm"
        )
        newImp = WM.getCurrentImage()
        fs = FileSaver(newImp)
        fs.saveAsTiff(
            "/Users/juliansegert/Documents/Roots/Four_root_image_stacks/Pos01/"
            + str(i) + ".tif")
        newImp.close()
Beispiel #8
0
def openAtFolder(event):
    if 0 == path.getText().find("http"):
        IJ.showMessage("Can't open folder: it's an URL")
        return
    directory = os.path.dirname(path.getText())
    od = OpenDialog("Open", directory, None)
    filepath = od.getPath()
    if filepath:
        IJ.open(filepath)
def straighten(stackName):
    '''
    IJ.run("Set Measurements...", "area mean min center redirect=None decimal=3")
    IJ.open(stackName)
    imp = IJ.getImage()
    stack = imp.getImageStack()

    for i in xrange(1, imp.getNSlices()+1):
        image = ImagePlus(str(i), stack.getProcessor(i))
        xvals = []
        yvals = []
        maxvals = []
        j = 0

        for k in xrange(0, 512, 2):
            IJ.makeRectangle(k, 0, 4, 512)
            IJ.run("Measure")
            table = RT.getResultsTable()

            x = table.getValue("XM", 0)
            y = table.getValue("YM", 0)
            #maxi = IJ.getResult("Max")
            table = []

            xvals.append(k)
            yvals.append(y)
            #maxvals.append(maxi)

            #if maxvals[j] == 0 and j > 0:
                #yvals[j] = yvals[j-1]

            j += 1

        print "xvals:", xvals
        print "yvals:", yvals
        mr = MR()
        IJ.run("Make Selection...", "freeline, "+str(xvals)+" ,"+ str(yvals))

        #IJ.runMacro("makeSelection...", "freeline, "+str(xvals)+" ,"+ str(yvals));

        #IJ.run("makeSelection(\"freeline\", xvals, yvals);")
        #IJ.run("Straighten...", "line = 80")
    '''
    IJ.open(stackName)
    imp = IJ.getImage()
    stack = imp.getImageStack()
    print imp.getNSlices()
    for i in range(1, imp.getNSlices()+1):
        image = ImagePlus(str(i), stack.getProcessor(i))
        IJ.runMacroFile("/Users/juliansegert/repos/Bio119_root_tracking/straightenOneImage.ijm")
        newImp = WM.getCurrentImage()
    	fs = FileSaver(newImp)
    	fs.saveAsTiff("/Users/juliansegert/Documents/Roots/Four_root_image_stacks/Pos01/"+str(i)+".tif")
    	newImp.close()    
Beispiel #10
0
 def openImage():
   print rel_path
   if rel_path.endswith(".klb"):
     try:
       klb = KLB.newInstance()
       img = klb.readFull(os.path.join(base_path, rel_path))
       IL.wrap(img, rel_path).show()
     except:
       print sys.exc_info()
   else:
     print "via IJ.open"
     IJ.open(os.path.join(base_path, rel_path))
Beispiel #11
0
def process(root, f):
    print(f)
    full_path = os.path.join(root, f)
    dest_path = os.path.join(root, "tmp", f)
    if not os.path.isdir(os.path.join(root, "tmp")):
        os.makedirs(os.path.join(root, "tmp"))
    
    IJ.open(full_path)
    imp = IJ.getImage()
    
    IJ.run("Properties...", "frame=5")
    IJ.run("Bio-Formats Exporter", "save=" + dest_path + " compression=Uncompressed")
    imp.close()
Beispiel #12
0
def make_tmp_tifs(images, tmp_dir, copy=False):
    file_pattern = '{i}.tif'
    files = []
    for i, image in enumerate(images):
        files += [tmp_dir + '/%d.tif' % i]
        if copy:
            from ij import IJ
            IJ.open(os.path.abspath(image))
            IJ.saveAs("Tiff", files[-1])
            IJ.run("Close All")
        else:
            force_symlink(os.path.abspath(image), files[-1])

    return files, file_pattern
Beispiel #13
0
 def openImage():
     print rel_path
     if rel_path.endswith(".klb"):
         if (KLB == None):
             print "Cannot open KLB due to missing module"
         try:
             klb = KLB.newInstance()
             img = klb.readFull(os.path.join(base_path, rel_path))
             IL.wrap(img, rel_path).show()
         except:
             print sys.exc_info()
     else:
         print "via IJ.open"
         IJ.open(os.path.join(base_path, rel_path))
Beispiel #14
0
def main():
    if (WindowManager.getImageCount() > 0):
        IJ.run("Save")
        processImage()


#  if (WindowManager.getImageCount() > 0):
#    for image in range(WindowManager.getImageCount()):
#      processImage()
    else:
        selected_dir = str(myDir)
        if not selected_dir.endswith(os.path.sep):
            selected_dir = selected_dir + os.path.sep
        dir_list = list()
        file_type = "stitched_images"

        if selected_dir.endswith(file_type + os.path.sep):
            dir_list.append(selected_dir)
            #print(dir_list)
        else:
            dir_list = listDir(selected_dir, file_type, recursive=True)
        print(dir_list)
        if len(dir_list) > 0:
            for dir in dir_list:
                genotype_dirs = list()
                filenames = os.listdir(dir)
                for filename in filenames:
                    if os.path.isdir(
                            os.path.join(os.path.abspath(dir), filename)):
                        genotype_dirs.append(
                            os.path.join(os.path.abspath(dir), filename))
                for genotype_dir in genotype_dirs:
                    java.lang.System.gc()
                    java.lang.System.gc()
                    java.lang.System.gc()
                    image_list = listDir(genotype_dir,
                                         file_type=".tiff",
                                         recursive=False)
                    remove_marker_dir(genotype_dir)
                    for image in image_list:
                        IJ.open(image)
                        processImage()
        else:
            image_list = listDir(selected_dir,
                                 file_type=".tiff",
                                 recursive=False)
            remove_marker_dir(selected_dir)
            for image in image_list:
                IJ.open(image)
                processImage()
Beispiel #15
0
def openedImagesmain(channel1, channel2, ignoreString, primarySize,
                     primaryImageThresh, secondaryImageThresh):
    def writeTablesToCSV(id, roiOut, speckleOut):
        try:
            #append your labels to them before they're written
            identifier = id[:-4]
            speckleOut_ = RTC.appendColToFront(identifier, speckleOut)
            roiOut_ = RTC.appendColToFront(identifier, roiOut)
            #save the tables to csvs -- they will append to a currently existing csv
            #or create a new one
            Saves.table2CSV("speckleOutput.csv", speckleOut_)
            Saves.table2CSV("AnalysisOutput.csv", roiOut_)
            print("finished writing tables to csvs.")
        except:
            print("failed to write to csvs.")
        finally:
            print("")

    #Begin
    try:
        RTC = ResultsTableToCSV(channel1, channel2, ignoreString)
        primary, secondary, images = RTC.getOpenImageNames()
        Binarize(primaryImageThresh, secondaryImageThresh, primary, secondary)
        speckleInputs = "primary=[{}] secondary=[{}] " \
           "redirect=None min_primary_size={} min_secondary_size=0.00000 " \
           "show=none exclude speckle statistic secondary_object"
        IJ.run("Speckle Inspector",
               speckleInputs.format(primary, secondary, primarySize))

        Saves = SaveStuff(primary)
        Saves.saveLogs()
        #Saves.saveNewImages(images)
        Saves.saveAllImages(images)

        speckleTableName = "Speckle List " + primary
        roiTableName = "Roi Analysis"

        roiOut = RTC.roiAnalysisToWrite(roiTableName)
        speckleOut = RTC.readResultsTablesOfNumbers(speckleTableName)
        WindowManager.closeAllWindows()
        fijiDir = IJ.getDir("imagej")
        fijiScriptsDir = join(fijiDir, "scripts")
        writeTablesToCSV(primary, roiOut, speckleOut)
        IJ.open(join(fijiScriptsDir, "SmootherSpeckling.py"))
        print("script completed successfully.")
    except:
        print("sorry, the script broke :/")
    finally:
        print("")
Beispiel #16
0
def executePairRegistration(prefix, tp, matrix):
    saveMatrixForTransformJ(matrix)
    infile = prefix + "_" + tp + ".tif"
    outfile = "reg_%s_%s.tif" % (prefix, tp)

    IJ.open(output_dir + infile)

    IJ.run(
        "TransformJ Affine", "matrix=" + output_dir +
        "TransformJ_matrix.txt interpolation=linear background=0.0")
    IJ.run("Save", "save=" + output_dir + outfile)
    while IJ.macroRunning():
        Thread.sleep(100)
    WindowManager.getWindow(infile).close()
    WindowManager.getWindow(outfile).close()
Beispiel #17
0
 def leafDoubleClicked(self, fileOb):
   name = fileOb.getName()
   idot = name.rfind('.')
   if -1 == idot:
     print "File name lacks extension"
     return
   # Open depending on what it is  
   extension = name[idot+1:].lower() # in lowercase
   languages = set(["py", "clj", "js", "java", "bs", "ijm", "r", "rb", "sc", "txt", "md"])
   if extension in languages:
     self.texteditor.open(fileOb)
   else:
     # Let ImageJ handle it
     print "Asking ImageJ to open file", fileOb
     IJ.open(fileOb.getAbsolutePath())
Beispiel #18
0
def split_channels_blue(imp):
    #Create blue channel
    original_blue = ChannelSplitter.getChannel(imp, 3)
    original_blue_IP = ImagePlus(filename, original_blue)
    fs = FileSaver(original_blue_IP)
    folder = "/Users/gceleste/Desktop/test/channels"
    filepath = folder + "/" + "{}_bluechannel.tif".format(filename)
    fs.saveAsTiff(filepath)
    #Open blue channel image.
    blue = IJ.open(filepath)
    #blue_IP = ImagePlus(filename, blue)
    IJ.run(
        "3D Objects Counter",
        "threshold=100 slice=1 min.=50 max.=1447680 exclude_objects_on_edges objects summary"
    )
    #Save blue object map
    blue_map = IJ.getImage()
    fs = FileSaver(blue_map)
    folder = "/Users/gceleste/Desktop/test/object maps"
    filepath = folder + "/" + "{}_objectmap(blue).jpg".format(filename)
    fs.saveAsJpeg(filepath)
    #Close blue channel image.
    blue_map.close()
    blue = IJ.getImage()
    blue.close()
def getCompositeImgs():
	BF, PI, filepath = getImgs()
	for i in range(len(BF)):
		IJ.open(filepath + '/' + PI[i])
		IJ.run('Auto Threshold', 'method=Yen ignore_black white')
		IJ.open(filepath + '/' + BF[i])
		IJ.run('8-bit')
		IJ.run('Merge Channels...', 'c1=%s c4=%s create'%(PI[i], BF[i]))
		IJ.run('Flatten')
		if 'processed' not in os.listdir(filepath):
			os.mkdir(filepath + '/processed/')
		name = BF[i].split('bf')
		IJ.saveAs('Tiff', filepath + '/processed/' + name[0] + '_COMPOSITE_' + name[1])
		IJ.run('Close')
		print '[+] Processed image: %s' %(name[0] + '_COMPOSITE_' + name[1])
	return 0
Beispiel #20
0
def split_channels_red(imp):
    #Create red channel
    original_red = ChannelSplitter.getChannel(imp, 1)
    original_red_IP = ImagePlus(filename, original_red)
    fs = FileSaver(original_red_IP)
    folder = "/Users/gceleste/Desktop/test/channels"
    filepath = folder + "/" + "{}_redchannel.tif".format(filename)
    fs.saveAsTiff(filepath)
    #Open red channel image.
    red = IJ.open(filepath)
    #red_IP = ImagePlus(filename, red)
    IJ.run(
        "3D Objects Counter",
        "threshold=130 slice=1 min.=50 max.=1447680 exclude_objects_on_edges objects summary"
    )
    #Save red object map.
    red_map = IJ.getImage()
    fs = FileSaver(red_map)
    folder = "/Users/gceleste/Desktop/test/object maps"
    filepath = folder + "/" + "{}_objectmap(red).jpg".format(filename)
    fs.saveAsJpeg(filepath)
    #Close red channel images.
    red_map.close()
    red = IJ.getImage()
    red.close()
def pairwise_stitching(tiff_1, tiff_2, temp_dir):
	IJ.open(tiff_1)
	tiff_1_title = os.path.basename(tiff_1)
	IJ.open(tiff_2)
	tiff_2_title = os.path.basename(tiff_2)
	new_fused_image = "" + tiff_1_title.split("_")[0] + "-" + tiff_2_title.split("_")[0] + "_.tiff"

	IJ.run("Pairwise stitching", "first_image=" + tiff_1_title +  " second_image=" + tiff_2_title + " fusion_method=[Linear Blending] fused_image=" + new_fused_image + " check_peaks=1 compute_overlap x=0.0000 y=0.0000 z=0.0000 registration_channel_image_1=[Average all channels] registration_channel_image_2=[Average all channels]")
	IJ.selectWindow(tiff_1_title)
	IJ.run("Close")
	os.remove(tiff_1)
	IJ.selectWindow(tiff_2_title)
	IJ.run("Close")
	os.remove(tiff_2)
	IJ.selectWindow(new_fused_image)
	imp = IJ.getImage()
	IJ.saveAsTiff(imp, os.path.join(temp_dir, new_fused_image))
	imp.close()
Beispiel #22
0
 def mousePressed(self, event):
     if 2 == event.getClickCount():
         # If the file is open, bring it to the front
         ids = WindowManager.getIDList()
         if ids:  # can be null
             is_open = False  # to allow bringing to front more than one window
             # in cases where it has been opened more than once
             for ID in ids:
                 imp = WindowManager.getImage(ID)
                 fi = imp.getOriginalFileInfo()
                 filepath = os.path.join(fi.directory, fi.fileName)
                 if File(filepath).equals(File(
                         event.getSource().getText())):
                     imp.getWindow().toFront()
                     is_open = True
             if is_open:
                 return
         # otherwise open it
         IJ.open(table_entries[getSelectedRowIndex()][-2])
def preparePairRegistration(tpA, tpB):
    fileA = "raw_" + tpA + ".tif"
    fileB = "raw_" + tpB + ".tif"

    IJ.open(output_dir + fileA)
    IJ.open(output_dir + fileB)

    IJ.run(
        "Rigid Registration",
        "initialtransform=[] n=1 tolerance=1.000 level=5 stoplevel=2 materialcenterandbbox=[] "
        + "template=%s measure=Euclidean" % (fileA))
    IJ.selectWindow("Matrix")
    IJ.saveAs("Text",
              "/Users/jug/MPI/ProjectNorden/output/matrix_%s.txt" % (tpB))
    window = WindowManager.getWindow("Matrix")
    window.close()
    window = WindowManager.getWindow(output_dir + fileA)
    window.close()
    window = WindowManager.getWindow(output_dir + fileB)
    window.close()
def main():
	
	
	IJ.open(dir_path+file_name) #IJ.open("/Users/richardhart/Dropbox/AMRE/2013-08-03-96dpiPrintTesting-DifferentZheights-Sample.png")
	
	IJ.selectWindow(file_name) #IJ.selectWindow("2013-08-03-96dpiPrintTesting-DifferentZheights-Sample.png")
	
	IJ.run("Options...", "iterations=1 count=1 edm=Overwrite") #setting binary mask options
	
	IJ.run("Make Binary") #converting a picture o a binary image. 

	IJ.run("Watershed")	#Watershed breaks appart blobs in a binary image into smaller pieces
	
	IJ.run("Set Measurements...", "area mean standard modal min centroid center perimeter bounding fit shape feret's integrated median skewness kurtosis area_fraction stack redirect=None decimal=3") #Specifying what measurements to take 
	
	IJ.run("Analyze Particles...", "size=0-Infinity circularity=0.00-1.00 show=Ellipses display clear include") #taking measurements
	
	IJ.selectWindow("Results") #Making sure the results are selected so the window's data will be saved
	
	IJ.saveAs("Results", dir_path + "Results.txt"); #IJ.saveAs("/Users/richardhart/Dropbox/AMRE/Results.txt")
Beispiel #25
0
def runThunderSTORM(filename):
    # ---------------------------------------------
    # Runs the ThunderSTORM plugin on the filename
    # provided with the settings from the top of
    # this file.
    # ---------------------------------------------
    global exportList
    if virtualStack:
        IJ.openVirtual(filename)
    else:
        IJ.open(filename)
    IJ.run(stormAnalysisCmd, stormAnalysisParams)
    dataStoreFilename = os.path.dirname(filename) + os.sep + os.path.splitext(
        os.path.basename(filename))[0] + ".csv"
    exportList.append(dataStoreFilename)
    exportParams = stormExportParams.replace("%filename", dataStoreFilename)
    print exportParams
    IJ.run(stormExportCmd, exportParams)
    WindowManager.closeAllWindows()
    return exportList
def run():
    Ch0dir = '/Volumes/TRANSCEND/Claudia/LGR5SegmentationTraining/DeformMask/'
    Ch1dir = '/Volumes/TRANSCEND/Claudia/LGR5SegmentationTraining/DeformMask/'
    DoubleChdir = '/Volumes/TRANSCEND/Claudia/LGR5SegmentationTraining/DeformDoubleChannelMask/'
    Raw_path = os.path.join(Ch0dir, '*tif')
    X = glob.glob(Raw_path)
    axes = 'YX'
    for fname in X:
      print(fname)
      IJ.open(fname);
      imp = IJ.getImage()
      Name = os.path.basename(os.path.splitext(fname)[0])
      Ch1Name = Ch1dir + Name + '.tif'
      IJ.open(Ch1Name);
      impCh1 = IJ.getImage()
      IJ.run("Merge Channels...", "c1="+imp.getTitle()+ " c2="+impCh1.getTitle()+ " create");
      IJ.saveAs('.tif', DoubleChdir +  Name);
      imp.close();
      impCh1.close();
      composite = wm.getFrontWindow()
      if composite is not None: done = composite.close()
Beispiel #27
0
def walkAnalysis(fileList, directory, outpath):
    from ij import IJ, ImagePlus
    from ij.macro import Interpreter as IJ1
    from datetime import datetime
    IJ1.batchMode = True
    current = 0
    pnum = 0
    nooresults = ''
    for files in os.walk(directory, topdown=True):
        for file in fileList:
            drc = ''.join(directory + file)
            cfile = file
            imp = IJ.open(drc)
            IJ.run("16-bit")
            IJ.setThreshold(65409, 65532)
            IJ.run("Subtract Background...", "rolling=" + Roll + " dark")
            ##*LIGHT CONDITIONS MUST BE CONSTANT!!* possibly omit light call in order to bugfix
            IJ.run(imp, "Gaussian Blur...", "sigma=" + SigM)
            IJ.run("Make Binary")
            ##increases contrast and allows watershed
            IJ.run("Watershed")
            dt = str(datetime.now())[:11]
            savestring = out + "mask" + dt + cfile
            IJ.saveAs(imp, "Jpeg", out + "mask" + cfile)
            ##jpeg saveas dramatically decreases process time
            IJ.run("Set Measurements...",
                   "integrated area_fraction redirect=None decimal=" + Dec)
            IJ.run(
                imp, "Analyze Particles...",
                "size=10-Infinity circularity=0.05-1.00 show=[Outlines] display clear include summarize in_situ"
            )
            ##most likely the value will change according to desired cell line
            current += 1  ##current is a counter for images processed, as well as possible naming convention for renaming images.
    numstr = str(current)
    #current is a int class and cannot be concat with a string.
    dt = str(
        datetime.now()
    )[:
      10]  ## this slice truncates the colon that is unacceptable in file naming convention. find an alternative solution if possible.
    results = (out + "Results" + dt + ".csv")
    if os.path.exists(results):
        while os.path.exists(results):
            pnum += 1
            results = (out + "Results" + dt + '-' + str(pnum) + ".csv")
        IJ.saveAs("Results", results)
    else:
        IJ.saveAs("Results", results)
    csvStr = (out + "Results" + dt + ".csv")
    IJ1.batchMode = False
    return numstr, csvStr
Beispiel #28
0
def main():
	#summary = False
	if (WindowManager.getImageCount() > 0):
		IJ.run("Save")
		image_dir = processImage()
#	if (WindowManager.getImageCount() > 0):
#		for image in range(WindowManager.getImageCount()):
#			processImage()
	else:
		#summary = True
		#selected_dir = IJ.getDirectory("Select Directory")
		if not selected_dir.endswith(os.path.sep):
			selected_dir = selected_dir + os.path.sep

		dir_list = list()
		file_type = [".tif", ".tiff"]
		image_list = listDir(selected_dir, file_type = file_type, recursive = False)
		for image in image_list:
			IJ.open(image)
			image_dir = processImage()

	summarize(os.path.join(image_dir, "markers" ))
	summarize(os.path.join(image_dir, "processed_markers"))
Beispiel #29
0
def main(threshold, min_size, max_size, remove_last_slice=False):
    IJ.run(
        "3D OC Options",
        "volume surface nb_of_obj._voxels nb_of_surf._voxels integrated_density mean_gray_value std_dev_gray_value median_gray_value minimum_gray_value maximum_gray_value centroid mean_distance_to_surface std_dev_distance_to_surface median_distance_to_surface centre_of_mass bounding_box dots_size=5 font_size=10 show_numbers white_numbers store_results_within_a_table_named_after_the_image_(macro_friendly) redirect_to=none"
    )
    IJ.run("Set Measurements...", "area mean centroid redirect=None decimal=6")

    Commands.closeAll()
    selected_dir = IJ.getDirectory("Select Directory")
    print(selected_dir)
    selected_dir = selected_dir + "/"
    dir_list = list()
    file_type = "processed_images"

    if selected_dir.endswith(file_type + "/"):
        dir_list.append(selected_dir)
    else:
        dir_list = listDir(selected_dir, file_type, recursive=True)
    print(dir_list)
    for dir in dir_list:
        print(dir)
        cd_dir = dir + "/cd/"
        print(cd_dir)
        makeDir(cd_dir)
        image_list = listDir(dir, file_type=".tiff", recursive=False)
        for i in image_list:
            print(i)
            now = time.time()
            IJ.open(i)
            imp = IJ.getImage()
            IJ.run(imp, "Measure", "")
            saveResults(imp, cd_dir)
            #processImage(imp, threshold, min_size, max_size, remove_last_slice)
            later = time.time()
            difference = int(later - now)
            #time.sleep(difference/10)
            print("The time difference is " + str(difference))
Beispiel #30
0
"""
Start a Trainable Weka Segmmentation

  Modifications
  Date      Who  Ver                       What
----------  --- ------  -------------------------------------------------
2019-05-17  JRM 0.1.00  Start a segmentation

"""
from org.python.core import codecs
codecs.setDefaultEncoding('utf-8')
import os
from ij import IJ, WindowManager

IJ.run("Close All")
"""
# MacOS
str_path = "/Users/jrminter/Documents/git/tips/ImageJ/jpg/aggregates_w_TWS.jpg"
 
"""
# Windows
str_path = "C:/Users/jrminter/Documents/git/tips/ImageJ/jpg/aggregates_w_TWS.jpg"
IJ.open(str_path)
IJ.run("Trainable Weka Segmentation")
Beispiel #31
0
"""
Start a Trainable Weka Segmmentation

  Modifications
  Date      Who  Ver                       What
----------  --- ------  -------------------------------------------------
2019-05-17  JRM 0.1.00  Start a segmentation

"""
from org.python.core import codecs
codecs.setDefaultEncoding('utf-8')
import os
from ij import IJ, WindowManager

IJ.run("Close All")

"""
# MacOS
str_path = "/Users/jrminter/Documents/git/tips/ImageJ/jpg/aggregates_w_TWS.jpg"
 
"""
# Windows
str_path = "C:/Users/jrminter/Documents/git/tips/ImageJ/jpg/aggregates_w_TWS.jpg"
IJ.open(str_path)
IJ.run("Trainable Weka Segmentation")
Beispiel #32
0
def duty_cycle(i, horizontal):
	IJ.open(i)
	IJ.run("Enhance Contrast...", "saturated=0.3 equalize")
	IJ.run("Smooth", "")
	'IJ.run("Anisotropic Diffusion 2D", "number=20 smoothings=1 keep=20 a1=0.50 a2=0.90 dt=20 edge=5")     # use instead of smooth for better results, slower
	imp = IJ.getImage()
	ImageConverter(imp).convertToGray8()
	file_base = str(imp.title)								# convert name into string
	file_base = file_base.split('.', 1)[0]					# remove all characters including and after .
	sample_id = file_base.split('_', 1)[0]
	height = imp.height
	width = imp.width
	IJ.run(imp, "Set Scale...", "distance=5000 known=1 pixel=1 unit=cm")
	IJ.setTool("line")
	for scan in range(1, num_scans):
		row_count = 0
		data=[]
		data2=[]
		last = 0
		filename = file_base + "_" + str(scan)
		
		if not horizontal:
			IJ.makeLine(0, scan*height/num_scans, width, scan*height/num_scans)				# horizontal line to measure vertical grating profile		
		else:
			IJ.makeLine(width*scan/num_scans, 9*height/10, width*scan/num_scans, 0)			# vertical line to measure horizontal grating profile
		
		IJ.run(imp, "Plot Profile", "")
		imp_plot = IJ.getImage()
		IJ.run(imp, "Find Peaks", setting)	# nw07 params: min._peak_amplitude=60 min._peak_distance=0 min._value=100 max._value=0 exclude list
		IJ.saveAs("Results", csvpath + filename + "_raw.csv")
		imp_plot.close()
		imp_plot = IJ.getImage()
		IJ.saveAs("Png", csvpath + "Peaks in Plot of " + filename + ".png")
		imp_plot.close()
		IJ.selectWindow(filename + "_raw.csv")
		IJ.run("Close")
		
		with open(csvpath + filename + "_raw.csv", "rb") as fin, open(csvpath + filename + "_peaks.csv", "wb") as fout:  
		    writer = csv.writer(fout)            
		    for row in csv.reader(fin):
		        if not row[2] == '':
		             writer.writerow(row)

		with open(csvpath + filename + "_peaks.csv", "rb") as File:
		    reader = csv.reader(File)
		    for row in reader:
		        row_count += 1
			if row_count == 1:
				continue
			data.append(tuple(row))								# Append all non-header rows into a list of data as a tuple of cells
		for row in sort_table(data, 2):
			data2.append(tuple(row))
		if len(data2) < 3:
			IJ.log(filename + " no peaks detected, skipping...")
			continue
		else:
			peaks = len(data2)
			last = data2[0]
			last = last[2]
			
			row_count = 0
			diff = 0
			colG = []
			blank = ""
			duty = zip(*data2)
			for row in data2:
				row_count += 1
				if row_count == 1:
					continue
				else:
					print row[2]
					print last
					diff = float(row[2]) - float(last)
					colG.append(diff)
					last = row[2]
			a, b = colG[::2], colG[1::2]
			avga = sum(a)/len(a)
			avgb = sum(b)/len(b)
			a_len_dev = len(a) - 1
			b_len_dev = len(b) - 1
			if b_len_dev > 1:
				a_stdev = sqrt(sum((x - avga)**2 for x in a) / a_len_dev)
				b_stdev = sqrt(sum((x - avgb)**2 for x in b) / b_len_dev)
			else:
				a_stdev = 1
				b_stdev = 1
			
			duty_cyc = avga/(avga+avgb)
			perc = duty_cyc*100
			invperc = 100 - perc
			inv_duty = 1 - duty_cyc
			duty_max = max(duty_cyc, inv_duty)
			duty_min = min(duty_cyc, inv_duty)
			percs = round(perc)
			percs = int(percs)
			percs = str(percs)
			invpercs = round(invperc)
			invpercs = int(invpercs)
			invpercs = str(invpercs)
		
			colG.insert(0, blank)
			a.insert(0, blank)
			b.insert(0, blank)
			b.insert(1, blank)
			
			i = 0
			while i < len(a):
					i += 2
					a.insert(i, blank)
			
			i = 1
			while i < len(b):
					i += 2
					b.insert(i, blank)
			
			duty.append(colG)
			duty.append(a)
			duty.append(b)	
			duty = zip(*duty)
			result = [sample_id, file_base, scan, duty_cyc, inv_duty, a_stdev, b_stdev, peaks, duty_max, duty_min]
			header = ["X0", "Y0", "X1", "Y1", "X2", "Y2", "diff", "a", "b"]
			results.append(result)
			with open(csvpath + filename + "_duty.csv", 'wb') as myfile:
				wr = csv.writer(myfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
				wr.writerow(header)
				wr.writerows(duty)
			print(filename + " duty cycle is " + percs + "/" + invpercs + "%.")
			IJ.log(filename + " duty cycle is " + percs + "/" + invpercs + "% (" + str(peaks) + " peaks found)")
			with open(csvpath + "results.csv", 'wb') as myfile:
				wr = csv.writer(myfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
				wr.writerows(results)		# Write the result data from all images into a single csv file
# This is not indexed by intellij
import net.imagej.legacy.IJ1Helper
import org.scijava.log.LogService

from net.imglib2.img.display.imagej import ImageJFunctions
# log = IJ1Helper.getLegacyContext().getService(LogService.class)

# Finds methods but no signatures
from ij import IJ
IJ.open()

repurl = "http://imagej.net/images"

IJ.open(repurl + "/FluorescentCells.jpg")
imp = IJ.getImage()
print imp.getClass()

img = ImageJFunctions.wrap(imp)
print img.getClass()
Beispiel #34
0
filelist = os.listdir(filepath)
metadata = []
imgsdata = []
for i in filelist:
	if i.split('_')[-1] == 'Properties.xml':
		metadata.append(i)
	if i.split('.')[-1] == 'tif':
		imgsdata.append(i.split('_')[0])

imgsdata = getUniques(imgsdata)
metadata = getUniques(metadata)
data = []

for i in imgsdata:
    scale = getScale(filepath + '/' + i + '_Properties.xml')
    img00 = IJ.open(filepath + '/' + i + '_ch00.tif')
    IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel");
    
    img01 = IJ.open(filepath + '/' + i + '_ch01.tif')
    IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel");
    data01 = getRadius(img01)
    cyto_r = scale * math.sqrt(float(data01[0].split('\t')[2])/math.pi)
    
    img02 = IJ.open(filepath + '/' + i + '_ch02.tif')
    IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel");
    data02 = getRadius(img02)
    nuc_r = scale * math.sqrt(float(data02[0].split('\t')[2])/math.pi)
    
    NCR = math.sqrt(nuc_r/cyto_r)**3
    data.append([data01, data02, scale, nuc_r, cyto_r, NCR])
    IJ.run('Close')
# A quick script to calibrate an Oxford AZtec image
#  Modifications
#   Date      Who  Ver                       What
# ----------  --- ------  -------------------------------------------------
# 2015-10-13  JRM 0.1.00  Initial prototype

from org.python.core import codecs
codecs.setDefaultEncoding('utf-8')

import os
from ij import IJ, Prefs
from ij.io import FileSaver 
import jmFijiGen as jmg
from ij.measure import Calibration

IJ.open(file.getAbsolutePath())
# load the dataset
imp = IJ.getImage()
fName = imp.getShortTitle()
wid = imp.getWidth()
argThree = "distance=%g known=%f pixel=1 unit=um" % (wid, fwMicrons)
IJ.run(imp, "Set Scale...", argThree)
IJ.run(imp, "Enhance Contrast", "saturated=0.35")
fPath = file.getParent()
fPath.replace("\\", "/")
tifName = fName + ".tif"
tifPath = os.path.join(fPath, tifName)


print(fName)
imp.changes = False
sleepTime = 3         # pause to see ong in sec
scaleX = 0.03143555   # um/px X
scaleY = 0.03144531   # um/px y
barW = 1.0            # bar width, microns
barH = 6              # bar height, pts
barF = 24             # bar font, pts
barC = "Black"        # bar color
barL = "Lower Right"  # bar location

homDir = os.environ['HOME']
relDir = "/Dropbox/datasets/AgX-dat/eia2855ImgSeries"
imgNam = "IMAGE027.tif"

imgPath = homDir + relDir + "/" + imgNam

IJ.open(imgPath);
IJ.run("Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.03143555 pixel_height=0.03144531 voxel_depth=1.0000000");
orig = IJ.getImage();

ti = orig.getShortTitle();
pngPath = homDir + relDir + "/" + ti + ".png"

strBar = "width=%g height=%g font=%g color=%s location=[%s] bold" % (barW, barH, barF, barC, barL)
# a hack to get the scale bars to work reliably
IJ.run(orig, "RGB Color", "")

# dummy to get things set
foo = orig.duplicate()
IJ.run(foo, "Add Scale Bar", strBar)
# explicitly save preferences
Prefs.savePreferences()
from ij import IJ
# from ij.gui import WaitForUserDialog
import glob, os

__author__ = 'Nichole Wespe'

inputDir = IJ.getDirectory("Choose Source Directory ")
pattern = os.path.join(inputDir, "*.tif")
fileList = glob.glob(pattern)
print "Found " + str(len(fileList)) + " tiff files to process."

for f in fileList:
	IJ.open(f)
	IJ.run("plate cropper")
	imp = IJ.getImage()
	imp.close()
	# Copies tiles for stitching into temp directory and stitches, if necessary
	if len(tiles)==1:
		params = "open=["+ imgDir +"tile_"+str(tiles[0])+".ome.tif] color_mode=Default view=Hyperstack stack_order=XYCZT"
		IJ.run("Bio-Formats Importer", params);
		tileImage = WindowManager.getImage("tile_"+str(tiles[0])+".ome.tif")
		tileImage.setSlice(int(tileImage.getNSlices()/2))
	else:
		ind = 1
		for t in tiles:
			shutil.copyfile(imgDir+"tile_"+str(t)+".ome.tif",imgDir+"temp/tile_"+str(ind)+".ome.tif")
			ind = ind + 1
		IJ.showStatus("Beginning stitch...")
		params = "type=[Grid: row-by-row] order=[Right & Down                ] grid_size_x=" + str(xs[2]) + " grid_size_y=" + str(ys[2]) + " tile_overlap=10 first_file_index_i=1 directory=[" + imgDir + "temp] file_names=tile_{i}.ome.tif output_textfile_name=TileConfiguration.txt fusion_method=[Linear Blending] regression_threshold=0.30 max/avg_displacement_threshold=2.50 absolute_displacement_threshold=3.50 compute_overlap ignore_z_stage subpixel_accuracy computation_parameters=[Save memory (but be slower)] image_output=[Fuse and display]"
		IJ.run("Grid/Collection stitching", params)
		fusedImage = WindowManager.getImage("Fused")
		IJ.saveAsTiff(fusedImage,imgDir+"temp/Fused.tif")
		fusedImage.close()
		IJ.open(imgDir+"temp/Fused.tif")
		tileImage = WindowManager.getImage("Fused.tif")
		tileImage.setSlice(int(tileImage.getNSlices()/2))
	
	gd = NonBlockingGenericDialog("Explore full resolution...")
	gd.addMessage("Select ROI for visualization at full resolution")
	gd.showDialog()
	doContinue = gd.wasOKed()

##### Removes temporary tile files ######
# filelist = [f for f in os.listdir(imgDir+"temp") if f.endswith(".tif")]
# for f in filelist:
#	os.remove(f)
Beispiel #39
0
	=======
	
	"""
    title = imp.getShortTitle()
    imp.setTitle(title)
    IJ.run("Stack to Images")
    impR = WindowManager.getImage("1")
    impG = WindowManager.getImage("2")
    impB = WindowManager.getImage("3")
    IJ.run("Merge Channels...", "c1=1 c2=2 c3=3 ignore")
    impRGB = WindowManager.getImage("RGB")
    # impRGB.show()
    impC = WindowManager.getImage("4")
    impC.close()
    impR.close()
    impG.close()
    impB.close()
    return (impRGB)


IJ.run("Close All")
imgDir = "/Users/jrminter/Desktop/"
imgNam = "jrm-screen-shot"
imgExt = ".png"
imgPath = imgDir + imgNam + imgExt
imgFullName = imgNam + imgExt
IJ.open(imgPath)
imp = IJ.getImage()
impRGB = convert_stack_4_to_rgb(imp)
impRGB.show()
	imp.changes = False
	imp.close()

# The size of the Gaussian Blur. Should be on the order of 30% of image width
size = 50

# A boolean to determine if we want to close - without warning - intermediate
# images
closeIntermediate = True

# The base title to give the image
strTitle = "small_rgb_bubbles"

IJ.run("Close All")
strImgPath = "/Users/jrminter/Documents/git/tips/ImageJ/png/small_rgb_bubbles.png"
IJ.open(strImgPath)
impOri = IJ.getImage()
impOri.setTitle(strTitle)
impOri.show()
[impR, impG, impB] = jmg.separate_colors(impOri)
impR.show()
impG.show()
impB.show()

impRb = jmg.gaussian_blur_8_bks(impR, size)
impRb.setTitle("rb")
impRb.show()

impGb = jmg.gaussian_blur_8_bks(impG, size)
impGb.setTitle("gb")
impGb.show()
Beispiel #41
0
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
IJ.run(
    "Scale...",
    "x=.5 y=.5 z=1.0 width=128 height=128 depth=930 interpolation=Bilinear average process create"
)
imp.close()
IJ.selectWindow("current-1")
Beispiel #42
0
    linCol     - the color for line/stroke in the overlay (default green)
    bDebug     - a flag (default False) that, if true, keeps the work image opem

    This adds the detected features to the overlay and returns the result table for
    processing for output.
    """
    title = imp.getTitle()
    shortTitle = imp.getShortTitle()
    imp.setTitle(shortTitle)
    imp.show()
    IJ.run(imp,"Duplicate...", "title=work")
    wrk = IJ.getImage()
    IJ.run(wrk, "Median...", "radius=2")
    IJ.run(wrk, "Enhance Contrast", "saturated=0.05")
    wrk.setTitle(shortTitle + "-km")
    IJ.run(wrk, "Threshold", strThrMeth)
    IJ.run(wrk, "Fill Holes", "")
    IJ.run(wrk, "Properties...", "channels=1 slices=1 frames=1 unit=px pixel_width=1 pixel_height=1 voxel_depth=1")
    IJ.run(wrk, "Set Measurements...", "area centroid center perimeter shape display redirect=None decimal=3")
    IJ. run(wrk, "Analyze Particles...", "display exclude clear add");
    
    return wrk


IJ.run("Close All");
closeRW = False
IJ.open("C:\\Data\\images\\key-test\\KMAG\\qm-05227-KMAG-96-19-08.tif");
ori = IJ.getImage()
kmi = anaKmag(ori)
kmi.show()