Example #1
0
			fileout = 	os.path.join(analyzeDir, os.path.basename(filepath))	
			IJ.saveAs(impOut, "Jpeg", fileout)

def createOutputImg(image, roim, centPart, metaphase):
	#maximal projection
	imp = image
	if image.getNSlices() > 1:
		zp = ZProjector()
		zp.setMethod(zp.MAX_METHOD)
		zp.setImage(image)
		zp.doProjection()
		imp = zp.getProjection()
	else:
		imp = image
	IJ.run(imp,"Enhance Contrast", "saturated=0.35")
	IJ.setForegroundColor(255,0,0)
	#need to show the image to draw overlay
	imp.show()
	IJ.run(imp,"RGB Color", "");
	for i in range(roim.getCount()):
		roim.select(imp, i)
		roim.runCommand("Draw")
	if metaphase:
		IJ.setForegroundColor(0,255,255)
	else:
		IJ.setForegroundColor(0,255,0)	
	roim.select(imp, centPart)
Example #2
0
def getMIP(stackImp):
    """
    Create a maximum intensity projection (MIP) from an ImagePlus stack

    @return ImagePlus maximum projection
    """
    zp = ZProjector(stackImp)
    zp.setMethod(ZProjector.MAX_METHOD)
    zp.setStopSlice(stackImp.getNSlices())
    zp.doHyperStackProjection(False)
    return zp.getProjection()
Example #3
0
def projectionImage(imp):
    """Returns the MIP of the specified ImagePlus (a composite stack)"""
    from ij.plugin import ZProjector
    roi_exists = imp.getRoi() is not None
    imp.deleteRoi()
    zp = ZProjector(imp)
    zp.setMethod(ZProjector.MAX_METHOD)
    zp.setStartSlice(1)
    zp.setStopSlice(imp.getNSlices())
    zp.doHyperStackProjection(True)
    mip_imp = zp.getProjection()
    mip_imp.setCalibration(imp.getCalibration())
    if roi_exists:
        mip_imp.restoreRoi()
    return mip_imp
Example #4
0
def project_z(imp, method):
  zp = ZProjector(imp)
  if method=="max":
    zp.setMethod(ZProjector.MAX_METHOD)
  if method=="sum":
    zp.setMethod(ZProjector.SUM_METHOD)
    
  zp.setStopSlice(imp.getNSlices())
  zp.doHyperStackProjection(True)
  zpimp = zp.getProjection()
  
  #IJ.run(imp, "Z Project...", "projection=[Max Intensity] all");
  #impout = IJ.getImage()
  
  return zpimp
Example #5
0
def main():

    #opens the image and gets its name
    # imp = open_test_img()
    # imp.show()
    imp = IJ.getImage()
    title = imp.getTitle()
    basename, extension = splitext(title)

    # does a minimum projection and makes a mask
    imp_min = ZProjector.run(imp, 'min')
    ip = imp_min.getProcessor()
    ip.setThreshold(1, 9999999999, 1)
    mask = ip.createMask()
    mask = ImagePlus("mask", mask)

    # fills in the holes in the mask
    IJ.run(mask, "Invert", "")
    IJ.run(mask, "Fill Holes", "")
    IJ.run(mask, "Invert", "")

    # converts to list and then finds the crop coordinates
    px = mask.getProcessor().getPixels()
    px = [-int(_) for _ in px]  #for some reason the 1s are -1 here
    px = reshape(px, (imp.height, imp.width))
    crop_top_left, crop_width, crop_height = find_largest_rectangle_2D(px)

    # crops the original image
    imp.setRoi(crop_top_left[0], crop_top_left[1], crop_width, crop_height)
    imp_cropped = imp.resize(crop_width, crop_height, "bilinear")
    imp_cropped.setTitle(basename + "_autocrop" + extension)
    imp_cropped.show()
def perform_cropping(imp, info, output_folder, default_path):
    imp.show()
    imp.setC(info.get_mosaic_labeled_ch())
    IJ.run("Enhance Contrast", "saturated=0.35")
    zcrop_imp, z_lims = z_crop(imp)
    info.set_z_crop_frames(z_lims)
    info.set_mosaic_labeled_ch(imp.getC())
    IJ.setTool("rect")
    zcrop_imp.hide()
    imp2 = ZProjector.run(zcrop_imp, "max")
    imp2.show()
    imp2.setC(info.get_mosaic_labeled_ch())
    crop_roi = None
    while crop_roi is None:
        WaitForUserDialog("Select XY region to crop...").show()
        crop_roi = imp2.getRoi()
    if crop_roi.getType():
        info.set_xy_crop_rect(
            str([(x, y) for x, y in zip(crop_roi.getPolygon().xpoints,
                                        crop_roi.getPolygon().ypoints)]))
    else:
        info.set_xy_crop_rect(crop_roi.getBounds().toString())
    imp2.close()
    zcrop_imp.show()
    zcrop_imp.setRoi(crop_roi)
    IJ.run("Crop", "")
    if crop_roi.getType():
        IJ.run(zcrop_imp, "Make Inverse", "")
        inv_roi = zcrop_imp.getRoi()
        IJ.run(zcrop_imp, "Set...", "value=0 stack")
        IJ.run(zcrop_imp, "Make Inverse", "")


#	zcrop_imp = z_crop_finetune(zcrop_imp, info);
    return imp, zcrop_imp, info, info.get_input_file_path()
def images_to_frames_stack(imgdir, savestack=False):
	'''
	Method for preparing a stack of frames using images inside the input folder.
	When savestack is true it saves the resulting stack to the images folder while opening the stack.
	'''
	title = "tracing_stack.tiff" # Title of the final image stack.
	imgdir = imgdir.getPath()
	imglist = buildList(imgdir, ext)
	if not imglist:
		raise IOError("No {0} were found in {0}.".format(ext, imgdir))
	method = "max"
	implist = []
	for img in imglist:
		imp = ImagePlus(img)
		if imp.isStack():
			imp = ZProjector.run(imp, method)
		implist.append(imp)
	stack = ImageStack(
		implist[0].getWidth(),
		implist[0].getHeight())
	[stack.addSlice(img.getProcessor()) for img in implist]
	stackimp = ImagePlus(title, stack)
	IJ.run(stackimp, "Properties...", "slices=1 frames={0}".format(stackimp.getStackSize()))
	if savestack:
		IJ.log("# Saving tracing stack...")
		save_string = os.path.join(imgdir, title)
		fs = ThreadedFileSaver.ThreadedFileSaver(stackimp, save_string, "saveAsTiff")
		fs.start()
	stackimp.show()
def stackprocessor(path, nChannels=4, nSlices=1, nFrames=1):
    imp = ImagePlus(path)
    imp = HyperStackConverter().toHyperStack(imp,
                                               nChannels,  # channels
                                               nSlices,  # slices
                                               nFrames)  # frames
    imp = ZProjector.run(imp, "max")
    return imp
Example #9
0
def maxZprojection(stackimp):
    '''copied from EMBL CMCI python-ImageJ cookbook.'''
    zp = ZProjector(stackimp)
    zp.setMethod(ZProjector.MAX_METHOD)
    zp.doProjection()
    zpimp = zp.getProjection()
    return zpimp
Example #10
0
	def __favg(self) :
		zp = ZProjector(self.__impRes) 
		zp.setMethod(ZProjector.AVG_METHOD)
		zp.doProjection() 
		imp = zp.getProjection()
		imp.show()
		if self.__fire : IJ.run(imp, "Fire", "")
