Example #1
0
def rotationNcropping(folder_in, folder_out):
    """ Function to rotate a set of 3D images such a a way the struts of the scaffold 
	the scaffols are alligned with x and y directions """

    for filename in os.listdir(folder_in):
        imp = IJ.openImage(os.path.join(folder_in, filename))
        IJ.run(
            imp, "TransformJ Rotate",
            "z-angle=9 y-angle=-6 x-angle=0.0 interpolation=Linear background=0.0"
        )
        imp = IJ.getImage()
        stack = imp.getImageStack()
        stackcropped = stack.crop(130, 64, 77, 1356, 1296, 1540)
        imp = ImagePlus("2", stackcropped)
        output = "nrrd=[" + folder_out + filename + "]"
        IJ.run(imp, "Nrrd ... ", output)
        imp.close()
        imp = None
        stack = None
        stackcropped = None
        gc.collect()
        time.sleep(15)
        gc.collect()
        IJ.run("Collect Garbage", "")
        IJ.run("Collect Garbage", "")
        IJ.getImage().close()
Example #2
0
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
Example #3
0
def calculate_mean_r(imp, ring_rois, centres):
    """calculate the average distance of the cell surface from the vessel axis"""
    w = imp.getWidth()
    h = imp.getHeight()
    rp = FloatProcessor(w, h)
    rpix = rp.getPixels()
    for lidx, (roi, centre) in enumerate(zip(ring_rois, centres)):
        for thetaidx, (x, y) in enumerate(
                zip(roi.getPolygon().xpoints,
                    roi.getPolygon().xpoints)):
            rpix[lidx * w + thetaidx] = math.sqrt((x - centre[0])**2 +
                                                  (y - centre[1])**2)
    rimp = ImagePlus("Radii", rp)
    IJ.setAutoThreshold(rimp, "Intermodes light")
    bp = rimp.createThresholdMask()
    bp.dilate()
    bp.erode()
    mask_imp = ImagePlus("Mask", bp)
    IJ.run(mask_imp, "Create Selection", "")
    roi = mask_imp.getRoi()
    rimp.setRoi(roi)
    mean_r = rimp.getStatistics().mean
    rimp.close()
    mask_imp.close()
    return mean_r
Example #4
0
def rmVoidCropNpreprocess(folder_in, folder_out, firstFolder, r):
    """Function to remove voids outside the scaffold(a cropping operation), Adding meta data, stack contrast adjust ment 
	Reducing computational cost is one of the main purpose of this fucntion. The function is written in a way that a set of images run at a time
	to manage computation time. Here tiff series of a 3D image is converted to a single NRRD file"""

    for x in range(r):
        fnum = firstFolder + x
        print(fnum)
        folder = folder_in + str(fnum) + "/"
        output = "nrrd=[" + folder_out + str(fnum) + ".nrrd]"
        imp = FolderOpener.open(folder)

        IJ.run(
            imp, "Properties...",
            "channels=1 slices=2159 frames=1 unit=[micro meters] pixel_width=0.81 pixel_height=0.81 voxel_depth=0.81"
        )
        stack = imp.getImageStack()
        stackcropped = stack.crop(404, 644, 480, 1604, 1476, 1678)
        imp = ImagePlus("1", stackcropped)
        IJ.run(imp, "Stack Contrast Adjustment", "is")
        imp = IJ.getImage()
        IJ.run(imp, "Nrrd ... ", output)
        imp.close()
        imp = None
        stack = None
        stackcropped = None
        gc.collect()

        time.sleep(15)
        gc.collect()
        IJ.run("Collect Garbage", "")
Example #5
0
def generate_cell_masks(watershed_seeds_imp,
                        intensity_channel_imp,
                        find_edges=False):
    """perform marker-driven watershed on image in intensity_channel_imp"""
    intensity_channel_title = intensity_channel_imp.getTitle()
    watershed_seed_title = watershed_seeds_imp.getTitle()
    title = os.path.splitext(intensity_channel_title)[0]
    intensity_channel_imp.show()
    watershed_seeds_imp.show()
    if find_edges:
        IJ.run(intensity_channel_imp, "Find Edges", "")
    IJ.run(
        intensity_channel_imp, "Marker-controlled Watershed",
        "input={} marker={} mask=None binary calculate use".format(
            intensity_channel_title, watershed_seed_title))
    ws_title = "{}-watershed.tif".format(title)
    watershed_imp = WM.getImage(ws_title)
    if watershed_imp is None:
        if ws_title[-3:] == 'tif':
            ws_title = os.path.splitext(ws_title)[0]
        else:
            ws_title = ws_title + '.tif'
        watershed_imp = WM.getImage(ws_title)
    IJ.setRawThreshold(watershed_imp, 1,
                       watershed_imp.getProcessor().maxValue() + 1, "Red")
    binary_cells_imp = ImagePlus("thresholded",
                                 watershed_imp.createThresholdMask())
    IJ.run(binary_cells_imp, "Kill Borders", "")
    kb_thresh_title = binary_cells_imp.getTitle()
    binary_cells_imp.close()
    binary_cells_imp = WM.getImage("{}-killBorders".format(kb_thresh_title))
    watershed_imp.close()
    intensity_channel_imp.changes = False
    intensity_channel_imp.close()
    return binary_cells_imp
Example #6
0
def make_tiled_imp(imp):
    """generate a ImageProcessor that is the input tiled 3 time horizontally"""
    ip = imp.getProcessor()
    stack = ImageStack(imp.getWidth(), imp.getHeight())
    for idx in range(3):
        stack.addSlice(ip)
    temp_imp = ImagePlus("temp", stack)
    tile_imp = MontageMaker().makeMontage2(temp_imp, 3, 1, 1, 1, 3, 1, 0,
                                           False)
    temp_imp.close()
    return tile_imp
Example #7
0
def prepros2(folder_in,folder_out):
	for filename in os.listdir(folder_in):
		imp =IJ.openImage(os.path.join(folder_in,filename))
		IJ.run(imp, "TransformJ Rotate", "z-angle=9 y-angle=-6 x-angle=0.0 interpolation=Linear background=0.0")
		imp = IJ.getImage()
		stack = imp.getImageStack()
		stackcropped  = stack.crop(118,98,70,1364,1304,904)
		imp = ImagePlus("2",stackcropped)
		output = "nrrd=["+folder_out+filename+"]"
		IJ.run(imp, "Nrrd ... ", output)
		imp.close()
		IJ.run("Collect Garbage", "")
Example #8
0
    def renderPreview(self, runStats):
        try:
            self.labelPreviewImp.close()
            self.maxZPreviewImp.close()
            self.maxYPreviewImp.close()
        except:
            print "imps already closed"

        fp = ShortProcessor(len(self.labelValues), 1, self.labelValues, None)
        labelerImp = ImagePlus("labeler", fp)
        src2 = clij2.push(labelerImp)
        dst = clij2.create(self.src)
        labelerImp.close()

        clij2.replaceIntensities(self.src, src2, dst)
        self.labelPreviewImp = clij2.pull(dst)
        previewDisplaySettings(self.labelPreviewImp, "label preview", 100,
                               self.cal)

        try:
            self.labelPreviewImp.setSlice(self.current)
        except:
            pass
        if runStats:
            clij2.statisticsOfBackgroundAndLabelledPixels(
                dst, self.src, self.results)
        dst2 = clij2.create(width, height, 1)
        clij2.maximumZProjection(dst, dst2)
        self.maxZPreviewImp = clij2.pull(dst2)
        previewDisplaySettings(self.maxZPreviewImp, "maxZ label preview", 50,
                               self.cal)

        dst3 = clij2.create(width, depth, 1)
        clij2.maximumYProjection(dst, dst3)
        self.maxYPreviewImp = clij2.pull(dst3)
        previewDisplaySettings(self.maxYPreviewImp, "maxY label preview", 50,
                               self.cal)

        dst3.close()
        dst.close()
        dst2.close()
        src2.close()

        labelWindow = self.labelPreviewImp.getWindow()
        x = labelWindow.getLocation().x
        y = labelWindow.getLocation().y

        maxZPreviewWindow = self.maxZPreviewImp.getWindow()
        maxZPreviewWindow.setLocation(x, y + height + 50)
        maxYPreviewWindow = self.maxYPreviewImp.getWindow()
        maxYPreviewWindow.setLocation(x + width / 2, y + height + 50)
        print labelWindow
Example #9
0
def prepros1(folder_in,folder_out,firstFolder):
	for x in range(1):
		fnum = firstFolder+x
		folder = folder_in+str(fnum)
		output = "nrrd=["+folder_out+str(fnum)+".nrrd]"
		imp = FolderOpener.open(folder)
		stack = imp.getImageStack()
		stackcropped  = stack.crop(404,644,538,1604,1476,1200)
		imp = ImagePlus("1",stackcropped)
		IJ.run(imp, "Stack Contrast Adjustment", "is")
		imp = IJ.getImage()
		IJ.run(imp, "Nrrd ... ", output);
		imp.close()
		IJ.run("Collect Garbage", "")
def snapshot(imp, c, z, f, x, y, L):
	'''Take a L x L snapshot centered at (x,y) at channel c, slice z and frame f

	Parameters:
		imp: an ImagePlus object for processing
		c, z, f: specificed channel, slice (z-dimension) and frame coordinate
		x, y: targeted center position to take the snapshot
		L: desired edge lengths of the snapshot in pixels

	Returns:
		cropped: an ImagePlus object of the snapshot image
	'''
	# Import inside function to limit scope
	from ij import ImagePlus
	
	# Get the dimensions of the images
	cN = imp.getNChannels()
	zN = imp.getNSlices()
#	fN = imp.getNFrames()

	# Convert specified position (c,z,f) to index assuming hyperstack order is czt (default)
	sliceIndex = int(cN * zN * (f-1) + cN * (z-1) + c)
	imp.setSlice(sliceIndex)
	ipTemp = imp.getProcessor()
	impTemp = ImagePlus('temp', ipTemp)

	# Expand the image by half of L to make sure final duplicate is the same size
	# when requested (x,y) could be within L pixels of the edge
	wOld = ipTemp.getWidth()
	hOld = ipTemp.getHeight()
	wNew = wOld + int(L)
	hNew = hOld + int(L)
	ipNew = ipTemp.createProcessor(wNew, hNew)
	ipNew.setColor(0) # 0 = black color
	ipNew.insert(ipTemp, int(L/2), int(L/2))
	imgNew = ImagePlus('new', ipNew)
	
	# Use the specified center coordinate x, y and the target side length to create ROI
	imgNew.setRoi(int(x), int(y), int(L), int(L))
#	cropped = ImagePlus('cropped', ipNew.crop())
	cropped = imgNew.crop()
	
	impTemp.close()
	imgNew.close()
	
	return cropped
Example #11
0
def generate_cell_masks(watershed_seeds_imp, intensity_channel_imp):
    """perform marker-driven watershed on image in intensity_channel_imp"""
    IJ.run(
        imp, "Marker-controlled Watershed",
        "input={} marker=Nuclei mask=None binary calculate use".format(
            os.path.splitext(intensity_channel_imp.getTitle())[0]))
    ws_title = "{}-watershed".format(intensity_channel_imp.getTitle())
    watershed_imp = WM.getImage(ws_title)
    IJ.setRawThreshold(watershed_imp, 1,
                       watershed_imp.getProcessor().maxValue(), "Red")
    binary_cells_imp = ImagePlus("thresholded",
                                 watershed_imp.createThresholdMask())
    IJ.run(binary_cells_imp, "Kill Borders", "")
    kb_thresh_title = binary_cells_imp.getTitle()
    binary_cells_imp.close()
    binary_cells_imp = WM.getImage("{}-killBorders".format(kb_thresh_title))
    watershed_imp.close()
    return binary_cells_imp
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 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 findCells(imp, rm, channel, noisetol, thresh):
    '''
	Function for finding cells as local maxima and creating an ROI showing them
	imp: ImagePlus
	rm: the current ROI manager
	channel, int: the channel being processed (used for ROI name)
	noisetol, thresh, ints: noise tolerance and pixel value threshold for findMaxima

	returns the count
	'''

    # set the channel
    imp.setC(channel)

    # find maxima
    ip = imp.getProcessor()
    mf = MaximumFinder()
    maxima = mf.findMaxima(ip, noisetol, thresh, MaximumFinder.SINGLE_POINTS,
                           False, False)

    findmaximashow = ImagePlus("Found Maxima", maxima)
    findmaximashow.show()  # an image of all the points
    maximaip = findmaximashow.getProcessor()
    maximahist = maximaip.getHistogram()
    cellCount = maximahist[255]

    if cellCount != 0:
        IJ.setRawThreshold(findmaximashow, 255, 255, "red")
        IJ.run(findmaximashow, "Create Selection", "")
        rm.addRoi(findmaximashow.getRoi()
                  )  # a selection consisting of all the points

    # close maxima image if present
    if findmaximashow:
        findmaximashow.close()

    return cellCount

