Example #1
0
 def keyPressed(self, event):
     key = event.getKeyCode()
     n = KeyboardListener.moves.get(key, 0)
     if 0 != n:
         self.dstack.shiftSlicesBy(n)
         event.consume()
     elif KEY.VK_R == key:
         self.dstack.reset()
         event.consume()
     elif KEY.VK_M == key:
         self.dstack.mirrorSlicesAt(self.imp.getCurrentSlice())
         event.consume()
     elif KEY.VK_W == key:
         if not event.isControlDown(
         ):  # otherwise, left control+W close the window
             width = IJ.getNumber("Window width:",
                                  min(7, self.dstack.size()))
             if not (IJ.CANCELED == width):
                 self.dstack.windowAroundSlice(self.imp.getCurrentSlice(),
                                               width)
             event.consume()
     if event.isConsumed():
         # Refresh
         self.imp.setStack(self.dstack)
     else:
         # Run pre-existing key listeners
         for l in self.listeners.get(event.getSource(), []):
             if not event.isConsumed():
                 l.keyPressed(event)
Example #2
0
def get_images(minimum=0, maximum=None, exact=None):
    ''' Returns a list of ImagePlus objects or None if it failed.
    Passing None as parameter will trigger a dialog to show up to enter the exact number of images.
    :param minimum: The minimum number of images to select (default: 0).
    :param maximum: The maximum number of images to select (default: None).
    :param exact: Set this to get an exact number of images (default: None).
    '''
    if not (minimum or maximum or exact):
        exact = int(IJ.getNumber("How many images do you want to process?", 3))
    def check_count(count):
        '''Returns True if the count of images is as required.'''
        # print count, exact, minimum, maximum
        if exact:
            if not count == exact:
                return False
        else:
            if minimum:
                if count < minimum:
                    return False
            if maximum:
                if count > maximum:
                    return False
        return True

    # Option 1: The selected image is a stack and has the demanded size.
    if check_count(WindowManager.getCurrentImage().getStackSize()):
        return stack_to_list_of_imp(WindowManager.getCurrentImage())

    # Option 2: The count of open images matches the demanded number.
    image_ids = WindowManager.getIDList()
    if exact:
        if len(image_ids) < exact:
            return None
        if len(image_ids) == exact:
            return [WindowManager.getImage(img_id) for img_id in image_ids]

    # Option 3: The user can select the images from a list.
    image_titles = [WindowManager.getImage(id).getTitle() for id in image_ids]
    img_count = len(image_ids)
    if exact:
        img_count = exact
    elif maximum:
        img_count = maximum
        image_titles.append('None')
    images_selected = dialogs.create_selection_dialog(image_titles,
                                                      range(img_count),
                                                      'Select images for drift correction'
                                                     )
    # dialogs.create_selection_dialog() returns None if canceled
    if not images_selected:
        return None
    # This is only true if 'None has been appended to image_titles and the user selected it.
    if len(image_ids) in images_selected:
        images_selected.remove(len(image_ids))
    if not check_count(len(images_selected)):
        return None
    image_list = [WindowManager.getImage(image_ids[selection]) for selection in images_selected]
    return image_list
Example #3
0
	def __split(self, event) : 
		sel = self.getSelected()
		if len(sel) != 1 : 
			IJ.showMessage("only one cell should be selected !")
			return
		else : 
			cellname = sel[0]
			rois = self.__rm.getRoisAsArray()
			self.__rm.runCommand("reset")
			n = int(IJ.getNumber("slice to split ?", 1))
			for i in range(n) : 
				self.__rm.addRoi(rois[i])
			#print self.__path+cellname+"-a.zip"
			self.__rm.runCommand("Save", self.__path+cellname+"-a.zip")
			self.__rm.runCommand("reset")
			for i in range(n, len(rois)) : 
				self.__rm.addRoi(rois[i])
			self.__rm.runCommand("Save", self.__path+cellname+"-b.zip")
			self.__rm.runCommand("reset")

		root = self.__path.rsplit(os.path.sep, 2)[0]+os.path.sep
		
		if not path.exists(root+"Cells"+os.path.sep) :os.makedirs(root+"Cells"+os.path.sep, mode=0777)

		fichiertemp = open(root+"Cells"+os.path.sep+cellname+"-a.cell","w")
		fichiertemp.write("NAMECELL="+cellname+"-a\n")
		fichiertemp.write("PATHCELL="+root+"Cells"+os.path.sep+cellname+"-a.cell\n")
		fichiertemp.write("PATHROIS="+root+"ROIs"+os.path.sep+cellname+"-a.zip\n")
		fichiertemp.write("NSLICES="+str(len(rois))+"\n")
		fichiertemp.write("SLICEINIT="+str(1)+"\n")
		fichiertemp.write("SLICEEND="+str(n)+"\n")
		r = random.randrange(5,205,1)
		g = random.randrange(10,210,1)
		b = random.randrange(30,230,1)
		fichiertemp.write("COLOR="+str(r)+";"+str(g)+";"+str(b)+"\n")
		fichiertemp.close()

		fichiertemp = open(root+"Cells"+os.path.sep+cellname+"-b.cell","w")
		fichiertemp.write("NAMECELL="+cellname+"-b\n")
		fichiertemp.write("PATHCELL="+root+"Cells"+os.path.sep+cellname+"-b.cell\n")
		fichiertemp.write("PATHROIS="+root+"ROIs"+os.path.sep+cellname+"-b.zip\n")
		fichiertemp.write("NSLICES="+str(len(rois))+"\n")
		fichiertemp.write("SLICEINIT="+str(n+1)+"\n")
		fichiertemp.write("SLICEEND="+str(len(rois))+"\n")
		r = random.randrange(5,205,1)
		g = random.randrange(10,210,1)
		b = random.randrange(30,230,1)
		fichiertemp.write("COLOR="+str(r)+";"+str(g)+";"+str(b)+"\n")
		fichiertemp.close()