Example #11
0
def main():
	root = myDir.getPath() # get the root out the java file object
	print(root)
	
	import os, glob

	# set up bioformats
	from loci.plugins import BF
	from loci.plugins.in import ImporterOptions
	options = ImporterOptions()
	options.setColorMode(ImporterOptions.COLOR_MODE_COMPOSITE)
	options.setGroupFiles(True)  # if the files are named logically if will group them into a stack
  	
	# this will do the maximum intensity projection
	from ij.plugin import ZProjector
	Zproj = ZProjector()

	for path, subdirs, files in os.walk(root):
		print(path)
		# just get the one of the files that matches your image pattern
		flist = glob.glob(os.path.join(path,"*.tif"))
		print(len(flist))
		if( flist ):
			file = flist[0]
			print("Processing {}".format(file))
			options.setId(file)
			imp = BF.openImagePlus(options)[0]

			# show the image if you want to see it
			IJ.run(imp, "Grays", "")
			imp.show()

			imp_max = Zproj.run(imp,'max')
			IJ.run(imp_max, "Grays", "")
			imp_max.show()

			# save the Z projection
			IJ.save(imp_max,file.rsplit('_',1)[0]+'_processed.tif')
Example #12
0
def create_and_save(imp, projections, path, filename, export_format):
    """Wrapper to create one or more projections and export the results.

    Parameters
    ----------
    imp : ij.ImagePlus
        The image stack to create the projections from.
    projections : list(str)
        A list of projection types to be done, valid options are 'Average',
        'Maximum' and 'Sum'.
    path : str
        The path to store the results in. Existing files will be overwritten.
    filename : str
        The original file name to derive the results name from.
    export_format : str
        The suffix to be given to Bio-Formats, determining the storage format.

    Returns
    -------
    bool
        True in case projections were created, False otherwise (e.g. if the
        given ImagePlus is not a Z-stack).
    """
    if not projections:
        log.debug("No projection type requested, skipping...")
        return False

    if imp.getDimensions()[3] < 2:
        log.error("ImagePlus is not a z-stack, not creating any projections!")
        return False

    command = {
        "Average": "avg",
        "Maximum": "max",
        "Sum": "sum",
    }
    for projection in projections:
        log.debug("Creating '%s' projection...", projection)
        proj = ZProjector.run(imp, command[projection])
        export_using_orig_name(
            proj,
            path,
            filename,
            "-%s" % command[projection],
            export_format,
            overwrite=True,
        )
        proj.close()

    return True
Example #13
0
def getPreview(image):
	enhancer = ContrastEnhancer()
	projector = ZProjector()
	splitter = ChannelSplitter()
	imp1 = ImagePlus("CH1", )
	width, height, channels, slices, frames = image.getDimensions()
	chimps = []
	for ch in range(1, channels + 1):
		projector = ZProjector(ImagePlus("C%i" % ch, splitter.getChannel(image, ch)))
		projector.setMethod(ZProjector.MAX_METHOD)
		projector.doProjection()
		proj = projector.getProjection()
		enhancer.equalize(proj)
		chimps.append(proj)
		
	return RGBStackMerge.mergeChannels(chimps, False)
def BackgroundFilter(imp, projection_method = "Median"):

    title = imp.getTitle()

    #Make a dict containg method_name:const_fieled_value pairs for the projection methods
    methods_as_strings=['Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median']
    methods_as_const=[ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD, ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD]
    method_dict=dict(zip(methods_as_strings, methods_as_const))

    #The Z-Projection magic happens here through a ZProjector object
    zp = ZProjector(imp)
    zp.setMethod(method_dict[projection_method])
    zp.doProjection()
    outstack = imp.createEmptyStack()
    outstack.addSlice(zp.getProjection().getProcessor())
    imp2 = ImagePlus(title+'_'+projection_method, outstack)
    out = ImageCalculator().run("Subtract create 32-bit stack", imp, imp2)
    return out
Example #15
0
def average(imp):
    """Create an average intensity projection.

    Parameters
    ----------
    imp : ij.ImagePlus
        The input stack to be projected.

    Returns
    -------
    ij.ImagePlus
        The result of the projection.
    """
    if imp.getDimensions()[3] < 2:
        log.warn("ImagePlus is not a z-stack, not creating a projection!")
        return imp

    log.debug("Creating average projection...")
    proj = ZProjector.run(imp, "avg")
    return proj
Example #16
0
	def previewImage(self, imp):
		roi = imp.getRoi()
		splitter = ChannelSplitter()
		channels = []
		for c in range(1, imp.getNChannels() + 1):
			channel = ImagePlus("Channel %i" % c, splitter.getChannel(imp, c))
			projector = ZProjector(channel)
			projector.setMethod(ZProjector.MAX_METHOD)
			projector.doProjection()
			channels.append(projector.getProjection())
		image = RGBStackMerge.mergeChannels(channels, False)
		image.title = imp.title + " MAX Intensity"
		image.luts = imp.luts
		imp.setRoi(roi)
		return image
Example #17
0
def process_caspase_signal(path_signal, path_imp, path_imp_out):

    path_imp = path_signal + path_imp
    imp = IJ.openImage(path_imp)
    imp.show()

    zp = ZProjector(imp)
    zp.setMethod(ZProjector.AVG_METHOD)
    zp.doProjection()
    zpimp = zp.getProjection()

    imp_sub = ImageCalculator().run("Subtract create stack", imp, zpimp)
    imp_sub.show()
    IJ.saveAs(imp_sub, "Tiff", path_signal + path_imp_out)

    imp.changes = False
    imp.close()
    imp_sub.changes = False
    imp_sub.close()
def extract_frame_process_roi(imp, frame, channel, process, background, roi, z_min, z_max, correct_only_xy):
  # extract frame and channel 
  imp_frame = ImagePlus("", extract_frame(imp, frame, channel, z_min, z_max)).duplicate()
  # check for roi and crop
  if roi != None:
    #print roi.getBounds()
    imp_frame.setRoi(roi)
    IJ.run(imp_frame, "Crop", "")
  # subtract background  
  if background > 0:
    #IJ.log("Subtracting "+str(background));
    IJ.run(imp_frame, "Subtract...", "value="+str(background)+" stack");
  # enhance edges  
  if process:
    IJ.run(imp_frame, "Mean 3D...", "x=1 y=1 z=0");
    IJ.run(imp_frame, "Find Edges", "stack");
  # project into 2D
  if imp_frame.getNSlices() > 1:
    if correct_only_xy:
      imp_frame = ZProjector.run( imp_frame, "avg");
  # return
  return imp_frame
Example #19
0
def extract_frame_process_roi(imp, frame, roi, options):
  # extract frame and channel 
  imp_frame = ImagePlus("", extract_frame(imp, frame, options['channel'], options['z_min'], options['z_max'])).duplicate()
  # check for roi and crop
  if roi != None:
    #print roi.getBounds()
    imp_frame.setRoi(roi)
    IJ.run(imp_frame, "Crop", "")
  # subtract background  
  if options['background'] > 0:
    #IJ.log("Subtracting "+str(background));
    IJ.run(imp_frame, "Subtract...", "value="+str(options['background'])+" stack");
  # enhance edges  
  if options['process']:
    IJ.run(imp_frame, "Mean 3D...", "x=1 y=1 z=0");
    IJ.run(imp_frame, "Find Edges", "stack");
  # project into 2D if we only want to correct the drift in x and y
  if imp_frame.getNSlices() > 1:
    if options['correct_only_xy']:
      imp_frame = ZProjector.run(imp_frame, "avg");
  # return
  return imp_frame