parser = OptionParser()
parser.add_option('-o', '--output', help='edf.tiff')
options, args = parser.parse_args()

print options.output
print args

# check input image size
tmp = ImagePlus(args[0])

# put input images in a stack
stack = ImageStack(tmp.getWidth(), tmp.getHeight())
for a in args:
    imp = ImagePlus(a)
    stack.addSlice(imp.getProcessor())
imp = ImagePlus("focus stack", stack)
IJ.saveAsTiff(imp, options.output.replace("_edf_", "_edf_stack_"))

#sys.exit()
# process input
output = process(imp)

# save output
IJ.saveAsTiff(output, options.output)

# close images
output.close()
imp.close()
Example #16
0
files_ = get_files(folder, fileend)
new_dir = make_dir(folder)

for uncalibrated in files_:
    img = ImagePlus(uncalibrated)
    print("old calibration: {}".format(img.getCalibration()))
    apply_calibration(img)
    # make ROI
    make_roi(img)
    print("cropping image")
    # crop to ROI
    new = crop_roi(img)
    print("new calibration: {}".format(new.getCalibration()))
    save_file(new, uncalibrated)
    img.close()
    new.close()
"""
# testing 
img = ImagePlus(files_[0])
img.show()
make_roi(img)
new = crop_roi(img)
new.show()
"""
"""
regex_string = re.compile(r"ImageDescription: (?P<id>AMT Camera System).+XpixCal=(?P<xpix>\d+?\.\d+).YpixCal=(?P<ypix>\d+?\.\d+).Unit=(?P<unit>\w\w)")
img_metadata = img.getProperties().getProperty("Info")
print(img_metadata)
grouped = regex_string.search(img_metadata)
try:
	def makeMask(self):
		"""
		This function makes the mask. The steps are (1) Minimum Filter - makes a darker boundary around beads (2) Autothresholding using the Huang algorithm - has some fuzzy logic and seems to work (3) Analyze particles with a size between 500-50000 and 
		circularity between 0.4 to 1.0; The mask generated is sometimes black on beads and white around. Then I need to invert the LUTs
		"""
	
		ipOriginal = self.stack.getProcessor(self.DIC_index)
		ip = ipOriginal.duplicate()
		imgUpdate = ImagePlus("New",ip)
		imgUpdate.setProcessor("Mask",ip)
		
		img0 = ImagePlus("Before",ipOriginal)
		img0.show()
		
		# Minimum filter
		RankFilters().rank(ip,2,RankFilters.MIN)
		img1 = ImagePlus("Filter",ip)
		# Autothreshold - Huang algorithm
		hist = ip.getHistogram()
		lowTH = Auto_Threshold.Huang(hist)
		ip.setThreshold(0,lowTH, ImageProcessor.BLACK_AND_WHITE_LUT)
		img3 = ImagePlus("Thresholded",ip)
		img3.show()

		# Making a binary mask
		IJ.run(img3,"Convert to Mask","")
		
		if self._dialog("Invert Mask ??") is True: IJ.run("Invert LUT")
		img3.updateAndDraw()
		
		# The true mask after Particle Analysis; Creates a mask image around the particles
		IJ.run(img3,"Analyze Particles...", "size=500-50000 circularity=0.40-1.00 show=Masks")
		img1.close()
		#img3.close()

		# Editing the masks (filling holes and dilating it twice)
		imgActive = IJ.getImage()
		IJ.run(imgActive,"Convert to Mask","")
		IJ.run(imgActive,"Fill Holes","")
		for i in range(8): IJ.run(imgActive,"Dilate","")
		ipActive = imgActive.getProcessor().convertToFloat()
		
		# Saving the mask
		maskFname = self.sourceDir + "\\" + self.title + '_mask'
		IJ.saveAs(imgActive, "PNG", maskFname)
				
		# Confirming that the image is masked and the histogram is correct
		#IJ.run(imgActive, "Histogram", "")
		
		#stats = ipActive.getStatistics()
		pixels = ipActive.getPixels()
		self.maskPixels = [pix/255 for pix in pixels]
		self.areaMask = self.maskPixels.count(1)

		# Checking if the image is fine. If not, returns option to skip
		ImageCalculator().calculate("zero create", img0, imgActive)

		skip = False
		if self._dialog("Skip Image ??") is True: skip = True

		IJ.run("Close All")
		return self.maskPixels, skip
			accept_waiter = NonBlockingGenericDialog("Thresholding...")
			accept_waiter.addNumericField("Threshold:",t_line,0)
			accept_waiter.setCancelLabel("Apply new threshold")
			accept_waiter.setOKLabel("Accept threshold")
			accept_waiter.showDialog()
			if (accept_waiter.wasCanceled()):
				newip.reset()
				newip.snapshot()
				t_line = accept_waiter.getNextNumber()
#				if (t_line > 10):
#					t_line = t_line - 5
#				else:
#					t_line = 5
				newip.setThreshold(0,t_line,ImageProcessor.BLACK_AND_WHITE_LUT)
				newImage.updateAndDraw()
			else:
				doSameSlice = False
				for i in range(newImage.getWidth()):
					for j in range(newImage.getHeight()):
						if (newip.getPixel(i,j) > newip.getMaxThreshold()):
							newip.putPixel(i,j,254)
						else:
							newip.putPixel(i,j,0)
				newnewip = newip.duplicate()
				newStack.addSlice(newnewip)
				newImage.close()

	castImage = ImagePlus("cast",newStack)
	castImage.show()
			
Example #19
0
    def process(self,imp):
        # extract nucleus channel, 8-bit and twice binned
        imp.setC(self.nucleusChannel)
        ip = imp.getChannelProcessor().duplicate()
        ip = ip.convertToByteProcessor()
        ip = ip.bin(4)
        nucleus = ImagePlus("nucleus_channel", ip)

        # threshold image and separate clumped nuclei
        IJ.run(nucleus, "Auto Threshold", "method=Otsu white setthreshold show");
        IJ.run(nucleus, "Make Binary", "thresholded remaining black");
        IJ.run(nucleus, "Watershed", "");

        directory = imp.getTitle()
        directory = directory.replace(" ", "_")\
            .replace(",", "_")\
            .replace("#", "_series")\
            .replace("...", "")\
            .replace(".","_")
        directory = os.path.join(self.exportDir, directory)
        sliceDirectory = os.path.join(directory, "slices")
        print directory
        print sliceDirectory
        if not os.path.exists(sliceDirectory):
            os.makedirs(sliceDirectory)

        # Create a table to store the results
        table = ResultsTable()

        # Create a hidden ROI manager, to store a ROI for each blob or cell
        #roim = RoiManager(True)

        # remove small particles and border particles
        pa = ParticleAnalyzer(\
            ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES,\
            Measurements.CENTER_OF_MASS,\
            table,\
            self.minArea, self.maxArea,\
            0.0,1.0)

        if pa.analyze(nucleus):
            print "All ok, number of particles: ", table.size()
        else:
            print "There was a problem in analyzing", imp, nucleus
        table.save(os.path.join(directory, "rt.csv"))

        # read the center of mass coordinates
        cmx = table.getColumn(0)
        cmy = table.getColumn(1)

        if self.debug:
            imp.show()

        i=0
        for i in range(0, min(self.nCells,table.size())):
            # ROI around the cell
            cmx = table.getValue("XM",i)
            cmy = table.getValue("YM",i)
            x = 4 * cmx - (self.boxSize - 1) / 2
            y = 4 * cmy - (self.boxSize - 1) / 2
            if (x < self.edge or y < self.edge or x > imp.getWidth() - self.edge or y > imp.getHeight() - self.edge):
                continue
            roi = Roi(x,y,self.boxSize,self.boxSize)
            imp.setRoi(roi, False)

            cellStack = ImageStack(self.boxSize, self.boxSize)

            for z in range(1, imp.getNSlices() + 1):
                imp.setSlice(z)
                for c in range(1, imp.getNChannels() + 1):
                    imp.setC(c)
                    # copy ROI to stack
                    imp.copy()
                    impSlice = imp.getClipboard()
                    cellStack.addSlice(impSlice.getProcessor())
                    if self.slices:
                        sliceTitle = "cell_%s_z%s_c%s" % (str(i).zfill(4), str(z).zfill(3), str(c))
                        print sliceTitle
                        IJ.saveAsTiff(impSlice, os.path.join(sliceDirectory, sliceTitle))
                    impSlice.close()

            title = "cell_" + str(i).zfill(4)
            cell = ImagePlus(title, cellStack)

            # save ROI image
            IJ.saveAsTiff(cell, os.path.join(directory, title))
            cell.close()

            if self.debug:
                imp.updateAndDraw()
                wait = Wait("particle done")
                wait.show()
		gd.showDialog()

	## Does simple interpolation of the ROIs through the stack
	if len(sliceList)>0:
		sliceList.sort(reverse=True)
		for sl in range(theImage.getNSlices()):
			if (sl+1) < sliceList[-1]:
				maskImage.setSliceWithoutUpdate(sliceList[-1])
				activeIp = maskImage.getProcessor().duplicate()
			elif (sl+1) > sliceList[0]:
				maskImage.setSliceWithoutUpdate(sliceList[0])
				activeIp = maskImage.getProcessor().duplicate()
			else:
				isFound = False
				for mark in sliceList:
					dist = sl+1 - mark
					if dist >= 0 and not isFound:
						isFound = True
						refSlice = mark
				maskImage.setSliceWithoutUpdate(refSlice)
				activeIp = maskImage.getProcessor().duplicate()
			maskImage.setSliceWithoutUpdate(sl+1)
			maskImage.setProcessor(activeIp)

	## Computes the overlay image
	ic = ImageCalculator()
	resultImage = ic.run("AND create stack",theImage,maskImage)
	resultImage.show()

	maskImage.close()
Example #21
0
    con = 1.0-(lMode[j]/iZero)
    conOut.append(con)   
    cirOut.append(lCirc[j])
    arOut.append(lAspRat[j])
    rndOut.append(lRound[j])
    solOut.append(lSolid[j])
    
    
  orig.show()
  outPth = sRptImgPath + strName + ".png"
  # burn a scale bar and save the image
  IJ.run(orig, "RGB Color", "")
  IJ.run(orig, "Add Scale Bar", strBar)
  IJ.saveAs(orig, "PNG", outPth)
  orig.changes = False
  orig.close()

  print("%d particles detected in image %s" % (nMeas, strNum))

# prepare the output file
f=open(sRptCsvPath, 'w')
strLine = 'img, part, ecd.nm, contrast, circ, a.r, round, solidity\n'
f.write(strLine)
for k in range(len(ecdOut)):
  strLine = "%d, %d, %.2f, %.4f, %.4f, %.4f, %.4f, %.4f\n" % (imgOut[k], parOut[k], ecdOut[k],  conOut[k], cirOut[k], arOut[k], rndOut[k], solOut[k] )
  f.write(strLine)

f.close()

toc = time.time()
Example #22
0
import glob
import os.path
import sys

from ij import IJ, ImagePlus, ImageStack, WindowManager
from ij.io import DirectoryChooser

from edfgui import ExtendedDepthOfField, Parameters

file_in = sys.argv[1]
file_out = sys.argv[2]

# EDF parameters
params = Parameters()
params.setQualitySettings(params.QUALITY_HIGH)
params.nScales = 10

# read input image
imp = ImagePlus(file_in)

# make all-in-focus image
edf = ExtendedDepthOfField(imp,params)
edf.process()

# save output
imp = WindowManager.getCurrentImage()
IJ.saveAsTiff(imp,file_out)
imp.close()

def do_tubefitting(im_path=im_test_path,
                   metadata_path=metadata_test_path,
                   output_path=output_path,
                   save_output=False):
    # todo: fix things so that all operations use a consistent definition of background rather than changing Prefs on the fly...
    Prefs.blackBackground = False
    info = PrescreenInfo()
    info.load_info_from_json(metadata_path)
    z_xy_ratio = abs(
        info.get_z_plane_spacing_um()) / info.get_xy_pixel_size_um()
    #z_xy_ratio = 1.0;
    bfimp = bf.openImagePlus(im_path)
    imp = bfimp[0]
    imp.show()
    IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel")
    imp = utils.downsample_for_isotropy(imp,
                                        extra_downsample_factor=1.0,
                                        info=info)
    rot_seg_imp, rot_proj_imp, egfp_mch_imps = split_and_rotate(imp, info)
    depth = rot_seg_imp.getNSlices() if rot_seg_imp.getNSlices(
    ) > rot_seg_imp.getNFrames() else rot_seg_imp.getNFrames()
    width = rot_seg_imp.getWidth()
    height = int(round(rot_seg_imp.getHeight() * z_xy_ratio))

    # Apply 3d MEDIAN FILTER to denoise and emphasise vessel-associated voxels
    fit_basis_imp = threshold_and_binarise(rot_seg_imp, z_xy_ratio)
    fit_basis_imp.setTitle("fit_basis_imp")
    fit_basis_imp.show()

    # plane-wise, use binary-outline
    # say the non-zero points then make up basis for fitting to be performed per http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html
    rois = []
    centres = []
    major_axes = []
    roi_imp = IJ.createImage("rois", width, height, depth, 32)
    pts_stack = ImageStack(width, height + 1)
    IJ.run(imp, "Line Width...", "line=3")
    for zidx in range(fit_basis_imp.getNSlices()):
        fit_basis_imp.setZ(zidx + 1)
        IJ.run(fit_basis_imp, "Outline", "slice")
        IJ.run(fit_basis_imp, "Create Selection", "")
        roi = fit_basis_imp.getRoi()
        fit_basis_imp.killRoi()
        pts = [(pt.x, pt.y) for pt in roi.getContainedPoints()]
        clean_pts = convex_hull_pts(pts)
        clean_pts = [(x, z_xy_ratio * y) for (x, y) in clean_pts]
        # make a stack of clean points...
        ip = FloatProcessor(width, height + 1)
        pix = ip.getPixels()
        for pt in clean_pts:
            pix[int(pt[1]) * width + int(pt[0])] = 128
        pts_stack.addSlice(ip)
        centre, angle, axl = ellipse_fitting.fit_ellipse(clean_pts)
        major_axes.append(max(axl))
        centres.append(centre)
        rot_seg_imp.setZ(zidx + 1)
        ellipse_roi = ellipse_fitting.generate_ellipse_roi(centre, angle, axl)
        rois.append(ellipse_roi)
    IJ.run(imp, "Line Width...", "line=1")
    cal = imp.getCalibration()
    smooth_centres, tangent_vecs = generate_smoothed_vessel_axis(
        centres, pixel_size_um=cal.pixelDepth)
    for zidx in range(fit_basis_imp.getNSlices()):
        centre = smooth_centres[zidx]
        major_axis = major_axes[zidx]
        ellipse_roi = EllipseRoi(centre[0] - 2, centre[1], centre[0] + 2,
                                 centre[1], 1.0)
        roi_imp.setZ(zidx + 1)
        roi_imp.setRoi(ellipse_roi)
        IJ.run(roi_imp, "Set...",
               "value=" + str(roi_imp.getProcessor().maxValue()) + " slice")

    pts_stack_imp = ImagePlus("Cleaned points", pts_stack)
    pts_stack_imp.setTitle("pts_stack_imp")
    pts_stack_imp.show()

    rot_seg_imp.changes = False
    rot_seg_imp.close()
    egfp_imp = egfp_mch_imps[0]
    mch_imp = egfp_mch_imps[1]
    imps_to_combine = [egfp_mch_imps[1], egfp_mch_imps[0], roi_imp]
    egfp_imp.show()
    mch_imp.show()
    roi_imp.show()
    print("box height um = " +
          str(roi_imp.getNSlices() * info.get_xy_pixel_size_um()))
    IJ.run(
        egfp_imp, "Size...", "width=" + str(width) + " height=" + str(height) +
        " depth=" + str(depth) + " average interpolation=Bilinear")
    IJ.run(
        mch_imp, "Size...", "width=" + str(width) + " height=" + str(height) +
        " depth=" + str(depth) + " average interpolation=Bilinear")
    #IJ.run("Merge Channels...", "c1=[" + mch_imp.getTitle() +
    #								"] c2=[" + egfp_imp.getTitle() +
    #								"] c7=[" + roi_imp.getTitle() + "] create keep");
    composite_imp = RGBStackMerge().mergeChannels(imps_to_combine, False)
    print(composite_imp)
    composite_imp.show()
    print("end of vessel centerline id step, image dims = ({}x{}x{})".format(
        composite_imp.getWidth(), composite_imp.getHeight(),
        composite_imp.getNSlices()))
    WaitForUserDialog("pause").show()
    # do qc here?

    #WM.getImage("Composite").addImageListener(UpdateRoiImageListener(rois));
    IJ.run(roi_imp, "8-bit", "")

    if save_output:
        FileSaver(composite_imp).saveAsTiffStack(
            os.path.join(output_path, "segmentation result.tif"))
        print(roi_imp)
        FileSaver(roi_imp).saveAsTiff(
            os.path.join(output_path, "vessel axis.tif"))

    egfp_imp.changes = False
    mch_imp.changes = False
    roi_imp.changes = False
    fit_basis_imp.changes = False
    pts_stack_imp.changes = False
    egfp_imp.close()
    mch_imp.close()
    #roi_imp.close();
    fit_basis_imp.close()
    pts_stack_imp.close()

    zcoords = [i for i in range(composite_imp.getNSlices())]
    xyz_smooth_centres = [(x, y, z)
                          for ((x, y), z) in zip(smooth_centres, zcoords)]

    composite_imp2 = straighten_vessel(composite_imp,
                                       xyz_smooth_centres,
                                       save_output=True)
    composite_imp3 = straighten_vessel(composite_imp2,
                                       xyz_smooth_centres,
                                       it=2,
                                       save_output=True)
    return composite_imp3
Example #24
0
	imstack=ImagePlus("stack3", istack)
	
	#IJ.run("Images to Stack", "name="+cle+"-plots title="+cle+" use")
	imstack.show()
	IJ.selectWindow("stack3")
	#imtorgb=[implot1,implot2,implot3]
	#rgbcon=RGBStackMerge()
	#IJ.run("Merge Channels...", "red="+implot1.getTitle()+" green="+implot2.getTitle()+" blue="+implot3.getTitle()+" gray=*None*");
	#lastimage=IJ.getImage()
	
	#lastimage = rgbcon.mergeChannels(imtorgb, True) 
	#lastimage.show()
	#IJ.run("Invert", "stack")
	IJ.run("Stack to RGB", "")
	lastimage=IJ.getImage()
	imstack.close()
	#cp = lastimage.getProcessor().convertToRGB()
	cp = lastimage.getProcessor()
	try : rgbstack.addSlice(cle, cp)
	except NameError : 
		rgbstack = lastimage.createEmptyStack()
		rgbstack.addSlice(cle, cp)
	lastimage.close()
	#IJ.selectWindow(cle+"-plots")
	#IJ.getImage().hide()
	
	del(reversions)
	del(speed)
	del(cumuld)

imprgb=ImagePlus("rgbStack", rgbstack)
class GridSet:
    """
    A class to keep track of multiple grid readers.
    
    cContains methods to keep track of scores and move forward and
    backward while keeping track of the scores.

    Writes a csv file containing the information about the grid as well
    as the score that was assigned to each cell in the grid.

    Writes a jpg thumbnail for each cropped cell in the grid.

    Writes an HTML report that matches scores to images.

    Images are displayed randomly to prevent biased scoring.

    Arguments:

    - fp : list, paths the the grid files used by the GridReader
    - scoreFile : string, an string giving the filename of the
      scores to write to.
    - thumbDir : string, the name of the directory to save the
      thumbnails in
    """
    def __init__(self, fp, scoreFile, thumbDir):
        # These will be indexed by the grid coordinates
        self.scores = {}
        # These will be indexed by the plateID
        self.grids = {}
        # Keeps the grid coordinates from each grid
        self.gridCoords = []
        for i in fp:
            grid = GridReader(i)
            # each coordinate is a tuple: (plateID, row, col, x, y)
            gridCoords = grid.getCoords()
            # save the grid reader in a dictionary
            self.grids[ grid.getPlateID() ] = grid
            # append the coordinates to the coordinates pile
            for coord in gridCoords:
                self.gridCoords.append(coord)
        # shuffle the coordinates
        shuffle(self.gridCoords)
        # Initialize the images, and some variable names
        self.openImage = ImagePlus()
        self.thumbDir = thumbDir
        self.scoreFile = scoreFile
        self.reportFile = os.path.splitext(scoreFile)[0] + ".html"
        self.reportFile2 = os.path.splitext(scoreFile)[0] + "-with-plate-positions.html"
        self.min = 0
        self.max = 255
        # This is the current coordinate position
        self.n = -1
        # Test for scorefiles
        if os.path.isfile( self.scoreFile ):
            print "Restoring previous scores"
            self.restoreScores()
        # Generate a spot for the HTML report to live in along with the thumbnails
        try:
            os.mkdir(self.thumbDir)
        except OSError:
            pass

    def restoreScores(self):
        """
        If a file with the same name is detected as the output score file,
        this method is called. It reads in the previous scores and
        sets the first image to be the image after the previous scores
        """
        # Open a file to the scores
        inFile = open( self.scoreFile , "r" )
        reader = csv.reader(inFile, delimiter=",")
        header = reader.next()
        # This will store the coordinates corresponding to the previous scores
        tmpCoords = []
        # for each row in the scores file, append the previous coordinates
        # and make an entry for the score
        for row in reader:
            plateID, row, col, x, y, theMin, theMax, score = row
            coord = (plateID, row, col, x, y)
            self.scores[ coord ] = (plateID, row, col, x, y, theMin, theMax, score)
            tmpCoords.append(coord)
        self.min = int(theMin)
        self.max = int(theMax)
        self.n = len(tmpCoords) - 1
        if self.n < 0:
            self.n = 0
        for coord in self.gridCoords:
            if coord not in self.scores:
                tmpCoords.append(coord)
        self.gridCoords = tmpCoords
        
    def writeThumbnail(self):
        plateID, row, col, x, y = self.currentCoordinate
        imName = "_".join([ str(plateID), str(row), str(col) ] ) + ".jpg"
        imName = os.path.join(self.thumbDir, imName)
        fs = FileSaver(self.openImage)
        fs.saveAsJpeg( imName )

    def setMinAndMax(self, minVal = None, maxVal = None):
        """
        Sets the min and max of the current image

        Arguments:
        - minVal : integer, the minimum value for the pixel display
        - maxVal : integer, the maximum value for the pixel display
        """
        if minVal is not None:
            self.min = minVal
        if maxVal is not None:
            self.max = maxVal
        self.openImage.getProcessor().setMinAndMax(self.min, self.max)
        self.openImage.updateChannelAndDraw()
        self.writeThumbnail()
            
    def openNext(self):
        """
        Opens the next image.

        Arguments:
        - thumbNails : bool, if True a thumbnail for th
          image is written when the image is opened
        """
        self.openImage.close()
        # Set the current number being examined
        self.n = self.n + 1
        try:
            self.currentCoordinate = self.gridCoords[ self.n ]
        except IndexError:
            gd = GenericDialog("")
            gd.addMessage("No more images")
            gd.showDialog()
            return None
        plateID, row, col, x, y = self.currentCoordinate
        # open the file
        grid = self.grids[ plateID ]
        self.openImage = grid.openSubImage(x,y)
        self.setMinAndMax()
        self.openImage.show()
        # Write the thumbnail
        self.writeThumbnail()
        # Try to return the information about the current score
        # if it doesn't exist, return an empty string. This
        # is used to display the score associated with the image
        try:
            return self.scores[ self.currentCoordinate ][7]
        except KeyError:
            return ""

    def openPrevious(self):
        """
        Opens the previous image.
        """
        self.n = self.n - 1
        if self.n < 0:
            self.n = 0
        else:
            self.openImage.close()
            self.currentCoordinate = self.gridCoords[ self.n ]
            plateID, row, col, x, y = self.currentCoordinate
            # open the file
            grid = self.grids[ plateID ]
            self.openImage = grid.openSubImage(x,y)
            self.setMinAndMax()
            self.openImage.show()
        # Retun the score of the image so it can be displayed
        try:
            return self.scores[ self.currentCoordinate ][7]
        except KeyError:
            return ""

    def writeScore(self, score):
        """
        Update the dictionary of scores with the new score and
        write the full dictionary to disk.

        Attributes:
        - score : string, the score to be associated with the grid
                  coordinates and the row/column info
        """
        header = ["plate", "row", "col", "x", "y", "min", "max", "score"]
        plateID, row, col, x, y = self.currentCoordinate
        # Save the info for the score in a dictionary
        info = (plateID,
                row,
                col,
                x,
                y,
                self.min,
                self.max,
                score)
        self.scores[ self.currentCoordinate ] = info
        # initialize a writer for the scores and write a header
        self.out = open( self.scoreFile , "w" )
        writer = csv.writer(self.out, delimiter=",")
        writer.writerow(header)
        for i in self.scores.values():
            writer.writerow( i )
        self.out.close() 

    def writeReport(self, reportName, thumbDir, numColumns = 5, textSize = 20, doInfo=False):
        """
        Writes an HTML report with alternating rows of
        images and their scores.

        Arguments:
        - numColumns : integer, the number of columns in the html report
        - textSize : integer, the text size for the scores
        """
        def img(location, width, height):
            return '<img src="%s" width="%i" height="%i">' % (location, width, height)
        # Initialize the HTML writer
        t = Table(col_align = ["center" for i in range(0,numColumns)])
        #t.rows.append(TableRow(["row", "col", "score", "image"], header=True))
        # For each score, sort by the colony morphology score
        scores = [i for i in self.scores.values()]
        sortedScores = [i for i in sorted( scores, key=lambda info: info[7])]
        ##### This next chunk makes a 5xn table in the HTML file with
        ##### alternating images and their scores.
        n = 0
        imgLine = []
        scoreLine = []
        for i in range(0, len(sortedScores)):
            plateID, row, col, x, y, theMin, theMax, score = sortedScores[i]
            # Font size is set above
            score = "<font size = '%i'>%s</font>" % (textSize, str(score))
            imgInfo = "%s: row %s, col %s" % (plateID, str(row), str(col))
            if doInfo:
                score = score + "<br>" + imgInfo
            # This should be a function
            imName = "_".join([ str(plateID), str(row), str(col) ] ) + ".jpg"
            # Images live in a subfolder. This splits the path so that
            # only the relative name is referenced
            thumbDir = os.path.split(thumbDir)[1]
            imName = os.path.join(thumbDir, imName)
            scoreLine.append( score )
            imgLine.append( img(imName, 300, 300) )
            n += 1
            if (( n % numColumns) == 0):
                t.rows.append( TableRow( imgLine ) )
                t.rows.append( TableRow( scoreLine) )
                n = 0
                imgLine = []
                scoreLine = []
        # Append the final row to the table
        t.rows.append( TableRow( imgLine ) )
        t.rows.append( TableRow( scoreLine) )
        # Initialize the connection for the report
        reportOut = open( reportName, "w")
        # write the html
        reportOut.write( str(t) )
        reportOut.close()

    def close(self):
        self.openImage.close()
        self.writeReport(self.reportFile, self.thumbDir)
        self.writeReport(self.reportFile2, self.thumbDir, doInfo=True)
        for grid in self.grids.values():
            grid.close()
def processImages(cfg, wellName, wellPath, images):
    firstImage = IJ.openImage(images[0][0][0][0])
    imgWidth = firstImage.getWidth()
    imgHeight = firstImage.getHeight()

    for c in range(0, cfg.getValue(ELMConfig.numChannels)):
        chanName = cfg.getValue(ELMConfig.chanLabel)[c]

        if cfg.getValue(ELMConfig.chanLabel)[c] in cfg.getValue(
                ELMConfig.chansToSkip):
            continue
        imColorSeq = ImageStack(imgWidth, imgHeight)
        imSeq = ImageStack(imgWidth, imgHeight)
        totalHist = []
        for z in range(0, cfg.getValue(ELMConfig.numZ)):
            for t in range(0, cfg.getValue(ELMConfig.numT)):

                currIP = IJ.openImage(images[c][z][t][0])
                imColorSeq.addSlice(currIP.duplicate().getProcessor())

                currIP = ELMImageUtils.getGrayScaleImage(
                    currIP, c, chanName, cfg)

                imSeq.addSlice(currIP.getProcessor())
                imgStats = currIP.getStatistics()
                currHist = imgStats.getHistogram()
                if not totalHist:
                    for i in range(len(currHist)):
                        totalHist.append(currHist[i])
                else:
                    for i in range(len(currHist)):
                        totalHist[i] += currHist[i]

        if cfg.hasValue(ELMConfig.thresholdFromWholeRange) and cfg.getValue(
                ELMConfig.thresholdFromWholeRange) == True:
            threshMethod = "Otsu"  # Default works very poorly for this data
            if cfg.hasValue(ELMConfig.thresholdMethod):
                threshMethod = cfg.getValue(ELMConfig.thresholdMethod)
            thresholder = AutoThresholder()
            computedThresh = thresholder.getThreshold(threshMethod, totalHist)
            cfg.setValue(ELMConfig.imageThreshold, computedThresh)
            print("\tComputed threshold from total hist (" + threshMethod +
                  "): " + str(computedThresh))
            print()
        else:
            print("\tUsing threshold computed on individual images!")
            print()
            computedThresh = 0

        chanName = cfg.getValue(ELMConfig.chanLabel)[c]

        imp = ImagePlus()
        imp.setStack(imSeq)
        imp.setDimensions(1, 1, cfg.getValue(ELMConfig.numT))
        imp.setTitle(wellName + ", channel " + str(c))

        impColor = ImagePlus()
        impColor.setStack(imColorSeq)
        impColor.setDimensions(1, 1, cfg.getValue(ELMConfig.numT))
        impColor.setTitle(wellName + ", channel " + str(c) + " (Color)")

        #----------------------------
        # Create the model object now
        #----------------------------

        # Some of the parameters we configure below need to have
        # a reference to the model at creation. So we create an
        # empty model now.

        model = Model()

        # Send all messages to ImageJ log window.
        model.setLogger(Logger.IJ_LOGGER)

        pa_features = [
            "Area", "PercentArea", "Mean", "StdDev", "Mode", "Min", "Max", "X",
            "Y", "XM", "YM", "Perim.", "BX", "BY", "Width", "Height", "Major",
            "Minor", "Angle", "Circ.", "Feret", "IntDen", "Median", "Skew",
            "Kurt", "RawIntDen", "FeretX", "FeretY", "FeretAngle", "MinFeret",
            "AR", "Round", "Solidity"
        ]

        featureNames = {}
        featureShortNames = {}
        featureDimensions = {}
        isInt = {}
        for feature in pa_features:
            featureNames[feature] = feature
            featureShortNames[feature] = feature
            featureDimensions[feature] = Dimension.STRING
            isInt[feature] = False

        model.getFeatureModel().declareSpotFeatures(pa_features, featureNames,
                                                    featureShortNames,
                                                    featureDimensions, isInt)

        #------------------------
        # Prepare settings object
        #------------------------

        settings = Settings()
        settings.setFrom(imp)

        dbgPath = os.path.join(wellPath, 'debugImages_' + chanName)
        if not os.path.exists(dbgPath):
            os.makedirs(dbgPath)

        if cfg.hasValue(ELMConfig.thresholdMethod):
            threshMethod = cfg.getValue(ELMConfig.thresholdMethod)
        else:
            threshMethod = "Default"

        # Configure detector - We use the Strings for the keys
        settings.detectorFactory = ThresholdDetectorFactory()
        settings.detectorSettings = {
            'THRESHOLD': computedThresh,
            'ABOVE': True,
            'DEBUG_MODE': True,
            'DEBUG_OUTPATH': dbgPath,
            'THRESHOLD_METHOD': threshMethod
        }

        #settings.detectorFactory = LocalThresholdDetectorFactory()
        #settings.detectorSettings = {
        #    'THRESHOLD' : computedThresh,
        #    'DEBUG_MODE' : True,
        #    'DEBUG_OUTPATH' : dbgPath
        #}

        # Configure spot filters - Classical filter on quality
        filter1 = FeatureFilter('QUALITY', 150, True)
        settings.addSpotFilter(filter1)

        # Configure tracker - We want to allow merges and fusions
        settings.trackerFactory = SparseLAPTrackerFactory()
        settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap(
        )  # almost good enough

        # Linking
        settings.trackerSettings[TrackerKeys.KEY_LINKING_MAX_DISTANCE] = 220.0
        # in pixels

        linkFeaturePenalties = HashMap()
        linkFeaturePenalties['Area'] = 1.0
        linkFeaturePenalties['POSITION_X'] = 1.0
        linkFeaturePenalties['POSITION_Y'] = 1.0
        #linkFeaturePenalties['Circ.'] = 1.0
        #linkFeaturePenalties['Mean'] = 1.0

        settings.trackerSettings[
            TrackerKeys.KEY_LINKING_FEATURE_PENALTIES] = linkFeaturePenalties
        # Gap closing
        settings.trackerSettings[TrackerKeys.KEY_ALLOW_GAP_CLOSING] = True
        settings.trackerSettings[TrackerKeys.KEY_GAP_CLOSING_MAX_FRAME_GAP] = 8
        settings.trackerSettings[
            TrackerKeys.KEY_GAP_CLOSING_MAX_DISTANCE] = 120.0
        # in pixels
        #settings.trackerSettings[TrackerKeys.KEY_GAP_CLOSING_FEATURE_PENALTIES] =  new HashMap<>(DEFAULT_GAP_CLOSING_FEATURE_PENALTIES));
        # Track splitting
        settings.trackerSettings[TrackerKeys.KEY_ALLOW_TRACK_SPLITTING] = False
        settings.trackerSettings[TrackerKeys.KEY_SPLITTING_MAX_DISTANCE] = 45.0
        # in pixels
        #settings.trackerSettings[TrackerKeys.KEY_SPLITTING_FEATURE_PENALTIES] =  new HashMap<>(DEFAULT_SPLITTING_FEATURE_PENALTIES));
        # Track merging
        settings.trackerSettings[TrackerKeys.KEY_ALLOW_TRACK_MERGING] = True
        settings.trackerSettings[TrackerKeys.KEY_MERGING_MAX_DISTANCE] = 45.0
        # in pixels
        #settings.trackerSettings[TrackerKeys.KEY_MERGING_FEATURE_PENALTIES] =  new HashMap<>(DEFAULT_MERGING_FEATURE_PENALTIES));
        # Others
        settings.trackerSettings[TrackerKeys.KEY_BLOCKING_VALUE] = float("inf")
        settings.trackerSettings[
            TrackerKeys.KEY_ALTERNATIVE_LINKING_COST_FACTOR] = 1.05
        settings.trackerSettings[TrackerKeys.KEY_CUTOFF_PERCENTILE] = 0.9

        # Configure track analyzers - Later on we want to filter out tracks
        # based on their displacement, so we need to state that we want
        # track displacement to be calculated. By default, out of the GUI,
        # no features are calculated.

        # The displacement feature is provided by the TrackDurationAnalyzer.
        settings.addTrackAnalyzer(TrackDurationAnalyzer())
        settings.addTrackAnalyzer(TrackBranchingAnalyzer())
        settings.addTrackAnalyzer(TrackIndexAnalyzer())
        settings.addTrackAnalyzer(TrackLocationAnalyzer())
        settings.addTrackAnalyzer(TrackSpeedStatisticsAnalyzer())

        settings.addSpotAnalyzerFactory(SpotIntensityAnalyzerFactory())
        settings.addSpotAnalyzerFactory(SpotContrastAndSNRAnalyzerFactory())

        # Configure track filters - We want to get rid of the two immobile spots at
        # the bottom right of the image. Track displacement must be above 10 pixels.
        #filter2 = FeatureFilter('TRACK_DISPLACEMENT', 1, True)
        #settings.addTrackFilter(filter2)
        #filter2 = FeatureFilter('TRACK_DISPLACEMENT', 1, True)
        #settings.addTrackFilter(filter2)

        #print("Spot feature analyzers: " + settings.toStringFeatureAnalyzersInfo())

        #-------------------
        # Instantiate plugin
        #-------------------

        trackmate = TrackMate(model, settings)
        trackmate.setNumThreads(1)

        #--------
        # Process
        #--------

        ok = trackmate.checkInput()
        if not ok:
            sys.exit(str(trackmate.getErrorMessage()))

        print("Processing " + chanName + "...")
        ok = trackmate.process()
        if not ok:
            sys.exit(str(trackmate.getErrorMessage()))

        #----------------
        # Display results
        #----------------
        print("Rendering...")

        # Set spot names based on track IDs
        # This allows track IDs to be displayed in the rendered video
        for tId in model.getTrackModel().trackIDs(True):
            trackSpots = model.getTrackModel().trackSpots(tId)
            for spot in trackSpots:
                spot.setName(str(tId))

        # Determine sub-tracks within a track
        # Since tracks can merge, we want to keep track of which track a spot is
        # in prior to the merge
        spotToSubTrackMap = {}
        spotIt = model.getSpots().iterator(False)
        trackModel = model.getTrackModel()
        subTrackCount = {}
        while spotIt.hasNext():
            spot = spotIt.next()
            spotEdges = trackModel.edgesOf(spot)
            # Find merge points within a track: ignore spots with fewer than 2 edges
            if (len(spotEdges) < 2):
                continue

            # We have a merge if we have multiple incoming edges
            incomingEdges = 0
            edgeIt = spotEdges.iterator()
            ancestorSpots = []
            while edgeIt.hasNext():
                edge = edgeIt.next()
                src = trackModel.getEdgeSource(edge)
                dst = trackModel.getEdgeTarget(edge)
                if dst.ID() == spot.ID():
                    ancestorSpots.append(src)
                    incomingEdges += 1
            # Ignore non-merges
            if incomingEdges < 2:
                continue

            trackId = trackModel.trackIDOf(spot)
            if trackId in subTrackCount:
                subTrackId = subTrackCount[trackId]
            else:
                subTrackId = 1
            for ancestorSpot in ancestorSpots:
                labelSubTrackAncestors(trackModel, spotToSubTrackMap,
                                       ancestorSpot, subTrackId, trackId,
                                       False)
                subTrackId += 1
            subTrackCount[trackId] = subTrackId

        # Spots after the last merge still need to be labeled
        for tId in trackModel.trackIDs(True):
            trackSpots = trackModel.trackSpots(tId)
            spotIt = trackSpots.iterator()
            lastSpot = None
            while spotIt.hasNext():
                spot = spotIt.next()
                outgoingEdges = 0
                spotEdges = trackModel.edgesOf(spot)
                edgeIt = spotEdges.iterator()
                while edgeIt.hasNext():
                    edge = edgeIt.next()
                    src = trackModel.getEdgeSource(edge)
                    dst = trackModel.getEdgeTarget(edge)
                    if src.ID() == spot.ID():
                        outgoingEdges += 1
                if outgoingEdges == 0 and len(spotEdges) > 0:
                    lastSpot = spot

            if tId in subTrackCount:
                subTrackId = subTrackCount[tId]
            else:
                subTrackId = 1
            if not lastSpot == None:
                labelSubTrackAncestors(trackModel, spotToSubTrackMap, lastSpot,
                                       subTrackId, tId, True)

        # Create output file
        trackOut = os.path.join(wellPath, chanName + "_spotToTrackMap.csv")
        trackFile = open(trackOut, 'w')
        # Fetch the track feature from the feature model.
        trackFile.write('Spot Id, Track Sub Id, Track Id, Frame \n')
        for spotId in spotToSubTrackMap:
            trackFile.write(
                str(spotId) + ', ' + ','.join(spotToSubTrackMap[spotId]) +
                '\n')
        trackFile.close()

        # Write Edge Set
        trackOut = os.path.join(wellPath, chanName + "_mergeEdgeSet.csv")
        trackFile = open(trackOut, 'w')
        trackFile.write('Track Id, Spot Id, Spot Id \n')
        edgeIt = trackModel.edgeSet().iterator()
        while edgeIt.hasNext():
            edge = edgeIt.next()
            src = trackModel.getEdgeSource(edge)
            dst = trackModel.getEdgeTarget(edge)
            trackId = trackModel.trackIDOf(edge)
            srcSubTrack = spotToSubTrackMap[src.ID()][0]
            dstSubTrack = spotToSubTrackMap[dst.ID()][0]
            if not srcSubTrack == dstSubTrack:
                trackFile.write(
                    str(trackId) + ', ' + str(src.ID()) + ', ' +
                    str(dst.ID()) + '\n')
        trackFile.close()

        selectionModel = SelectionModel(model)
        displayer = HyperStackDisplayer(model, selectionModel, impColor)
        displayer.setDisplaySettings(
            TrackMateModelView.KEY_TRACK_COLORING,
            PerTrackFeatureColorGenerator(model,
                                          TrackIndexAnalyzer.TRACK_INDEX))
        displayer.setDisplaySettings(
            TrackMateModelView.KEY_SPOT_COLORING,
            SpotColorGeneratorPerTrackFeature(model,
                                              TrackIndexAnalyzer.TRACK_INDEX))
        displayer.setDisplaySettings(TrackMateModelView.KEY_DISPLAY_SPOT_NAMES,
                                     True)
        displayer.setDisplaySettings(
            TrackMateModelView.KEY_TRACK_DISPLAY_MODE,
            TrackMateModelView.TRACK_DISPLAY_MODE_LOCAL_BACKWARD_QUICK)
        displayer.setDisplaySettings(
            TrackMateModelView.KEY_TRACK_DISPLAY_DEPTH, 2)
        displayer.render()
        displayer.refresh()

        trackmate.getSettings().imp = impColor
        coa = CaptureOverlayAction(None)
        coa.execute(trackmate)

        WindowManager.setTempCurrentImage(coa.getCapture())
        IJ.saveAs('avi', os.path.join(wellPath, chanName + "_out.avi"))

        imp.close()
        impColor.close()
        displayer.clear()
        displayer.getImp().hide()
        displayer.getImp().close()
        coa.getCapture().hide()
        coa.getCapture().close()

        # Echo results with the logger we set at start:
        model.getLogger().log(str(model))

        # The feature model, that stores edge and track features.
        fm = model.getFeatureModel()

        # Write output for tracks
        numTracks = model.getTrackModel().trackIDs(True).size()
        print "Writing track data for " + str(numTracks) + " tracks."
        trackDat = {}
        for tId in model.getTrackModel().trackIDs(True):
            track = model.getTrackModel().trackSpots(tId)

            # Ensure track spots dir exists
            trackOut = os.path.join(wellPath, chanName + "_track_spots")
            if not os.path.exists(trackOut):
                os.makedirs(trackOut)
            # Create output file
            trackOut = os.path.join(trackOut, "track_" + str(tId) + ".csv")
            trackFile = open(trackOut, 'w')

            # Write Header
            header = 'Name, ID, Frame, '
            for feature in track.toArray()[0].getFeatures().keySet():
                if feature == 'Frame':
                    continue
                header += feature + ", "
            header = header[0:len(header) - 2]
            header += '\n'
            trackFile.write(header)
            # Write spot data
            avgTotalIntensity = 0
            for spot in track:
                #print spot.echo()
                data = [
                    spot.getName(),
                    str(spot.ID()),
                    str(spot.getFeature('FRAME'))
                ]
                for feature in spot.getFeatures():
                    if feature == 'Frame':
                        continue
                    elif feature == 'TOTAL_INTENSITY':
                        avgTotalIntensity += spot.getFeature(feature)
                    data.append(str(spot.getFeature(feature)))
                trackFile.write(','.join(data) + '\n')
            trackFile.close()
            avgTotalIntensity /= len(track)

            # Write out track stats
            # Make sure dir exists
            trackOut = os.path.join(wellPath, chanName + "_tracks")
            if not os.path.exists(trackOut):
                os.makedirs(trackOut)
            # Create output file
            trackOut = os.path.join(trackOut, "track_" + str(tId) + ".csv")
            trackFile = open(trackOut, 'w')
            # Fetch the track feature from the feature model.
            header = ''
            for featName in fm.getTrackFeatureNames():
                header += featName + ", "
            header = header[0:len(header) - 2]
            header += '\n'
            trackFile.write(header)

            features = ''
            for featName in fm.getTrackFeatureNames():
                features += str(fm.getTrackFeature(tId, featName)) + ', '
            features = features[0:len(features) - 2]
            features += '\n'
            trackFile.write(features)
            trackFile.write('\n')
            trackFile.close()

            trackDat[tId] = [
                str(tId),
                str(fm.getTrackFeature(tId, 'TRACK_DURATION')),
                str(avgTotalIntensity),
                str(fm.getTrackFeature(tId, 'TRACK_START')),
                str(fm.getTrackFeature(tId, 'TRACK_STOP'))
            ]

        # Create output file
        trackOut = os.path.join(wellPath, chanName + "_trackSummary.csv")
        trackFile = open(trackOut, 'w')
        # Fetch the track feature from the feature model.
        trackFile.write(
            'Track Id, Duration, Avg Total Intensity, Start Frame, Stop Frame \n'
        )
        for track in trackDat:
            trackFile.write(','.join(trackDat[track]) + '\n')
        trackFile.close()

        trackOut = os.path.join(wellPath, chanName + "_trackModel.xml")
        trackFile = File(trackOut)
        writer = TmXmlWriter(trackFile, model.getLogger())
        #writer.appendLog( logPanel.getTextContent() );
        writer.appendModel(trackmate.getModel())
        writer.appendSettings(trackmate.getSettings())
        #writer.appendGUIState( controller.getGuimodel() );
        writer.writeToFile()

    model.clearSpots(True)
    model.clearTracks(True)

    return trackDat
Example #27
0
    del pix2
    del pix3
    del pix4
    if not os.path.exists(subsub):
        os.mkdir(subsub)
    pixels = []
    for j in range(4):
        System.gc()
        imp = segmentator.applyClassifier(imps[j], 0, True)
        imp = imp.getStack()
        imp = imp.getProcessor(1)
        cm = imp.getColorModel()
        pixels.append(imp.getPixels())
    pix1 = pixels[0]
    pix2 = pixels[1]
    pix3 = pixels[2]
    pix4 = pixels[3]
    pixcomb = pix1[:-s * d1] + pix2[s * d1:-s * d1] + pix3[s * d1:-s *
                                                           d1] + pix4[s * d1:]
    result = ImagePlus("Result", FloatProcessor(d1, dimentions[1], pixcomb,
                                                cm))
    IJ.save(result, subsub + "\\result_RAW.tif")
    IJ.run(result, "Despeckle", "")
    strel = morphology.Strel.Shape.DISK.fromDiameter(3)
    result = morphology.Morphology.erosion(result.getProcessor(), strel)
    result = result.convertToByteProcessor()
    result = ImagePlus("plus", result)
    IJ.run(result, "Gaussian Blur...", "sigma=15")
    IJ.save(result, subsub + "\\result_READY.tif")
    result.close()
		tracked[i]= 11
print test.labelValues
fp= ShortProcessor(len(tracked), 1,tracked , None)

labelerImp= ImagePlus("labeler", fp)
src2=clij2.push(labelerImp)
conLabeledStack=ImageStack(imp1.width, imp1.height)


if frames>1:
	for nFrame in range(1,frames+1):

		imp3=extractFrame(imp1, nFrame)
		src=clij2.push(imp3)
		dst=clij2.create(src)
		clij2.replaceIntensities(src, src2, dst)
		LabeledImp=clij2.pull(dst)
		conLabeledStack = concatStacks( conLabeledStack, LabeledImp)
	concatLabeledImp= ImagePlus("Labeled "+imageName, conLabeledStack)
	
	ImageConverter.setDoScaling(0)
	ImageConverter(concatLabeledImp).convertToGray16()
	
	IJ.setMinAndMax(concatLabeledImp, 0, 255)
	concatLabeledImp.setCalibration(imp1.getCalibration())
	concatLabeledImp.setDimensions(1, imp1.getNSlices(), imp1.getNFrames())
	concatLabeledImp = CompositeImage(concatLabeledImp, CompositeImage.COMPOSITE)
	concatLabeledImp.show()
	IJ.run("glasbey_on_dark")
	labelerImp.close()
Example #29
0
                "microscope=WideField wavelength=500 na=1.40 pinhole=1 text1=[Sample infos:\n] text2=Comments:\n scale=5 save save=['"
                + filename + "']")

            # close the tiny crop
            IJ.selectWindow("duplicate_spot")
            image_2.close()

            # open output from MetroloJ
            f = open(directory + "/psf_bead_" + str(count) + "_summary.xls")
            text = f.readlines()

            # parses from XLS to a float, multiply by the correction factor
            x_res = float(text[1].split("\t")[1].split(" ")[0]) * corr_factor_x
            y_res = float(text[2].split("\t")[1].split(" ")[0]) * corr_factor_y
            z_res = float(text[3].split("\t")[1].split(" ")[0]) * corr_factor_z

            # writes new line to the summary output
            outputfile.write(
                str(count) + "," + str(x_res) + "," + str(y_res) + "," +
                str(z_res) + "\n")
            f.close()

        # close everything else!
        im_slice.close()
        image.changes = False
        image.close()
        IJ.selectWindow("Results")
        IJ.run("Close")

        outputfile.close()
	## Outputs each stitched z plane as a separate file
	iReader = ImageReader()
	iReader.setId(parentLSMFilePath)
	for z in range(max_coords[2]+basic_info[4]):
	## for z in range(50,51):
		IJ.showStatus("z: "+str(z+1)+" of "+str(max_coords[2]+basic_info[4]))
		chIps = []
		resImages = []
		for ch in range(basic_info[0]):
			chIps.append(ByteProcessor(max_coords[0]+scale_info[2],max_coords[1]+scale_info[2]))
		for ch in range(basic_info[0]):
			resImages.append(ImagePlus("ch"+str(ch+1),chIps[ch]))
		for se in range(basic_info[1]):
			IJ.showProgress(se,basic_info[1])
			if z >= coords_upscaled[se][2] and z <= coords_upscaled[se][2]+basic_info[4]-1:
				iReader.setSeries(se)
				for ch in range(basic_info[0]):
					byteArray = iReader.openBytes((z-coords_upscaled[se][2])*basic_info[0]+ch)
					testIp = ByteProcessor(scale_info[2],scale_info[2],byteArray)
					testImage = ImagePlus("tester",testIp)
					Image_stamper.stampStack(testImage,resImages[ch],coords_upscaled[se][0],coords_upscaled[se][1],0)			
					activeIp = chIps[ch]
					testImage.close()
					
					
		for ch in range(len(resImages)):
			IJ.saveAsTiff(resImages[ch],parentLSMFilePath+"_tiles/v_img/img_z_"+str(z+1)+"_c_"+str(ch+1)+".tif")
		#outPlaneImage = RGBStackMerge.mergeChannels(resImages,False)
		#IJ.saveAsTiff(outPlaneImage,parentLSMFilePath+"_tiles/v_img/img_z_"+str(z+1)+".tif")
		#outPlaneImage.close()
Example #31
0
    if 'w' in colors:
	if len(colors) > 2:
    	    composite = RGBStackMerge.mergeChannels(imps_for_comp, True)
    	    IJ.saveAsTiff(composite, merge_output_dir + '/' + stage_pos)
    	    composite.close()
    else:
	if len(colors) > 1:
    	    composite = RGBStackMerge.mergeChannels(imps_for_comp, True)
    	    IJ.saveAsTiff(composite, merge_output_dir + '/' + stage_pos)
    	    composite.close()
    imps_for_z_comp = [None, None, None, None, None, None, None]
    if blue:
        z_cyan = maxZprojection(c_imp)
        IJ.saveAsTiff(z_cyan, z_proj_dir+'/blue/'+stage_pos)
        imps_for_z_comp[4] = z_cyan
        c_imp.close()
    if cyan:
        z_cyan = maxZprojection(c_imp)
        IJ.saveAsTiff(z_cyan, z_proj_dir+'/cyan/'+stage_pos)
        imps_for_z_comp[4] = z_cyan
        c_imp.close()
    if green:
        z_green = maxZprojection(g_imp)
        IJ.saveAsTiff(z_green, z_proj_dir+'/green/'+stage_pos)
        imps_for_z_comp[1] = z_green
        g_imp.close()
    if yellow:
        z_green = maxZprojection(g_imp)
        IJ.saveAsTiff(z_green, z_proj_dir+'/yellow/'+stage_pos)
        imps_for_z_comp[1] = z_green
        g_imp.close()
Example #32
0
jDD = SM(K, K).eqInnerProductMatrix(jD)
jMP = MP(jD, jDD)

# matching pursuit to create a sparse appoximation

w = []
for i in range(0, p):
    q = x[i]
    if Rt == "OMP":
        W = jMP.vsOMP(q, t_w)
    elif Rt == "MP":
        W = jMP.vsBMP(q, t_w)
    else:
        W = jMP.vsORMP(q, t_w)
    w.append(W)

w2 = zip(*w)

Sp = Matrix(w2).getColumnPackedCopy()

#return matrices to images
ipFloat = FloatProcessor(K, imp2.height * imp2.width, Sp)
impa = ImagePlus("Sp", ipFloat)
impa.show()
IJ.run("Montage to Stack...",
       "columns=1 rows=" + str(imp2.height) + " border=0")
imp3 = IJ.getImage()
IJ.run("Reslice [/]...", "output=1.000 start=Left avoid")
impa.close()
imp3.close()
Example #33
0
            ip1 = cellstack.getProcessor(zslice)
            ip1.resetMinAndMax()
            ip1.blurGaussian(parameters['cellsigma'])
            bp1 = ip1.convertToByte(1)
            impBin1 = ImagePlus('BinarizedCells ' + str(zslice), bp1)
            impBin1.show()
            IJ.run('Auto Threshold',
                   'method=' + parameters['cellmethod'] + ' white')
            IJ.run(
                'Analyze Particles...',
                'size=' + parameters['cellsize'] + ' circularity=' +
                parameters['cellcircularity'] + ' exclude add')
            if rmi.getCount() == 0:
                print 'No cell ROI on slice ' + str(zslice)
                impBin1.changes = False
                impBin1.close()
                continue

            #Get nuclei ROIs
            ip2 = nucleistack.getProcessor(zslice)
            ip2.resetMinAndMax()
            ip2.blurGaussian(parameters['nucsigma'])
            bp2 = ip2.convertToByte(1)
            impBin2 = ImagePlus('BinarizedNuclei', bp2)
            impBin2.show()
            rmi.select(impBin2, rmi.getCount() - 1)
            IJ.setBackgroundColor(0, 0, 0)
            IJ.run('Clear Outside')
            impBin2.deleteRoi()
            IJ.selectWindow('BinarizedNuclei')
            IJ.run('Auto Threshold', 'method=' + parameters['nucmethod'] +
def getGrayScaleImage(currIP, c, chanName, cfg):
    if (cfg.hasValue(ELMConfig.upperLeftExclusionX)):
        ulExclusionX = cfg.getValue(ELMConfig.upperLeftExclusionX)
    else:
        ulExclusionX = 0

    if (cfg.hasValue(ELMConfig.upperLeftExclusionY)):
        ulExclusionY = cfg.getValue(ELMConfig.upperLeftExclusionY)
    else:
        ulExclusionY = 0

    if (cfg.hasValue(ELMConfig.lowerRightExclusionX)):
        lrExclusionX = cfg.getValue(ELMConfig.lowerRightExclusionX)
    else:
        lrExclusionX = currIP.getWidth()

    if (cfg.hasValue(ELMConfig.lowerRightExclusionY)):
        lrExclusionY = cfg.getValue(ELMConfig.lowerRightExclusionY)
    else:
        lrExclusionY = currIP.getHeight()

    imgType = currIP.getType()
    if (chanName in cfg.getValue(
            ELMConfig.chansToSkip)):  # Don't process skip channels
        currIP.close()
        return None
    elif imgType == ImagePlus.COLOR_RGB or imgType == ImagePlus.COLOR_256:
        if (chanName == ELMConfig.BRIGHTFIELD):
            toGray = ImageConverter(currIP)
            toGray.convertToGray8()
        elif (chanName == ELMConfig.BLUE) \
                or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED) \
                or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN): #
            chanIdx = 2
            if (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED):
                chanIdx = 0
            elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN):
                chanIdx = 1
            imgChanns = ChannelSplitter.split(currIP)
            currIP.close()
            currIP = imgChanns[chanIdx]

            # Clear the Exclusion zone, so it doesn't mess with  thresholding
            imgProc = currIP.getProcessor()
            imgProc.setColor(Color(0, 0, 0))
            imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(),
                             currIP.getHeight())
            imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY)
        elif (chanName == ELMConfig.YELLOW):
            # Clear the Exclusion zone, so it doesn't mess with  thresholding
            imgProc = currIP.getProcessor()
            imgProc.setColor(Color(0, 0, 0))
            imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(),
                             currIP.getHeight())
            imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY)

            # Create a new image that consists of the average of the red & green channels
            title = currIP.getTitle()
            width = currIP.getWidth()
            height = currIP.getHeight()
            newPix = ByteProcessor(width, height)
            for x in range(0, width):
                for y in range(0, height):
                    currPix = currIP.getPixel(x, y)
                    newPix.putPixel(x, y, (currPix[0] + currPix[1]) / 2)
            currIP.close()
            currIP = ImagePlus(title, newPix)
        else:
            print "ERROR: Unrecognized channel name! Name: " + chanName
            currIP.close()
            return None
    elif imgType == ImagePlus.GRAY16 or imgType == ImagePlus.GRAY32 or imgType == ImagePlus.GRAY8:
        if not imgType == ImagePlus.GRAY8:
            toGray = ImageConverter(currIP)
            toGray.convertToGray8()
    else:
        print "ERROR: Unrecognized channel name & image type! Channel: " + chanName + ", imgType: " + str(
            imgType)
        currIP.close()
        return None

    return currIP
def perform_user_qc(in_imp, edges, alt_edges, fixed_anchors_list, params):
	"""allow the user to intervene to fix erroneously identified membrane edges"""
	n_frames = in_imp.getNFrames();
	n_channels = in_imp.getNChannels();
	output_folder = params.output_path;
	current_edges = edges;
	rgbstack = ImageStack(in_imp.getWidth(), in_imp.getHeight());
	if n_frames > 1:
		for tidx in range(n_frames): 
			in_imp.setT(tidx+1);
			ip = in_imp.getProcessor();
			rgbip = ip.convertToRGB();
			rgbstack.addSlice(rgbip);
	else:
		for cidx in range(n_channels):
			in_imp.setC(cidx+1);
			ip = in_imp.getProcessor();
			rgbip = ip.convertToRGB();
			rgbstack.addSlice(rgbip);
	imp = ImagePlus(("RGB " + in_imp.getTitle()), rgbstack);
	IJ.run("Colors...", "foreground=red background=white selection=yellow");
	for tidx in range(imp.getNSlices()):
		imp.setSlice(tidx+1);
		for anchor in params.manual_anchor_positions:
			imp.setRoi(PointRoi(anchor[0], anchor[1]));
			IJ.run(imp, "Draw", "slice");
	imp.show();
	autoset_zoom(imp);
	imp.setPosition(1);
	imp.setRoi(current_edges[0]);
	if n_frames > 1:
		listener = UpdateRoiImageListener(current_edges);
		imp.addImageListener(listener);
	IJ.setTool("freeline");
	do_flip = True;
	while do_flip:
		dialog = NonBlockingGenericDialog("User quality control");
		dialog.enableYesNoCancel("Continue", "Flip all edges");
		dialog.setCancelLabel("Cancel analysis");
		dialog.addMessage("Please redraw the membrane edges as necessary, \n" + 
						"making sure to draw beyond anchor points at either end...\n" + 
						"Click OK when done. ");
		p = Panel();
		but = Button("Flip this edge");
		al = Listener(edges, alt_edges, imp);
		but.addActionListener(al);
		p.add(but);
		dialog.addPanel(p);
		dialog.showDialog();
		if dialog.wasCanceled():
			raise KeyboardInterrupt("Run canceled");
		elif dialog.wasOKed():
			do_flip = False;
		else:
			print("flip edges");
			do_flip = True;
			if n_frames > 1:
				imp.removeImageListener(listener);
			current_edges = alt_edges if (current_edges == edges) else edges;
			imp.setPosition(1);
			imp.setRoi(current_edges[0]);
			if n_frames > 1:
				listener = UpdateRoiImageListener(current_edges);
				imp.addImageListener(listener);

	last_roi = imp.getRoi();
	if n_frames > 1:
		qcd_edges = listener.getRoiList();
		if imp.getNFrames() > imp.getNSlices():
			qcd_edges[imp.getT() - 1] = last_roi;
		else:
			qcd_edges[imp.getZ() - 1] = last_roi;
		imp.removeImageListener(listener);
	else:
		qcd_edges = [last_roi];
	mbio.save_qcd_edges2(qcd_edges, output_folder);
	# next four lines are a quick and dirty hack...
	if n_frames > 1:
		nframes = imp.getNFrames() if imp.getNFrames()>imp.getNSlices() else imp.getNSlices();
	else:
		nframes = n_frames;
	for fridx in range(0, nframes):
		if (qcd_edges[fridx].getType()==Roi.FREELINE) or (qcd_edges[fridx].getType()==Roi.POLYLINE):
			if (fridx == 0) or params.constrain_anchors:
				anchors = params.manual_anchor_positions;
			else:
				anchors = fixed_anchors_list[fridx - 1];
			fixed_anchors = mb.fix_anchors_to_membrane(anchors, qcd_edges[fridx], params);
			fixed_anchors = mb.order_anchors(fixed_anchors, params.manual_anchor_midpoint);
			fixed_anchors_list[fridx] = fixed_anchors;
			poly =  qcd_edges[fridx].getInterpolatedPolygon(0.25, False);
			polypoints = [(x,y) for x,y in zip(poly.xpoints, poly.ypoints)];
			idx = [polypoints.index(fixed_anchors[0]), polypoints.index(fixed_anchors[1])];
			idx.sort();
			polypoints = polypoints[idx[0]:idx[1]];
			newedge = PolygonRoi([x for (x,y) in polypoints], 
									[y for (x,y) in polypoints], 
									Roi.POLYLINE);
			newedge = mb.check_edge_order(anchors, newedge);
			imp.setPosition(fridx + 1);
			imp.setRoi(newedge);
			IJ.run(imp, "Interpolate", "interval=1.0 smooth adjust");
			IJ.run(imp, "Fit Spline", "");
			qcd_edges[fridx] = imp.getRoi();
	mbio.save_qcd_edges2(qcd_edges, output_folder);
	imp.changes = False;
	imp.close();
	return qcd_edges, fixed_anchors_list;
		IJ.log('Working on short time course around cut at frame ' + str(cutIndex))
		imStack = ij.ImageStack(512,512)
		for fileIndex in range(-1,21):
			filename = "%06d_mix.tif" % (cutIndex+fileIndex)
			#print filename
			imp = IJ.openImage(os.path.join(srcDir, folder, filename))
			ip = imp.getProcessor()
			#print(ip)
			imStack.addSlice(filename, ip)

		newFileName = "%s_E%sC%d.tif" % (date, embryoNumber, 1+cutIndices.index(cutIndex))
		newImp = ImagePlus(newFileName, imStack)
		newImp.show()
		IJ.log('Saving data to ' + os.path.join(outputDir, newFileName))
		IJ.save(newImp,  os.path.join(outputDir, newFileName))
		newImp.close()

	# Also save whole lot as an image stack...
	IJ.log('Working on complete time course - this might take a while...')
	images = [f for f in os.listdir(os.path.join(srcDir, folder))
	    if f.endswith('mix.tif')]

	imStack = ij.ImageStack(512,512)
	for image in images:
		imp = IJ.openImage(os.path.join(srcDir, folder, image))
		ip = imp.getProcessor()
		imStack.addSlice(image, ip)

	newFileName = "%s_E%s complete data.tif" % (date, embryoNumber)
	newImp = ImagePlus(newFileName, imStack)
	newImp.show()
Example #37
0
	
	
	
	
	
	
	image.setDimensions(2, z_slices, 1)
	image.setOpenAsHyperStack(True)
	print(image.isHyperStack(), image.getNChannels(), image.getOverlay())
	#image.flattenStack()
	image.show()
	fs = FileSaver(image)
	filepath = directory + "/" + filename + "_coloc.tiff" 
	
	fs.saveAsTiff(filepath) 
	image.close()

	image = IJ.getImage()
	IJ.run(image_dapi,"Convert to Mask", "method=Otsu background=Default calculate")
	fs = FileSaver(image_dapi)
	filepath = directory + "/" + filename + "_dapi.tiff" 
	
	fs.saveAsTiff(filepath) 
	
	
	#image = IJ.getImage()
	#image.close()
	
	[red_spots, red_spots_dapi] = get_red_spots(rest, z_slices, image_dapi)
	
	[green_spots, green_spots_dapi] = get_green_spots(rest, z_slices, image_dapi)
def straighten_vessel(imp, smooth_centres, it=1, save_output=False):
    """use IJ straigtening tool to deal with convoluted vessels"""
    print("straighten vessel input image dims = " + str(imp.getWidth()) + "x" +
          str(imp.getHeight()))
    rot_imp = utils.rot3d(imp, axis='x')
    if it == 1:
        roi = PolygonRoi([x for x, y, z in smooth_centres],
                         [z for x, y, z in smooth_centres], Roi.FREELINE)
        print("len interp polygon = " +
              str(roi.getInterpolatedPolygon().npoints))
    elif it == 2:
        new_zs = [z for z in range(rot_imp.getWidth())]
        new_ys = lin_interp_1d([z for x, y, z in smooth_centres],
                               [y for x, y, z in smooth_centres], new_zs)
        roi = PolygonRoi(new_zs, new_ys, Roi.FREELINE)

    split_ch = ChannelSplitter().split(rot_imp)
    mch_imp = split_ch[0]
    egfp_imp = split_ch[1]
    roi_imp = split_ch[2]

    roi_imp.setRoi(roi)

    for zidx in range(egfp_imp.getNSlices()):
        for chidx in range(3):
            split_ch[chidx].setZ(zidx + 1)
            split_ch[chidx].setRoi(roi)
            ip = Straightener().straightenLine(split_ch[chidx], 150)
            if chidx == 1:
                if zidx == 0:
                    egfp_straight_stack = ImageStack(ip.getWidth(),
                                                     ip.getHeight())
                egfp_straight_stack.addSlice(ip)
            elif chidx == 0:
                if zidx == 0:
                    mch_straight_stack = ImageStack(ip.getWidth(),
                                                    ip.getHeight())
                mch_straight_stack.addSlice(ip)
            else:
                if zidx == 0:
                    roi_straight_stack = ImageStack(ip.getWidth(),
                                                    ip.getHeight())
                roi_straight_stack.addSlice(ip)

    egfp_out_imp = ImagePlus("Straightened EGFP", egfp_straight_stack)
    mch_out_imp = ImagePlus("Straightened mCh", mch_straight_stack)
    roi_out_imp = ImagePlus("Straightened ROI", roi_straight_stack)
    if it == 2:
        egfp_out_imp = utils.rot3d(egfp_out_imp, axis='y')
        mch_out_imp = utils.rot3d(mch_out_imp, axis='y')
        roi_out_imp = utils.rot3d(roi_out_imp, axis='y')
    egfp_out_imp.show()
    mch_out_imp.show()
    roi_out_imp.show()
    IJ.run(
        "Merge Channels...",
        "c1=[" + mch_out_imp.getTitle() + "] c2=[" + egfp_out_imp.getTitle() +
        "] c7=[" + roi_out_imp.getTitle() + "] create keep")
    #	WaitForUserDialog("pause").show();
    #	if it==1:
    egfp_out_imp.close()
    mch_out_imp.close()
    roi_out_imp.close()
    new_composite = IJ.getImage()
    if save_output:
        FileSaver(new_composite).saveAsTiffStack(
            os.path.join(output_path, "after rotation " + str(it) + ".tif"))
    return new_composite
def getThresholdedMask(currIP, c, z, t, chanName, cfg, wellPath, dbgOutDesc):
    if (cfg.hasValue(ELMConfig.upperLeftExclusionX)):
        ulExclusionX = cfg.getValue(ELMConfig.upperLeftExclusionX)
    else:
        ulExclusionX = 0

    if (cfg.hasValue(ELMConfig.upperLeftExclusionY)):
        ulExclusionY = cfg.getValue(ELMConfig.upperLeftExclusionY)
    else:
        ulExclusionY = 0

    if (cfg.hasValue(ELMConfig.lowerRightExclusionX)):
        lrExclusionX = cfg.getValue(ELMConfig.lowerRightExclusionX)
    else:
        lrExclusionX = currIP.getWidth()

    if (cfg.hasValue(ELMConfig.lowerRightExclusionY)):
        lrExclusionY = cfg.getValue(ELMConfig.lowerRightExclusionY)
    else:
        lrExclusionY = currIP.getHeight()

    imgType = currIP.getType()
    if (chanName in cfg.getValue(
            ELMConfig.chansToSkip)):  # Don't process skip channels
        currIP.close()
        return None
    elif imgType == ImagePlus.COLOR_RGB or imgType == ImagePlus.COLOR_256:
        if (chanName == ELMConfig.BRIGHTFIELD):
            toGray = ImageConverter(currIP)
            toGray.convertToGray8()
            if cfg.params[ELMConfig.imgType] == "png":
                darkBackground = True
            else:
                darkBackground = False
        elif (chanName == ELMConfig.BLUE) \
                or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED) \
                or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN): #
            chanIdx = 2
            if (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED):
                chanIdx = 0
            elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN):
                chanIdx = 1
            imgChanns = ChannelSplitter.split(currIP)
            currIP.close()
            currIP = imgChanns[chanIdx]

            # Clear the Exclusion zone, so it doesn't mess with  thresholding
            imgProc = currIP.getProcessor()
            imgProc.setColor(Color(0, 0, 0))
            imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(),
                             currIP.getHeight())
            imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY)
            darkBackground = True
        elif (chanName == ELMConfig.YELLOW):
            # Clear the Exclusion zone, so it doesn't mess with  thresholding
            imgProc = currIP.getProcessor()
            imgProc.setColor(Color(0, 0, 0))
            imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(),
                             currIP.getHeight())
            imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY)

            # Create a new image that consists of the average of the red & green channels
            title = currIP.getTitle()
            width = currIP.getWidth()
            height = currIP.getHeight()
            newPix = ByteProcessor(width, height)
            for x in range(0, width):
                for y in range(0, height):
                    currPix = currIP.getPixel(x, y)
                    newPix.putPixel(x, y, (currPix[0] + currPix[1]) / 2)
            currIP.close()
            currIP = ImagePlus(title, newPix)
            darkBackground = True
        else:
            print "ERROR: Unrecognized channel name! Name: " + chanName
            currIP.close()
            return None
    elif imgType == ImagePlus.GRAY16 or imgType == ImagePlus.GRAY32 or imgType == ImagePlus.GRAY8:
        if (chanName == ELMConfig.BRIGHTFIELD):
            if cfg.params[ELMConfig.imgType] == "png":
                darkBackground = True
            else:
                darkBackground = False
        else:
            darkBackground = True

        if not imgType == ImagePlus.GRAY8:
            toGray = ImageConverter(currIP)
            toGray.convertToGray8()
    else:
        print "ERROR: Unrecognized channel name & image type! Channel: " + chanName + ", imgType: " + str(
            imgType)
        currIP.close()
        return None

    WindowManager.setTempCurrentImage(currIP)

    if cfg.getValue(ELMConfig.debugOutput):
        IJ.saveAs('png',
                  os.path.join(wellPath, "Processing_" + dbgOutDesc + ".png"))

    upperThreshImg = currIP.duplicate()

    # If threshold value is set, use it
    if (cfg.hasValue(ELMConfig.imageThreshold)):
        thresh = cfg.getValue(ELMConfig.imageThreshold)
        if (darkBackground):
            currIP.getProcessor().setThreshold(thresh, 255,
                                               ImageProcessor.NO_LUT_UPDATE)
        else:
            currIP.getProcessor().setThreshold(0, thresh,
                                               ImageProcessor.NO_LUT_UPDATE)
    else:  # Otherise, automatically compute threshold
        threshMethod = "Default"
        if cfg.hasValue(ELMConfig.thresholdMethod):
            threshMethod = cfg.getValue(ELMConfig.thresholdMethod)

        currIP.getProcessor().setAutoThreshold(threshMethod, darkBackground,
                                               ImageProcessor.NO_LUT_UPDATE)
        threshRange = currIP.getProcessor().getMaxThreshold(
        ) - currIP.getProcessor().getMinThreshold()
        #print "\t\tZ = " + str(z) + ", T = " + str(t) +  ", chan " + chanName + ": Using default threshold of minThresh: " + str(currIP.getProcessor().getMinThreshold()) + ", maxThresh: " + str(currIP.getProcessor().getMaxThreshold())
        if currIP.getType() != ImagePlus.GRAY8:
            print "\tChannel " + chanName + " is not GRAY8, instead type is %d" % currIP.getType(
            )
        if threshRange > cfg.getValue(ELMConfig.maxThreshRange):
            if (cfg.hasValue(ELMConfig.defaultThreshold)):
                thresh = cfg.getValue(ELMConfig.defaultThreshold)
                print "\t\tZ = " + str(z) + ", T = " + str(
                    t
                ) + ", chan " + chanName + ": Using default threshold of " + str(
                    thresh) + ", minThresh: " + str(currIP.getProcessor(
                    ).getMinThreshold()) + ", maxThresh: " + str(
                        currIP.getProcessor().getMaxThreshold())
                if (darkBackground):
                    currIP.getProcessor().setThreshold(
                        thresh, 255, ImageProcessor.NO_LUT_UPDATE)
                else:
                    currIP.getProcessor().setThreshold(
                        0, thresh, ImageProcessor.NO_LUT_UPDATE)
            else:
                print "\t\tZ = " + str(z) + ", T = " + str(
                    t
                ) + ", chan " + chanName + ": Ignored Objects due to threshold range! minThresh: " + str(
                    currIP.getProcessor().getMinThreshold(
                    )) + ", maxThresh: " + str(
                        currIP.getProcessor().getMaxThreshold())
                currIP.close()
                return None

    IJ.run(currIP, "Convert to Mask", "")

    # Clear out exclusion zones
    imgProc = currIP.getProcessor()
    imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(),
                     currIP.getHeight())
    imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY)

    IJ.run(currIP, "Close-", "")

    # Brightfield has an additional thresholding step
    if cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.BRIGHTFIELD:
        if cfg.getValue(ELMConfig.debugOutput):
            IJ.saveAs(
                'png', os.path.join(wellPath,
                                    "OrigMask_" + dbgOutDesc + ".png"))

        upperThresh = 255 * 0.95
        upperThreshImg.getProcessor().setThreshold(
            upperThresh, 255, ImageProcessor.NO_LUT_UPDATE)
        IJ.run(upperThreshImg, "Convert to Mask", "")
        IJ.run(upperThreshImg, "Close-", "")
        if cfg.getValue(ELMConfig.debugOutput):
            WindowManager.setTempCurrentImage(upperThreshImg)
            IJ.saveAs(
                'png',
                os.path.join(wellPath,
                             "UpperThreshMask_" + dbgOutDesc + ".png"))

        ic = ImageCalculator()
        compositeMask = ic.run("OR create", currIP, upperThreshImg)
        IJ.run(compositeMask, "Close-", "")
        currIP.close()
        currIP = compositeMask
        WindowManager.setTempCurrentImage(currIP)

    if cfg.getValue(ELMConfig.debugOutput):
        WindowManager.setTempCurrentImage(currIP)
        IJ.saveAs('png', os.path.join(wellPath,
                                      "Binary_" + dbgOutDesc + ".png"))

    upperThreshImg.close()
    return currIP
def scaleandfilter(infile,outfile,scalex,scaley,scalez,anisofilter,runtube):
	
	print ("infile is: "+infile)
	imp = Opener().openImage(infile)
	print imp
	print "scalex = %f; scaley = %f ; scalez = %f" % (scalex,scaley,scalez)
	
	# Rescale
	cal = imp.getCalibration()
	iml = ImgLib.wrap(imp)
	scaledimg = Scale3D(iml, scalex, scaley, scalez)
	imp2=ImgLib.wrap(scaledimg)
	
	# find range of pixel values for scaled image
	from mpicbg.imglib.algorithm.math import ComputeMinMax
	# (for imglib2 will be: net.imglib2.algorithm.stats)
	minmax=ComputeMinMax(scaledimg)
	minmax.process()
	(min,max)=(minmax.getMin().get(),minmax.getMax().get())
	# Make a copy of the stack (converting to 8 bit as we go)
	stack = ImageStack(imp2.width, imp2.height)
	print "min = %e, max =%e" % (min,max)
	for i in xrange(1, imp2.getNSlices()+1):
		imp2.setSliceWithoutUpdate(i)
		ip=imp2.getProcessor()
		# set range
		ip.setMinAndMax(min,max)
		stack.addSlice(str(i), ip.convertToByte(True))
	
	# save copy of calibration info
	cal=imp.getCalibration()
	# close original image
	imp.close()
	# make an image plus with the copy
	scaled = ImagePlus(imp2.title, stack)
	
	# Deal with calibration info which didn't seem to come along for the ride
	cal.pixelWidth/=scalex
	cal.pixelHeight/=scaley
	cal.pixelDepth/=scalez
	scaled.setCalibration(cal)
	print "dx = %f; dy=%f; dz=%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth)
	
	intif=infile+".tif"
	outtif=infile+"-filtered.tif"
	if anisofilter.upper() != 'FALSE':
		print("saving input file as "+intif)
		f=FileSaver(scaled)
		f.saveAsTiffStack(intif)
		scaled.close()
		# anisotropic filtering
		anisopts="-scanrange:10 -tau:2 -nsteps:2 -lambda:0.1 -ipflag:0 -anicoeff1:1 -anicoeff2:0 -anicoeff3:0"
		anisopts=anisopts+" -dx:%f -dy:%f -dz:%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth)

		if sys.version_info > (2, 4):
			#for testing
			# subprocess.check_call(["cp",intif,outtif])
			subprocess.check_call([anisofilter]+anisopts.split(' ')+[intif,outtif])
		else:
			os.system(" ".join([anisofilter]+anisopts.split(' ')+[intif,outtif]))
		# Open anisofilter output back into Fiji
		print("Opening output tif: "+outtif)
		scaled = Opener().openImage(outtif)
		scaled.setCalibration(cal)
	
	# Hessian (tubeness)
	print("Running tubeness")
	if(runtube):
		tp=TubenessProcessor(1.0,False)
		result = tp.generateImage(scaled)
		IJ.run(result, "8-bit","")
	else:
		result=scaled
	# Save out file
	fileName, fileExtension = os.path.splitext(outfile)
	print("Saving as "+fileExtension+": "+outfile)
	if fileExtension.lower()=='.nrrd':
		nw=Nrrd_Writer()
		nw.setNrrdEncoding("gzip")
		nw.save(result,outfile)
	else:
		# Save to PIC
		IJ.run(result,"Biorad ...", "biorad=["+outfile+"]")
	scaled.close()
	result.close()
Example #41
0
class gui(JFrame):
	def __init__(self): # constructor 
		#origing of coordinates
		self.coordx = 300
		self.coordy = 50

		self.imageCount = 0 #a counter for the image list
		self.listendFlag = 0 #some values to check
		#inintialize values
		self.imLeft = None
		self.imRight = None
		self.chosenOne = None
		self.chosenIm = None
		#create panel (what is inside the GUI)
		self.panel = self.getContentPane()
		self.panel.setLayout(GridLayout(5,2))

		#define buttons here:
		quitButton = JButton("Quit", actionPerformed=self.quit)
		loadButton = JButton("Load", actionPerformed=self.load)
		leftButton = JButton("Choose Left", actionPerformed = self.ChooseLeft)
		rightButton = JButton("Choose Right", actionPerformed = self.ChooseRight)
		ThresButton = JButton("Threshold",actionPerformed = self.ImThresh)
		self.ThreshField = JTextField("5", 1)
		StartConversionButton = JButton("Start Conversion", actionPerformed = self.StartConv)
		ConvertButton = JButton("Convert Image", actionPerformed = self.ImConvert)
		
		#Zslider = JSlider(JSlider.HORIZONTAL,0, 100, 0)

		#add buttons here
		self.panel.add(loadButton)
		self.panel.add(quitButton)
		self.panel.add(leftButton)
		self.panel.add(rightButton)
		self.panel.add(self.ThreshField)
		self.panel.add(ThresButton)
		self.panel.add(StartConversionButton)
		self.panel.add(ConvertButton)
		#self.panel.add(Zslider)

       	#other stuff to improve the look
		self.pack() # packs the frame
		self.setVisible(True) # shows the JFrame
		self.setLocation(0,self.coordy+200)


		




	#define functions for the buttons:
       
	def quit(self, event): #quit the gui
		if self.imLeft is not None:
			self.imLeft.close()
			self.imRight.close()
		self.dispose()
       

	def load(self, event): #choose a folder to load images
		self.imdir = DirectoryChooser("Select a dir, dude").getDirectory()

		self.pictureList = [path.join(self.imdir, f) for f in listdir(self.imdir) if path.splitext(f)[1]==".tiff" and 'AVG' not in f and 'Avg' not in f]  #list of pictures (not averages) with .tiff extension
		print self.pictureList #list of pictures
		self.imLeft = ImagePlus(self.pictureList[self.imageCount]) #read the image
		self.imageCount =self.imageCount+1 #increase counter
		self.imRight = ImagePlus(self.pictureList[self.imageCount]) #read the image
		self.imageCount =self.imageCount+1
		
		self.imLeft.show() #show image on the left
		self.imLeft.getWindow().setLocation(self.coordx,self.coordy) #reposition image
		
       
		self.imRight.show() #show image on the right
		self.rightImLocx = self.coordx+self.imLeft.getWindow().getWidth() #set a variable with the x position for right image
		self.imRight.getWindow().setLocation(self.rightImLocx,self.coordy) #reposition image

		#WindowOrganizer("Tile")
		
		#SyncWindows(self.imLeft.getTitle() + " " + self.imRight.getTitle())
		#IJ.run("Sync Windows")

		print len(self.pictureList)

		

	def ChooseLeft(self, event): #remove right image and load another
		if self.listendFlag==0: #if is not the end of the list
			print "You chose left, which is of course right"
			self.imRight.close()
		if self.imageCount>=len(self.pictureList): #if is the end of the list
			print "YOU HAVE A WINNER!!!"
			self.listendFlag = 1	#flag
			if self.imageCount==len(self.pictureList):
				self.chosenOne = 'L'	#a variable to know the position of the chosen one
			self.imageCount = self.imageCount+1	#this is to avoid changing the chosen one
		else:
			self.imRight = ImagePlus(self.pictureList[self.imageCount]) #read next image
			self.imageCount =self.imageCount+1	#increase counter
			self.imRight.show() #show image on the right
			self.imRight.getWindow().setLocation(self.rightImLocx,self.coordy) #reposition image

	
	def ChooseRight(self, event): #same as above but for the right image
		if self.listendFlag==0:
			print "You chose right, :)"
			self.imLeft.close()
		if self.imageCount>=len(self.pictureList):
			print "YOU HAVE A WINNER!!!"
			self.listendFlag = 1
			if self.imageCount==len(self.pictureList):
				self.chosenOne = 'R'
			self.imageCount = self.imageCount+1
		else:
			self.imLeft = ImagePlus(self.pictureList[self.imageCount])
			self.imageCount =self.imageCount+1
			self.imLeft.show() #show image on the left
			self.imLeft.getWindow().setLocation(self.coordx,self.coordy) #reposition image


	def ImThresh(self, event): #play wiht the threshold for every image
		IJ.setThreshold(float(self.ThreshField.getText()), 255)
		IJ.setOption("BlackBackground", false)



	def StartConv(self,event):
		print 'hola ', self.chosenOne
		os.path.makedirs('/Users/vergara/Desktop/EMBL/Images/PrImR6/4registered/AcTub/Average/test/')
		print 'adios'
		#print exists('/Users/vergara/Desktop/EMBL/Images/PrImR6/4registered/AcTub/Average/')
		#allow to use only if there is a chosen one
		
		#create a folder to store the binarized images
		if self.chosenOne == None:
			print 'Please choose one reference image first'
		elif self.chosenOne == 'L':
			#print 'You chose the left'
			self.chosenIm = self.imLeft
		elif self.chosenOne == 'R':
			#print 'You chose the right'
			self.chosenIm = self.imRight

		if self.chosenIm is not None:
			self.chosenIm.getWindow().setLocation(self.coordx,self.coordy) #reposition image
			
			#create directory
			self.bindir = path.join(self.imdir, 'CuratedBinarization/')
			print self.bindir
			makedirs(self.bindir)
			#IJ.File.makeDirectory(self.bindir)
			
			
			
			#if path.exists(self.bindir):
				
				#shutil.rmtree(self.bindir) #remove previous version if it already existed
			#	print 'Please remove previous directory and try again'
			#else:
			#	print self.bindir
			#	makedirs(self.bindir)
				
			
			#get the information of the the chosen one, binarize it, save it, and avoid open it again


			
	
	def ImConvert(self,event): #apply the threshold that the image has
		#allow to use only if StartConv has been pressed
		IJ.run("Convert to Mask", "method=Default background=Dark")