Example #4
0
def checkLeafNumbers(dir):
    maskdir = os.path.join(dir, "mask")
    resdir = os.path.join(dir, "res")

    with open(os.path.join(dir, "leafnumbers.csv")) as f:
        leafnumbers = [tuple(s.rstrip("\n").split(",")) for s in f.readlines()]

    for filename, n in leafnumbers:
        n = int(n)
        ip = IJ.openImage(os.path.join(maskdir, "mask_%s" % filename.decode('utf-8')))
        ip.show()
        ans = int(IJ.getNumber("Number of Leaf", n))
        if ans < n:
            with open(os.path.join(resdir, "res_%s.csv" % os.path.splitext(filename)[0].decode("utf-8")), "r") as f:
                header, paResults = readPAResults(f)
            paResults = sorted(paResults, key=lambda x: x.area, reverse=True)
            with codecs.open(os.path.join(resdir, "res_%s.csv" % os.path.splitext(filename)[0].decode("utf-8")), "w", "utf-8") as f:
                table = [header]
                table += [row.asRow() for row in paResults[:ans]]
                f.writelines(table)
        ip.close()
import os
from ij import IJ
import glob
from ij.plugin.frame import RoiManager

_threshold_percent = 0.9
_n_channels = IJ.getNumber("Enter the number of channels used in this experiment (including brightfield)", 3)

def get_percentile(imp, percentile):

    IJ.log("Segmenting brightfield with percentile threshold {}".format(percentile))

    stats = imp.getRawStatistics()
    hist = stats.histogram()
    
    hist_x_min = stats.histMin
    hist_x_max = stats.histMax
    hist_x_range = hist_x_max - hist_x_min
    
    hist_x_values = []
    
    for bin in range(0, stats.nBins):
    
        #print("Fraction pixels with intensity in bins 0 to {}".format(bin))
        integral = sum(hist[0:bin])/sum(hist)
        #print(integral)
    
        intensity = hist_x_range * bin/stats.nBins
        hist_x_values.append(intensity)
        
        #print(intensity)
def run():
	image = IJ.getImage()
	minArea = IJ.getNumber("Enter area cutoff: " , 1)
	particleRemover(image, minArea)
Example #7
0
from ij.measure import CurveFitter

# Utils is a set of utilites for opening images, creating the output directory, saving images closing all windows
# If it is in the Fiji jars/Lib directory, it will be found. Otherwise, an explicit absolute path must be appended to the search path.
# The path in the next line must be changed to appropriate to the system on which this code runs
sys.path.append(os.path.abspath("/home/amw/git/jythonIJdev/libs"))
from Utils import *

close_non_image_windows()
close_image_windows()

# If number of exposures is less than 1, assume default exposure list.

exposures = []
while True:
    exposures.append(IJ.getNumber("exposure (ms)", -1))
    if exposures[-1] < 0:
        exposures.pop()
        exposures.sort()
        break
if len(exposures) < 2:
    exposures = [4, 10, 20, 50, 100, 200, 500, 1000, 2000,
                 5000]  # default exposures that I happen to use

pprint(exposures)

inputImp, inputPrefix, inputDirPath = open_image()
print("image directory path: ", inputDirPath.encode("ascii"))
inputImp.setTitle(inputPrefix)
inputTitle = inputImp.getTitle()
print("image name: ", inputTitle.encode("ascii"))
Example #8
0
from ij import IJ

imp = IJ.getImage()

title = imp.getTitle()
title = title[:-4]
interval_units = IJ.getString("Collection interval units: ", 'hrs')
start_time = IJ.getString("Start time: ", '0')
interval_by_units = IJ.getNumber("Collection interval in {}:".format(interval_units), 0.17)
fontsize = IJ.getNumber("Fontsize:", 14)
#get the directory containing the active image
path = IJ.getDirectory("image")
# If the active image is a duplicate of another image open, its path will be False and
# will print as 'None'. If this is the case, have the user choose a directory to put the
# timestamped tif
if not path:
    IJ.log("Image has no source directory")
    path = IJ.getDirectory("Choose the directory to save the timestamped tif")
else: 
    pass

height = imp.getHeight()
width = imp.getWidth()
size = imp.getImageStackSize()

IJ.log("Image title: {}".format(title))
IJ.log("Save path: {}".format(path))
IJ.log("Height: {}".format(height))
IJ.log("Width: {}".format(width))
IJ.log("Size: {}".format(size))