Example #20
0
def subtractzproject(imp, projectionMethod="Median"):
    """This function takes an input stack, and subtracts a projection from the 
    whole stack from each individual frame. Thereby, everything that is not moving 
    in a timeseries is filtered away.

    Args:
        imp (ImagePlus): An input stack as ImagePlus object.
        projectionMethod (str, optional): Choose the projection method. Options are 
            'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median'. 
            Defaults to "Median".

    Returns:
        ImagePlus: The resulting stack.
    """
    #Start by getting the active image window and get the current active channel and other stats
    cal = imp.getCalibration()
    title = imp.getTitle()

    # Define a dictionary containg method_name:const_fieled_value pairs for the projection methods.
    methods_as_strings = [
        'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices',
        'Standard Deviation', 'Median'
    ]
    methods_as_const = [
        ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD,
        ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD
    ]
    method_dict = dict(zip(methods_as_strings, methods_as_const))

    # Run Z-Projection.
    zp = ZProjector(imp)
    zp.setMethod(method_dict[projectionMethod])
    zp.doProjection()
    impMedian = zp.getProjection()

    # Subtract Z-Projection and return output ImagePlus.
    impout = ImageCalculator().run("Subtract create 32-bit stack", imp,
                                   impMedian)
    impout.setCalibration(cal)
    return impout
Example #21
0
    def doprojection(self, title, onGPU=False):
        '''
		Run ij.plugin.Zprojector on image referenced by title using self.method as
		projection method and saves the projection on self.savefolder.
		'''
        IJ.log("# Processing {0}...".format(title))
        imp = self.load_image(title)
        if onGPU:
            projection = self.CLIJ2_max_projection(imp)
        else:
            projection = ZProjector.run(imp, self.method)
        if self.savefolder:
            save_string = os.path.join(self.savefolder, title)
            try:
                ij.io.FileSaver(projection).saveAsTiff(save_string)
                IJ.log("{0}".format(save_string))
            except:
                IJ.log(
                    "ij.io.FileSaver raised an exception while trying to save img '{0}' as '{1}'.Skipping image."
                    .format(title, save_string))
        else:
            imp.close()
            projection.show()
	def saveMaxProject(self, destFolder=''):
		channelNumber = 1
		for imp in self.channelImp:
			if not destFolder:
				destFolder = os.path.join(self.enclosingPath, self.enclosingfolder + '_tif', 'max')
			if not os.path.isdir(destFolder):
				os.makedirs(destFolder)

			# make max project
			zp = ZProjector(imp)
			zp.setMethod(ZProjector.MAX_METHOD)
			zp.doProjection()
			zimp = zp.getProjection()

			# save
			saveFile = 'max_' + os.path.splitext(self.filename)[0] + '_ch' + str(channelNumber) + '.tif'
			savePath = os.path.join(destFolder, saveFile)
			fs = FileSaver(zimp)
			bPrintLog('saveMaxProject():' + savePath, 3)
			fs.saveAsTiff(savePath)

			channelNumber += 1
def processFile(filename, inDir, outDir, dichroics, mergeList):

	if mergeList is None:
		merge = False
	else:
		merge = True
	
	filenameExExt = os.path.splitext(filename)[0]
	filepath = inDir + filename
      
	# parse metadata
	reader = ImageReader()
	omeMeta = MetadataTools.createOMEXMLMetadata()
	reader.setMetadataStore(omeMeta)
	reader.setId(filepath)
	numChannels = reader.getSizeC()
	numSlices = reader.getSizeZ()
	numFrames = reader.getSizeT()
	seriesCount = reader.getSeriesCount()

	globalMetadata = reader.getGlobalMetadata()
	seriesMetadata = reader.getSeriesMetadata()

	objLensName = globalMetadata['- Objective Lens name #1']

	areaRotation = float(seriesMetadata['area rotation #1'])
	acquisitionValueRotation = float(seriesMetadata['acquisitionValue rotation #1'])
	if 'regionInfo rotation #1' in seriesMetadata:
		regionInfoRotation = float(seriesMetadata['regionInfo rotation #1'])
	else:
		regionInfoRotation = float(0)

	totalRotation = areaRotation + regionInfoRotation
	physSizeX = omeMeta.getPixelsPhysicalSizeX(0)
	physSizeY = omeMeta.getPixelsPhysicalSizeY(0)
	pxSizeX = physSizeX.value(UNITS.MICROM)
	pxSizeY = physSizeY.value(UNITS.MICROM)

	# log metadata
	IJ.log("\nMETADATA")
	#IJ.log("Filename: " + filepath)
	IJ.log("Number of series: " + str(seriesCount))
	IJ.log("Number of channels: " + str(numChannels))
	IJ.log("Number of frames: " + str(numFrames))
	IJ.log("Number of slices: " + str(numSlices))
	IJ.log("Objective lens: " + objLensName)
	IJ.log("FOV rotation: " + str(areaRotation))
	IJ.log("ROI rotation: " + str(regionInfoRotation))
	IJ.log("Total rotation: " + str(totalRotation))
	IJ.log("Pixel size:")
	IJ.log("\t\tX = " + str(physSizeX.value()) + " " + physSizeX.unit().getSymbol())
	IJ.log("\t\tY = " + str(physSizeY.value()) + " " + physSizeY.unit().getSymbol())
  
	if merge:
		tifDir = outDir + "." + str(datetime.now()).replace(" ", "").replace(":", "") + "/"
		if not os.path.exists(tifDir):
			os.makedirs(tifDir)
			IJ.log("\nCreated temporary folder: " + tifDir + "\n")
		else:
			IJ.log("Unable to create temporary folder!\n")
	else:
		tifDir = outDir + filenameExExt + "/"
		if not os.path.exists(tifDir):
			os.makedirs(tifDir)
			IJ.log("\nCreated subfolder: " + tifDir + "\n")
		else:
			IJ.log("\nSubfolder " + tifDir +  " already exists.\n")

	# correct images
	tifFilePaths = []
	for i in range(numChannels):
		ip = extractChannel(oirFile=filepath, ch=i)
		if dichroics[i] == "DM1":
			IJ.log("Channel " + str(i+1) + " was imaged using DM1, so no correction required.")
		else:
			offsets = getOffset(obj=objLensName,dm=dichroicDict[dichroics[i]])
			xom = offsets['x']
			yom = offsets['y']
			if abs(totalRotation) > 0.1:
				rotOff = rotateOffset(x=xom, y=yom, angle=-totalRotation)
				xom = rotOff['x']
				yom = rotOff['y']
			xop = int(round(xom/pxSizeX))
			yop = int(round(yom/pxSizeY))
			IJ.log("Channel " + str(i+1) + " offsets")
			IJ.log("\t\tMicrometres")
			IJ.log("\t\t\t\tx = " + str(xom))
			IJ.log("\t\t\t\ty = " + str(yom))
			IJ.log("\t\tPixels")
			IJ.log("\t\t\t\tx = " + str(xop))
			IJ.log("\t\t\t\ty = " + str(yop))
			IJ.run(ip, "Translate...", "x=" + str(-xop) + " y=" + str(-yop) + " interpolation=None stack")

		tifFilePath = tifDir + filenameExExt + "_ch_"+str(i+1)+".tif"
		tifFilePaths.append(tifFilePath)
		if os.path.exists(tifFilePath):
			IJ.log("\nOutput file exists: " + tifFilePath)
			IJ.log("Rerun plugin choosing a different output folder")
			IJ.log("or delete file and then rerun plugin.")
			IJ.log("Image processing terminated!\n")
			return
		FileSaver(ip).saveAsTiff(tifFilePath)

	if merge:
		max_list = []
		for i in range(len(mergeList)):
			if mergeList[i] != None:
				mergeList[i] = readSingleChannelImg(tifFilePaths[mergeList[i]])
				channel = mergeList[i]#https://python.hotexamples.com/examples/ij.plugin/RGBStackMerge/mergeChannels/python-rgbstackmerge-mergechannels-method-examples.html
				projector = ZProjector(channel)
				projector.setMethod(ZProjector.MAX_METHOD)
				projector.doProjection()
				max_list.append(projector.getProjection())
		merged = RGBStackMerge.mergeChannels(mergeList, False)
		merged_max = RGBStackMerge.mergeChannels(max_list, False)
		mergedChannelFilepath = outDir + filenameExExt + ".tif"
		maxMergedChannelFilepath = outDir + filenameExExt + "_max.tif"
		if os.path.exists(mergedChannelFilepath):
			IJ.log("\nOutput file exists: " + mergedChannelFilepath)
			IJ.log("Rerun plugin choosing a different output folder")
			IJ.log("or delete file and then rerun plugin.")
			IJ.log("Image processing terminated!\n")
		FileSaver(merged).saveAsTiff(mergedChannelFilepath)
		FileSaver(merged_max).saveAsTiff(maxMergedChannelFilepath)
		for tf in tifFilePaths:
			os.remove(tf)
		os.rmdir(tifDir)	

	IJ.log("\nFinished processing file:\n" + filepath + "\n")
	if merge:
		IJ.log("Image file with channels aligned:\n" + outDir + filenameExExt + ".tif\n")
	else:
		IJ.log("Aligned images (one tiff file for each channel) can be found in:\n" + tifDir + "\n")
def maxZprojection(stackimp):
	zp = ZProjector(stackimp)
	zp.setMethod(ZProjector.MAX_METHOD)
	zp.doProjection()
	zpimp = zp.getProjection()
	return (zpimp)
def Zproj(stackimp,method,z_ind,z_range):
	"""
	Gets a single channel z-stack as imp and max project it using the provided method.
	stackimp(ImagePlus): a single channel z-stack as ImagePlus object
	z_index(int): The central stack number
	z_range(int): The total number of stacks surrounding the z_index to indclude
	"""
	from ij.plugin import ZProjector
#	imp= stackimp.duplicate()
	zp = ZProjector(stackimp)
	if method=="MAX":
		print "MAX"
		zp.setMethod(ZProjector.MAX_METHOD)
	elif method=="SUM":
		zp.setMethod(ZProjector.MAX_METHOD)
	zp.setStartSlice(z_ind-int(z_range/2))
	zp.setStopSlice(z_ind+int(z_range/2))
	zp.doProjection()
	zpimp = zp.getProjection()
	return zpimp
Example #26
0
def make_projection(imp, method, slices):
    z_prjor = ZProjector(imp)
    prj_imp = z_prjor.run(imp, method, slices[0], slices[1])
    return prj_imp
Example #27
0
def process_pi_signal(path, position, unsynchronized=True):

    if unsynchronized:
        path_signal = path + "\\pi"
        path_signal_before = path_signal + "\\before"
        path_signal_after = path_signal + "\\after"
        path_signal_merged = path_signal + "\\merged"
        path_imp_before = path_signal_before + "\\pi_in-focusxy%sc1.tif" % position
        path_imp_after = path_signal_after + "\\pixy%sc1.tif" % position
        path_imp_merged = path_signal_merged + "\\merged.tif"
        path_imp_merged_sub = path_signal_merged + "\\merged_sub.tif"

        imp1 = IJ.openImage(path_imp_before)
        imp1.show()
        imp2 = IJ.openImage(path_imp_after)
        imp2.show()

        zp1 = ZProjector(imp1)
        zp1.setMethod(ZProjector.AVG_METHOD)
        zp1.doProjection()
        zpimp1 = zp1.getProjection()

        zp2 = ZProjector(imp2)
        zp2.setMethod(ZProjector.AVG_METHOD)
        zp2.doProjection()
        zpimp2 = zp2.getProjection()

        imp_sub1 = ImageCalculator().run("Subtract create stack", imp1, zpimp1)
        imp_sub1.show()

        imp_sub2 = ImageCalculator().run("Subtract create stack", imp2, zpimp2)
        imp_sub2.show()

        concatenate_files(imp1, imp2, path_imp_merged)
        concatenate_files(imp_sub1, imp_sub2, path_imp_merged_sub)

    else:
        path_signal = path + "\\pi\\seq0002xy%sc1.tif" % position
        path_sub = path + "\\pi\\sub.tif"

        imp = IJ.openImage(path_signal)
        imp.show()

        zp = ZProjector(imp)
        zp.setMethod(ZProjector.AVG_METHOD)
        zp.doProjection()
        zpimp = zp.getProjection()

        imp_sub = ImageCalculator().run("Subtract create stack", imp, zpimp)
        imp_sub.show()

        IJ.saveAs(imp_sub, "Tiff", path_sub)

        imp.changes = False
        imp.close()
        zpimp.changes = False
        zpimp.close()
        imp_sub.changes = False
        imp_sub.close()
Example #28
0
def project(img, method):
    zp = ZProjector.run(img, method)
    return zp
Example #29
0
def Zproj(stackimp, method, z_ind, z_range):
    # Gets a stack and max project it.
    from ij.plugin import ZProjector
    #	imp= stackimp.duplicate()
    zp = ZProjector(stackimp)
    if method == "MAX":
        print "MAX"
        zp.setMethod(ZProjector.MAX_METHOD)
    elif method == "SUM":
        print "SUM"
        zp.setMethod(ZProjector.MAX_METHOD)
    print "+/-", int(z_range / 2), "of z-index", z_ind
    zp.setStartSlice(z_ind - int(z_range / 2))
    zp.setStopSlice(z_ind + int(z_range / 2))
    zp.doProjection()
    zpimp = zp.getProjection()
    return zpimp
Example #30
0
import os, sys
from ij import IJ
from ij.io import FileSaver
from loci.plugins import BF
from subprocess import call
from ij.plugin import ZProjector 

try:
	filepath = getArgument()
except Exception, e:
	sys.exit(" no file " + e)
try:
	imp = BF.openImagePlus(filepath)
	image = imp[0]
	zProj = ZProjector(image)
	zProj.setMethod(zProj.MAX_METHOD)
	zProj.doProjection()
	imgMax = zProj.getProjection()
	#imgMax.show()
	FileSaver(imgMax).saveAsTiff(os.path.splitext(filepath)[0] + "_MAX.tif")
except Exception, e:
	sys.exit(e)
except Exception, e:
	sys.exit(e)
Example #31
0
def main():
    # setup
    Prefs.blackBackground = True
    params = Parameters()
    params.load_last_params()
    # select folders
    if params.last_input_path is not None:
        DirectoryChooser.setDefaultDirectory(params.last_input_path)
    dc = DirectoryChooser("Choose root folder containing data for analysis")
    input_folder = dc.getDirectory()
    params.last_input_path = input_folder
    if input_folder is None:
        raise KeyboardInterrupt("Run canceled")
    if params.last_output_path is not None:
        DirectoryChooser.setDefaultDirectory(
            os.path.dirname(params.last_output_path))
    dc = DirectoryChooser("choose location to save output")
    output_folder = dc.getDirectory()
    timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S')
    output_folder = os.path.join(output_folder, (timestamp + ' output'))
    params.last_output_path = output_folder
    os.mkdir(output_folder)
    analysis_mode = choose_analysis_mode(params)
    params.last_analysis_mode = analysis_mode
    params.persist_parameters()

    # load  image(s):
    files_lst = [
        f for f in os.listdir(input_folder) if os.path.splitext(f)[1] == '.tif'
    ]
    out_statses = []
    for f in files_lst:
        print("Working on image {}...".format(os.path.splitext(f)[0]))
        imp = IJ.openImage(os.path.join(input_folder, f))
        metadata = import_iq3_metadata(
            os.path.join(input_folder,
                         os.path.splitext(f)[0] + '.txt'))
        imp = HyperStackConverter.toHyperStack(imp, 3,
                                               imp.getNSlices() // 3, 1,
                                               "Color")
        imp = ZProjector.run(imp, "max")
        imp.setC(3)
        IJ.run(imp, "Blue", "")
        IJ.run(imp, "Enhance Contrast", "saturated=0.35")
        imp.setC(2)
        IJ.run(imp, "Red", "")
        IJ.run(imp, "Enhance Contrast", "saturated=0.35")
        imp.setC(1)
        IJ.run(imp, "Green", "")
        IJ.run(imp, "Enhance Contrast", "saturated=0.35")
        imp.show()
        imp.setDisplayMode(IJ.COMPOSITE)
        cal = imp.getCalibration()
        cal.setUnit(metadata["y_unit"])
        cal.pixelWidth = metadata["x_physical_size"]
        cal.pixelHeight = metadata["y_physical_size"]
        imp.setCalibration(cal)

        if analysis_mode == "GFP intensity":
            out_stats = gfp_analysis(imp, f, output_folder)
        elif analysis_mode == "Manual":
            out_stats = manual_analysis(imp, f, output_folder)
        out_statses.extend(out_stats)
        print("Current total number of cells identified: {}".format(
            len(out_statses)))
        # get # nuclei per "cell"
    params.save_parameters_to_json(
        os.path.join(output_folder, "parameters used.json"))
    WaitForUserDialog(
        "Done", "Done, having analysed {} cells in total!".format(
            len(out_statses))).show()
    return
Example #32
0
# manual roi copied from z-projected version of this resliced image (add roi from z-proj to ROI manager, then add 
# to resliced image)

imp.killRoi();
IJ.run(imp, "Reslice [/]...", "output=1.000 start=Top avoid");
rot_imp = IJ.getImage();
crop_roi = Roi(10, 0, rot_imp.getWidth()-20, rot_imp.getHeight());
rot_imp.setRoi(crop_roi);
rot_imp.crop();
rot_imp.show();
WaitForUserDialog("pause").show();
split_ch = ChannelSplitter().split(rot_imp);
mch_imp = split_ch[0];
egfp_imp = split_ch[1];
roi_imp = split_ch[2];
zproj_imp = ZProjector.run(roi_imp, "max");
IJ.setRawThreshold(zproj_imp, 33153, 65535, None);
IJ.run(zproj_imp, "Make Binary", "")
zproj_imp.show();
raise error;
IJ.run(zproj_imp, "Skeletonize", "");
IJ.run(zproj_imp, "Create Selection", "");
roi = zproj_imp.getRoi();
floatpoly = roi.getContainedFloatPoints();
roi = PolygonRoi(floatpoly, Roi.FREELINE);
zproj_imp.setRoi(roi);
WaitForUserDialog("pause").show();

#IJ.setTool("freeline");
#WaitForUserDialog("Draw a line").show();
#IJ.run(zproj_imp, "Fit Spline", "");
def zproj(imp):
	zpimp = ZP()
	zpimp.setImage(imp)
	zpimp.setMethod(zpimp.MAX_METHOD)
	zpimp.setStartSlice(1)
	zpimp.setStopSlice(imp.getNSlices())
	zpimp.doHyperStackProjection(True)
	zpedimp = zpimp.getProjection()
	return zpedimp
	def saveMaxProject(self, destFolder=''):
		# ch1
		if self.imp_ch1:
			# make max project
			zp = ZProjector(self.imp_ch1)
			zp.setMethod(ZProjector.MAX_METHOD)
			zp.doProjection()
			zimp = zp.getProjection()

			# save
			fs = FileSaver(zimp)
			bPrintLog('saveMaxProject():' + self.savePathMax_ch1, 3)
			fs.saveAsTiff(self.savePathMax_ch1)
		# ch2
		if self.imp_ch2:
			# make max project
			zp = ZProjector(self.imp_ch2)
			zp.setMethod(ZProjector.MAX_METHOD)
			zp.doProjection()
			zimp = zp.getProjection()

			# save
			fs = FileSaver(zimp)
			bPrintLog('saveMaxProject():' + self.savePathMax_ch2, 3)
			fs.saveAsTiff(self.savePathMax_ch2)
		# ch1
		if self.imp_ch3:
			# make max project
			zp = ZProjector(self.imp_ch3)
			zp.setMethod(ZProjector.MAX_METHOD)
			zp.doProjection()
			zimp = zp.getProjection()

			# save
			fs = FileSaver(zimp)
			bPrintLog('saveMaxProject():' + self.savePathMax_ch3, 3)
			fs.saveAsTiff(self.savePathMax_ch3)
def main():
	### debug ###############################################################
	#print (sys.version_info);
	#print(sys.path);
	#file_path = "D:\\data\\Inverse blebbing\\MAX_2dpf marcksl1b-EGFP inj_TgLifeact-mCh_movie e4_split-bleb1.tif";
	#output_root = "D:\\data\\Inverse blebbing\\output";
	#from datetime import datetime
	#timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S');
	#output_folder = os.path.join(output_root, (timestamp + ' output')); 
	#os.mkdir(output_folder); 
	########################################################################
	
	# ensure consistent preference settings
	Prefs.blackBackground = False;

	# prompt user for input parameters
	params = mbui.analysis_parameters_gui();

	# prompt user for file locations
	file_path, output_folder = mbio.file_location_chooser(params.input_image_path);
	params.setInputImagePath(file_path);
	params.setOutputPath(output_folder);

	# get image file
	import_opts, params = mbui.choose_series(file_path, params);
	imps = bf.openImagePlus(import_opts);
	imp = imps[0];

	# catch unexpected image dimensions - for now, project in Z...:
	if  imp.getNSlices() > 1:
		mbui.warning_dialog(["More than one Z plane detected.", 
							"I will do a maximum projection before proceeding", 
							"Continue?"]);
		imp = ZProjector.run(imp,"max all");

	params = mbio.get_metadata(params);
	params.setCurvatureLengthUm(round(params.curvature_length_um / params.pixel_physical_size) * params.pixel_physical_size);
	params.persistParameters();
	IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel");
	imp.show();
	if imp.getNChannels() > 1:
		imp.setPosition(params.membrane_channel_number, 1, 1);
	mbui.autoset_zoom(imp);
	IJ.run("Enhance Contrast", "saturated=0.35");

	# prompt user to select ROI
	original_imp, crop_params = mbui.crop_to_ROI(imp, params);
	if crop_params is not None:
		params.perform_spatial_crop = True;
		mbui.autoset_zoom(imp);
	else:
		params.perform_spatial_crop = False;


	# prompt user to do time cropping
	imp, start_end_tuple = mbui.time_crop(imp, params);
	params.setTimeCropStartEnd(start_end_tuple);

	repeats = 1;
	inner_outer_comparisons = None;
	if params.inner_outer_comparison:
		inner_outer_comparisons = InnerOuterComparisonData();
		repeats = 2;

	IJ.selectWindow(imp.getTitle());
	IJ.run("Enhance Contrast", "saturated=0.35");
	for r in range(0, repeats):
		calculated_objects = CalculatedObjects();
		if params.time_crop_start_end[0] is not None:
			calculated_objects.timelist = [idx * params.frame_interval for idx in range(params.time_crop_start_end[0], params.time_crop_start_end[1]+1)]
		else:
			calculated_objects.timelist = [idx * params.frame_interval for idx in range(imp.getNFrames())];
		calculated_objects, params, split_channels = mbfs.generate_edges(imp, params, calculated_objects, (r+1)/repeats);
		membrane_channel_imp = split_channels[0];
		actin_channel_imp = split_channels[1];
		segmentation_channel_imp = split_channels[2];

		calculated_objects = mbfs.calculate_outputs(params,
													calculated_objects, 
													split_channels, 
													repeat_fraction=(r+1)/repeats);
						
		# output colormapped images and kymographs 
		fig_imp_list = mbfs.generate_and_save_figures(imp, calculated_objects, params, membrane_channel_imp, segmentation_channel_imp);
		mbfs.save_csvs(calculated_objects, params);
	
		params.saveParametersToJson(os.path.join(params.output_path, "parameters used.json"));
		imp.changes = False;
		IJ.setTool("zoom");
		if params.close_on_completion or (params.inner_outer_comparison and r!=(repeats-1)):
			for fig_imp in fig_imp_list:
				fig_imp.close();
		elif params.close_on_completion and (r==(repeats-1)):
			imp.close();
	
	if params.inner_outer_comparison:
		tname = "Time, " + params.interval_unit;
		output_folder = os.path.dirname(params.output_path);
		profile = [[((inner, outer), (float(outer)/inner)) for inner, outer in zip(calculated_objects.inner_outer_data.inner_means, calculated_objects.inner_outer_data.outer_means)]];
		mbio.save_profile_as_csv(profile, 
								os.path.join(output_folder, "Intensity ratios.csv"), 
								"outer/inner", 
								xname="inner", 
								yname="outer",
								tname=tname, 
								time_list=calculated_objects.timelist);
		sd_profile = [[((inner, outer), (float(outer)/inner)) for inner, outer in zip(calculated_objects.inner_outer_data.inner_sds, calculated_objects.inner_outer_data.outer_sds)]];
		mbio.save_profile_as_csv(profile, 
								os.path.join(output_folder, "Intensity standard deviation ratios.csv"), 
								"outer sd/inner sd", 
								xname="inner sd", 
								yname="outer sd",
								tname=tname, 
								time_list=calculated_objects.timelist);
	return;
	
		print 'Opening image', imageNPath
		impN = IJ.openImage( imageNPath )
		impN.setRoi( ROI_xStart, ROI_yStart, ROI_xSize, ROI_ySize )
		slices = impN.getNSlices()
		if ROI_zSize == 0:
			ROI_zSize = slices
		stack = impN.getStack()
		# crop(int x, int y, int z, int width, int height, int depth)
		impN.setStack( stack.crop( ROI_xStart, ROI_yStart, ROI_zStart, ROI_xSize, ROI_ySize, ROI_zSize ) )
		#impN.setStack( stack.crop( ROI_xStart, ROI_yStart, 130, ROI_xSize, ROI_ySize, 220 ) )
		#impN.setStack( stack.crop( ROI_xStart, ROI_yStart, 275, ROI_xSize, ROI_ySize, 1 ) )
		fs = FileSaver( impN )
		fs.saveAsTiff( imageNCroppedPath )
	
		zp = ZProjector(impN)
		zp.setMethod( ZProjector.MAX_METHOD )
		zp.doProjection()
		MIPimpN = zp.getProjection()
		#MIPimpN.show()

	if applyMembraneCropping == 1:
		imageMPath = membraneFolder + digit + appendix
		imageMCroppedPath = cropMembraneOutput + digit + appendix
	
		print 'Opening image', imageMPath
		impM = IJ.openImage( imageMPath )
		impM.setRoi( ROI_xStart, ROI_yStart, ROI_xSize, ROI_ySize )
		slices = impM.getNSlices()
		if ROI_zSize == 0:
			ROI_zSize = slices
Example #37
0
def startTracking(filepath, fdir, ffile, filename):
    outpath = fdir
    troutpath = fdir + separator + ffile + separator + "tracked" + separator
    stackoutpath = fdir + separator + ffile + separator + "stacks" + separator

    pixwidth = 0.647
    interval_sec = 600  #pr
    if "141006" in fdir:
        interval_sec = 600
    elif "141117" in fdir:
        interval_sec = 300
    elif "141215" in fdir:
        interval_sec = 300

    if not os.path.isdir(outpath):
        os.mkdir(outpath)
    if not os.path.isdir(troutpath):
        os.mkdir(troutpath)
    if not os.path.isdir(stackoutpath):
        os.mkdir(stackoutpath)

    print 'filepath: ', filepath  #pr
    print 'fdir: ', fdir  #pr
    print 'ffile: ', ffile  #pr
    IJ.run("Image Sequence...",
           "open=" + filepath + " file=" + filename + " sort")
    #pr
    #IJ.run("Image Sequence...", "open=" + filepath + " file=molm sort"); #pr
    imp = WindowManager.getCurrentImage()
    imptitle = imp.getTitle()
    nframes = imp.getNSlices()
    IJ.run(
        imp, "Properties...", "channels=1 slices=1 frames=" + str(nframes) +
        " unit=inch pixel_width=" + str(pixwidth) + " pixel_height=" +
        str(pixwidth) + " voxel_depth=1.0000 frame=[" + str(interval_sec) +
        " sec]")

    IJ.run(imp, "Duplicate...", "title=" + imptitle + "_dup duplicate")
    imp_dup = WindowManager.getImage(imptitle + "_dup")
    IJ.run(imp_dup, "Gaussian Blur...", "sigma=50 stack")

    ic = ImageCalculator()
    imp_corr = ic.run("Divide create 32-bit stack", imp, imp_dup)
    imp_corr.setTitle(imptitle + "_corrected")
    imp_corr.show()
    imp.changes = False
    imp.close()
    imp_dup.changes = False
    imp_dup.close()

    IJ.run(imp_corr, "8-bit", "")
    IJ.run(
        imp_corr, "Normalize Local Contrast",
        "block_radius_x=100 block_radius_y=100 standard_deviations=1 stretch stack"
    )
    IJ.saveAs(imp_corr, "Tiff",
              stackoutpath + separator + imptitle + "_corrected.tif")

    IJ.run(imp_corr, "Duplicate...", "title=" + imptitle + "_bg duplicate")
    imp_bg = WindowManager.getImage(imptitle + "_bg")

    #Prefs.blackBackground = True;
    IJ.setAutoThreshold(imp_bg, "MinError dark")
    IJ.run(imp_bg, "Convert to Mask", "stack")
    IJ.run(imp_bg, "Analyze Particles...",
           "size=10000-Infinity show=Masks stack")
    imp_bg.changes = False
    imp_bg.close()

    imp_bgmask = WindowManager.getImage("Mask of " + imptitle + "_bg")

    ic = ImageCalculator()
    imp_corr_wobg = ic.run("Subtract create stack", imp_corr, imp_bgmask)
    imp_corr_wobg.setTitle(imptitle + "_corrected_womask")
    imp_corr_wobg.show()

    IJ.saveAs(imp_corr_wobg, "Tiff",
              stackoutpath + separator + imptitle + "_corrected_womask.tif")
    #pr

    # pr: substract average frames
    zp = ZProjector(imp_corr_wobg)
    zp.setMethod(ZProjector.AVG_METHOD)
    zp.doProjection()
    zpimp = zp.getProjection()
    zpimp.show()
    imp_corr_wobg_sub = ImageCalculator().run("Subtract create stack",
                                              imp_corr_wobg, zpimp)
    imp_corr_wobg_sub.show()
    #imp_corr_wobg.changes = False
    #imp_corr_wobg.close()
    # pr: subtract average frames (END)

    IJ.saveAs(
        imp_corr_wobg_sub, "Tiff", stackoutpath + separator + imptitle +
        "_corrected_womask_substracted.tif")
    #pr
    IJ.saveAs(
        zpimp, "Tiff",
        stackoutpath + separator + imptitle + "_corrected_womask_avg.tif")
    #commented out: pr
    #IJ.saveAs(imp_corr_wobg, "Tiff", stackoutpath+separator+imptitle+"_corrected_womask.tif");
    IJ.saveAs(imp_bgmask, "Tiff",
              stackoutpath + separator + imptitle + "_bgmask.tif")

    print(stackoutpath + separator + imptitle +
          "_corrected_womask_substracted.tif")
    print(stackoutpath + separator + imptitle + "_corrected_womask_avg.tif")
    print(stackoutpath + separator + imptitle + "_bgmask.tif")

    imp_corr.changes = False
    imp_corr.close()
    imp_bgmask.changes = False
    imp_bgmask.close()

    imp_corr_wobg.changes = False
    imp_corr_wobg.close()
    #imp_corr_wobg_sub.changes = False
    #imp_corr_wobg_sub.close()
    zpimp.changes = False
    zpimp.close()

    #IJ.log(System.getProperty("os.name"))
    #IJ.log(fdir)

    return imp_corr_wobg_sub
Example #38
0
def main():
    # Prepare directory tree for output.
    indir = IJ.getDirectory("input directory")
    outdir = IJ.getDirectory(".csv output directory")
    c1dir = os.path.join(outdir, "Channel1")
    c2dir = os.path.join(outdir, "Channel2")
    c3dir = os.path.join(outdir, "Channel3")
    c4dir = os.path.join(outdir, "Channel4")
    channelsdir = os.path.join(outdir, "Channels")
    if not os.path.isdir(c1dir):
        os.mkdir(c1dir)
    if not os.path.isdir(c2dir):
        os.mkdir(c2dir)
    if not os.path.isdir(c3dir):
        os.mkdir(c3dir)
    if not os.path.isdir(c4dir):
        os.mkdir(c4dir)
    if not os.path.isdir(channelsdir):
        os.mkdir(channelsdir)

    # Collect all file paths in the input directory
    files = readdirfiles(indir)

    # Initialize the results tables.
    c1Results = ResultsTable()
    c2Results = ResultsTable()
    c3Results = ResultsTable()
    c4Results = ResultsTable()

    for file in files:

        IJ.log("File: {}/{}".format(files.index(file) + 1, len(files)))

        if file.endswith('.tif'):

            # Open .tiff file as ImagePlus.
            imp = Opener().openImage(file)
            imp = ZProjector.run(imp, "max")
            # imp = stackprocessor(file,
            #                        nChannels=4,
            #                        nSlices=7,
            #                        nFrames=1)
            channels = ChannelSplitter.split(imp)
            name = imp.getTitle()

            # For every channel, save the inverted channel in grayscale as .jpg.
            for channel in channels:
                IJ.run(channel, "Grays", "")
                IJ.run(channel, "Invert", "")
                jpgname = channel.getShortTitle()
                jpgoutfile = os.path.join(channelsdir,
                                          "{}.jpg".format(jpgname))
                IJ.saveAs(channel.flatten(), "Jpeg", jpgoutfile)
                IJ.run(channel, "Invert", "")

            # OPTIONAL - Perform any other operations (e.g. crossexcitation compensation tasks) before object count.
            c2name = channels[2].getTitle()
            cal = channels[2].getCalibration()
            channels[2] = ImagePlus(
                c2name,
                ImageCalculator().run("divide create 32-bit", channels[2],
                                      channels[3]).getProcessor(
                                      )  # This removes AF647 bleed-through
            )
            channels[2].setCalibration(cal)

            # Settings for channel1 threshold.
            c1 = countobjects(channels[0],
                              c1Results,
                              threshMethod="Triangle",
                              subtractBackground=True,
                              watershed=True,
                              minSize=0.00,
                              maxSize=100,
                              minCirc=0.00,
                              maxCirc=1.00)

            # Settings for channel2 threshold.
            c2 = countobjects(channels[1],
                              c2Results,
                              threshMethod="RenyiEntropy",
                              subtractBackground=True,
                              watershed=False,
                              minSize=0.00,
                              maxSize=30.00,
                              minCirc=0.00,
                              maxCirc=1.00)

            # Settings for channel3 threshold.
            c3 = countobjects(channels[2],
                              c3Results,
                              threshMethod="RenyiEntropy",
                              subtractBackground=True,
                              watershed=False,
                              minSize=0.00,
                              maxSize=30.00,
                              minCirc=0.00,
                              maxCirc=1.00)

            # Settings for channel4 threshold.
            c4 = countobjects(channels[3],
                              c4Results,
                              threshMethod="RenyiEntropy",
                              subtractBackground=True,
                              watershed=False,
                              minSize=0.20,
                              maxSize=100.00,
                              minCirc=0.00,
                              maxCirc=1.00)

            # Format filenames for thresholded .tiff files.
            outfileC1 = os.path.join(c1dir, "threshold_c1_{}".format(name))
            outfileC2 = os.path.join(c2dir, "threshold_c2_{}".format(name))
            outfileC3 = os.path.join(c3dir, "threshold_c3_{}".format(name))
            outfileC4 = os.path.join(c4dir, "threshold_c4_{}".format(name))

            # Save thresholded .tiff files.
            IJ.saveAs(c1.flatten(), "Tiff", outfileC1)
            IJ.saveAs(c2.flatten(), "Tiff", outfileC2)
            IJ.saveAs(c3.flatten(), "Tiff", outfileC3)
            IJ.saveAs(c4.flatten(), "Tiff", outfileC4)

    # Show results tables.


#    c1Results.show("channel1")
#    c2Results.show("channel2")
#    c3Results.show("channel3")
#    c4Results.show("channel4")

# Prepare results table filenames.
    c1out = os.path.join(outdir, "channel1.csv")
    c2out = os.path.join(outdir, "channel2.csv")
    c3out = os.path.join(outdir, "channel3.csv")
    c4out = os.path.join(outdir, "channel4.csv")

    # Save results tables.
    ResultsTable.save(c1Results, c1out)
    ResultsTable.save(c2Results, c2out)
    ResultsTable.save(c3Results, c3out)
    ResultsTable.save(c4Results, c4out)
Example #39
0
def glidingprojection(imp,
                      startframe=1,
                      stopframe=None,
                      glidingFlag=True,
                      no_frames_per_integral=3,
                      projectionmethod="Median"):
    """This function subtracts the gliding projection of several frames from the
    input stack. Thus, everything which moves too fast is filtered away.

    Args:
        imp (ImagePlus): Input image as ImagePlus object.
        startframe (int, optional): Choose a start frame. Defaults to 1.
        stopframe (int, optional): Choose an end frame. Defaults to None.
        glidingFlag (bool, optional): Should a gliding frame by frame projection be used? Defaults to True.
        no_frames_per_integral (int, optional): Number of frames to project each integral. Defaults to 3.
        projectionmethod (str, optional): Choose the projection method. Options are 
        'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median'. Defaults to "Median".

    Raises:
        RuntimeException: Start frame > stop frame.

    Returns:
        ImagePlus: The output stack.
    """
    # Store some image properties.
    cal = imp.getCalibration()
    width, height, nChannels, nSlices, nFrames = imp.getDimensions()
    title = imp.getTitle()

    # Some simple sanity checks for input parameters.
    if stopframe == None: stopframe = nFrames
    if (startframe > stopframe):
        IJ.showMessage("Start frame > Stop frame, can't go backwards in time!")
        raise RuntimeException("Start frame > Stop frame!")

    # If a subset of the image is to be projected, these lines of code handle that.
    if ((startframe != 1) or (stopframe != nFrames)):
        imp = Duplicator().run(imp, 1, nChannels, 1, nSlices, startframe,
                               stopframe)

    # Define the number of frames to advance per step based on boolean input parameter glidingFlag.
    if glidingFlag: frames_to_advance_per_step = 1
    else: frames_to_advance_per_step = no_frames_per_integral

    # Make a dict containg method_name:const_fieled_value pairs for the projection methods
    methods_as_strings = [
        'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices',
        'Standard Deviation', 'Median'
    ]
    methods_as_const = [
        ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD,
        ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD
    ]
    method_dict = dict(zip(methods_as_strings, methods_as_const))

    # Initialize a ZProjector object and an empty stack to collect projections.
    zp = ZProjector(imp)
    zp.setMethod(method_dict[projectionmethod])
    outstack = imp.createEmptyStack()

    # Loop through all the frames in the image, and project that frame with the other frames in the integral.
    for frame in range(1, nFrames + 1, frames_to_advance_per_step):
        zp.setStartSlice(frame)
        zp.setStopSlice(frame + no_frames_per_integral)
        zp.doProjection()
        outstack.addSlice(zp.getProjection().getProcessor())

    # Create an image processor from the newly created Z-projection stack
    # nFrames = outstack.getSize()/nChannels
    impout = ImagePlus(
        title + '_' + projectionmethod + '_' + str(no_frames_per_integral) +
        '_frames', outstack)
    impout = HyperStackConverter.toHyperStack(impout, nChannels, nSlices,
                                              nFrames)
    impout.setCalibration(cal)
    return impout
 def do_projection(self, channel, proj_type=None):
     proj = ZProjector()  ## create projection class
     if proj_type is None:
         if self.do_z[channel] == "MAX":
             proj.setMethod(ZProjector.MAX_METHOD)
         elif self.do_z[channel] == "AVG":
             proj.setMethod(ZProjector.AVG_METHOD)
         else:
             print "Dont know how to project this way"
             print "Just using a single slice for images!!"
             return None
     else:
         if proj_type == "MAX":
             proj.setMethod(ZProjector.MAX_METHOD)
         elif proj_type == "AVG":
             proj.setMethod(ZProjector.AVG_METHOD)
         else:
             print "Dont know how to project this way"
             print "Just using a single slice for images!!"
             return None
     proj.setImage(self.stack_imps[channel])
     proj.doProjection()
     projection = proj.getProjection()
     conv = ImageConverter(projection)
     conv.convertToGray16()
     conv.setDoScaling(False)
     self.projections[channel] = projection
     self.projections_done[channel] = self.do_z[channel]
def main():
    # ensure consistent preference settings
    Prefs.blackBackground = False

    # get locations for previous and new outputs
    params = Parameters()
    params.loadLastParams()
    output_folder_old, output_folder = mbio.rerun_location_chooser(
        params.input_image_path)
    params.loadParametersFromJson(
        os.path.join(output_folder_old, 'parameters used.json'))
    params.setOutputPath(output_folder)

    # present user with the familiar setup UI, with options that don't make sense/aren't yet implemented disabled
    params = mbui.analysis_parameters_gui(rerun_analysis=True, params=params)

    # get original image file (for overlays etc.)
    if not os.path.isfile(params.input_image_path):
        mbui.warning_dialog([
            "The original data can't be found at the location specified in saved parameters. ",
            "(Possibly something as simple as a change in network drive mapping has occurred)",
            "Please specify the location of the original image file..."
        ])
        params.setInputImagePath(
            mbio.input_file_location_chooser(params.output_path))

    import_opts, params = mbui.choose_series(params.input_image_path, params)
    imps = bf.openImagePlus(import_opts)
    imp = imps[0]

    if imp.getNSlices() > 1:
        mbui.warning_dialog([
            "More than one Z plane detected.",
            "I will do a maximum projection before proceeding", "Continue?"
        ])
        imp = ZProjector.run(imp, "max all")

    params = mbio.get_metadata(params)
    params.setCurvatureLengthUm(
        round(params.curvature_length_um / params.pixel_physical_size) *
        params.pixel_physical_size)
    params.persistParameters()
    IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel")
    imp.show()
    if imp.getNChannels() > 1:
        imp.setPosition(params.membrane_channel_number, 1, 1)
    mbui.autoset_zoom(imp)
    IJ.run("Enhance Contrast", "saturated=0.35")

    # prompt user to select ROI
    original_imp = Duplicator().run(imp)
    _, crop_params = mbui.crop_to_ROI(imp, params)
    imp.show()

    if crop_params is not None:
        params.perform_spatial_crop = True
        mbui.autoset_zoom(imp)
        imp.updateAndDraw()
        review_crop = mb.check_cropping(output_folder_old, params)
        keep_crop = not review_crop
        if review_crop:
            keep_crop = mbui.crop_review()
        if not keep_crop:
            imp.changes = False
            imp.close()
            imp = original_imp
        else:
            original_imp.close()
    else:
        original_imp.close()

    # prompt user to do time cropping
    imp, start_end_tuple = mbui.time_crop(imp, params)
    params.setTimeCropStartEnd(start_end_tuple)

    # import edges
    membrane_edges = mbio.load_qcd_edges2(
        os.path.join(output_folder_old, "user_defined_edges.zip"))
    mbio.save_qcd_edges2(membrane_edges, params.output_path)

    calculated_objects = CalculatedObjects()
    calculated_objects.membrane_edges = membrane_edges
    if params.time_crop_start_end[0] is not None:
        calculated_objects.timelist = [
            idx * params.frame_interval
            for idx in range(params.time_crop_start_end[0],
                             params.time_crop_start_end[1] + 1)
        ]
    else:
        calculated_objects.timelist = [
            idx * params.frame_interval for idx in range(imp.getNFrames())
        ]

    split_channels = mbfs.split_image_plus(imp, params)
    membrane_channel_imp = split_channels[0]
    actin_channel_imp = split_channels[1]
    segmentation_channel_imp = None
    if params.photobleaching_correction:
        if os.path.isfile(
                os.path.join(output_folder_old, 'binary_membrane_stack.tif')):
            segmentation_binary_path = os.path.join(
                output_folder_old, 'binary_membrane_stack.tif')
            segmentation_channel_imp = IJ.openImage(segmentation_binary_path)
        else:
            segmentation_channel_imp = split_channels[2]
            segmentation_channel_imp = mb.make_and_clean_binary(
                segmentation_channel_imp, params.threshold_method)
        split_channels[2] = segmentation_channel_imp

    calculated_objects = mbfs.calculate_outputs(params, calculated_objects,
                                                split_channels)

    # output colormapped images and kymographs
    fig_imp_list = mbfs.generate_and_save_figures(imp, calculated_objects,
                                                  params, membrane_channel_imp,
                                                  segmentation_channel_imp)
    mbfs.save_csvs(calculated_objects, params)

    params.saveParametersToJson(
        os.path.join(params.output_path, "parameters used.json"))
    imp.changes = False
    IJ.setTool("zoom")
    if params.close_on_completion:
        for fig_imp in fig_imp_list:
            fig_imp.close()
            imp.close()

    return
Example #42
0
def maxZprojection(stackimp):
	zp = ZProjector(stackimp)
	zp.setMethod(ZProjector.MAX_METHOD)
	zp.doProjection()
	zpimp = zp.getProjection()
	return zpimp