Ejemplo n.º 1
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", "")
 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]
Ejemplo n.º 3
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)
Ejemplo n.º 4
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
Ejemplo n.º 5
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
Ejemplo n.º 6
0
def Zproj(stackimp, method, z_ind, z_range):
    # Gets a stack and max project it.
    #	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
Ejemplo n.º 7
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)
Ejemplo n.º 8
0
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
Ejemplo n.º 9
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 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
Ejemplo n.º 11
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
	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
Ejemplo n.º 13
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()
Ejemplo n.º 14
0
	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)
Ejemplo n.º 15
0
    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)
Ejemplo n.º 16
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
Ejemplo n.º 17
0
 def maxZprojection(self, inputimg):
     zp = ZProjector(inputimg)
     zp.setMethod(ZProjector.MAX_METHOD)
     zp.doProjection()
     Zproj = zp.getProjection()
     return Zproj
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)
Ejemplo n.º 20
0
def ColMigBud():
    def setupDialog(imp):

        gd = GenericDialog("Collective migration buddy options")
        gd.addMessage("Collective migration buddy 2.0, you are analyzing: " +
                      imp.getTitle())
        calibration = imp.getCalibration()

        if (calibration.frameInterval > 0):
            default_interval = calibration.frameInterval
            default_timeunit = calibration.getTimeUnit()

        else:
            default_interval = 8
            default_timeunit = "min"

        gd.addNumericField("Frame interval:", default_interval,
                           2)  # show 2 decimals
        gd.addCheckbox("Do you want to use a gliding window?", True)
        gd.addCheckbox(
            "Project hyperStack? (defaluts to projecting current channel only)",
            False)
        gd.addStringField("time unit", default_timeunit, 3)
        gd.addSlider("Start compacting at frame:", 1, imp.getNFrames(), 1)
        gd.addSlider("Stop compacting at frame:", 1, imp.getNFrames(),
                     imp.getNFrames())
        gd.addNumericField("Number of frames to project in to one:", 3,
                           0)  # show 0 decimals

        gd.addChoice('Method to use for frame projection:', methods_as_strings,
                     methods_as_strings[5])

        gd.showDialog()

        if gd.wasCanceled():
            IJ.log("User canceled dialog!")
            return

        return gd

    #Start by getting the active image window and get the current active channel and other stats
    imp = WindowManager.getCurrentImage()
    cal = imp.getCalibration()
    nSlices = 1  #TODO fix this in case you want to do Z-stacks
    title = imp.getTitle()
    current_channel = imp.getChannel()
    #zp = ZProjector(imp)

    #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
    ]
    medthod_dict = dict(zip(methods_as_strings, methods_as_const))

    # Run the setupDialog, read out and store the options
    gd = setupDialog(imp)
    frame_interval = gd.getNextNumber()
    time_unit = gd.getNextString()
    glidingFlag = gd.getNextBoolean()
    hyperstackFlag = gd.getNextBoolean()

    #Set the frame interval and unit, and store it in the ImagePlus calibration
    cal.frameInterval = frame_interval
    cal.setTimeUnit(time_unit)
    imp.setCalibration(cal)

    start_frame = int(gd.getNextNumber())
    stop_frame = int(gd.getNextNumber())

    #If a subset of the image is to be projected, these lines of code handle that
    if (start_frame > stop_frame):
        IJ.showMessage("Start frame > Stop frame, can't go backwards in time!")
        raise RuntimeException("Start frame > Stop frame!")

    if ((start_frame != 1) or (stop_frame != imp.getNFrames())):
        imp = Duplicator().run(imp, 1, nChannels, 1, nSlices, start_frame,
                               stop_frame)

    no_frames_per_integral = int(gd.getNextNumber())

    #the doHyperstackProjection method can't project past the end of the stack
    if hyperstackFlag:
        total_no_frames_to_project = imp.getNFrames() - no_frames_per_integral
    #the doProjection method can project past the end, it just adds black frames at the end
    #When not projecting hyperstacks, just copy the current active channel from the active image
    else:
        total_no_frames_to_project = imp.getNFrames()
        imp = Duplicator().run(imp, current_channel, current_channel, 1,
                               nSlices, start_frame, stop_frame)

    #The Z-Projection magic happens here through a ZProjector object
    zp = ZProjector(imp)
    projection_method = gd.getNextChoice()
    chosen_method = medthod_dict[projection_method]
    zp.setMethod(chosen_method)
    outstack = imp.createEmptyStack()

    if glidingFlag:
        frames_to_advance_per_step = 1
    else:
        frames_to_advance_per_step = no_frames_per_integral

    for frame in range(1, total_no_frames_to_project,
                       frames_to_advance_per_step):
        zp.setStartSlice(frame)
        zp.setStopSlice(frame + no_frames_per_integral)
        if hyperstackFlag:
            zp.doHyperStackProjection(False)
            projected_stack = zp.getProjection().getStack()
            for channel in range(projected_stack.getSize()):
                outstack.addSlice(projected_stack.getProcessor(channel + 1))
        else:
            zp.doProjection()
            outstack.addSlice(zp.getProjection().getProcessor())

    #Create an image processor from the newly created Z-projection stack
    nChannels = imp.getNChannels()
    nFrames = outstack.getSize() / nChannels
    imp2 = ImagePlus(
        title + '_' + projection_method + '_' + str(no_frames_per_integral) +
        '_frames', outstack)
    imp2 = HyperStackConverter.toHyperStack(imp2, nChannels, nSlices, nFrames)
    imp2.show()

    Startmenu()
Ejemplo n.º 21
0
options = getOptions()
if options is not None:
    runCamR, runCamL, CamRScale, CamLScale, BackgroundWindowStart, BackgroundWindowEnd, GridSize, TranslateR, TranslateL = options  # unpack each parameter
    print runCamR, runCamL, CamRScale, CamLScale, BackgroundWindowStart, BackgroundWindowEnd, GridSize, TranslateR, TranslateL

if runCamR:
    impR1 = FolderOpener.open(folder, "file=CamR sort")
    UID = impR1.title
    filepath = folder.strip(UID + '/')

    projectR = ZProjector(impR1)
    projectR.setMethod(ZProjector.AVG_METHOD)
    projectR.setImage(impR1)
    projectR.setStartSlice(int(BackgroundWindowStart))
    projectR.setStopSlice(int(BackgroundWindowEnd))
    projectR.doProjection()
    projectionR = projectR.getProjection()

    impR2 = ImageCalculator().run("Subtract create stack", impR1, projectionR)
    IJ.run(impR2, "Enhance Contrast", "saturated=0.4 process_all")
    IJ.run(impR2, "Set Scale...",
           "distance=" + str(CamRScale) + " known=1 unit=cm")
    IJ.run(impR2, "Grid...",
           "grid=Lines area=" + str(GridSize) + " color=Cyan")
    IJ.run(impR2, "Translate...",
           "x=" + str(TranslateR) + " y=0 interpolation=None stack")

    savepath = path.join(folder, UID + "_CR.tif")
    print savepath
    fs = FileSaver(impR2)
    if fs.saveAsTiffStack(savepath):
Ejemplo n.º 22
0
def BackgroundFilter():
    def setupDialog(imp):

        gd = GenericDialog("Toolbox options")
        gd.addMessage("Imagej toolbox, you are analyzing: " + imp.getTitle())
        calibration = imp.getCalibration()

        if (calibration.frameInterval > 0):
            default_interval = calibration.frameInterval
            default_timeunit = calibration.getTimeUnit()

        else:
            default_interval = 10
            default_timeunit = "sec"

        gd.addNumericField("Frame interval:", default_interval,
                           2)  # show 2 decimals
        #    gd.addCheckbox("Do you want to use a gliding window?", True)
        #    gd.addCheckbox("Project hyperStack? (defaluts to projecting current channel only)", False)
        #    gd.addStringField("time unit",default_timeunit, 3)
        #    gd.addSlider("Start compacting at frame:", 1, imp.getNFrames(), 1)
        #    gd.addSlider("Stop compacting at frame:", 1, imp.getNFrames(), imp.getNFrames())
        #    gd.addNumericField("Number of frames to project in to one:", 3, 0)  # show 0 decimals

        gd.addChoice('Method to use for stack background filtering:',
                     methods_as_strings, methods_as_strings[5])

        gd.showDialog()

        if gd.wasCanceled():
            IJ.log("User canceled dialog!")
            return

        return gd

    #Start by getting the active image window and get the current active channel and other stats
    imp = WindowManager.getCurrentImage()
    cal = imp.getCalibration()
    nSlices = 1  #TODO fix this in case you want to do Z-stacks
    title = imp.getTitle()
    current_channel = imp.getChannel()
    #zp = ZProjector(imp)

    #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))

    gd = setupDialog(imp)

    #The Z-Projection magic happens here through a ZProjector object
    zp = ZProjector(imp)
    projection_method = gd.getNextChoice()
    chosen_method = method_dict[projection_method]
    zp.setMethod(chosen_method)
    outstack = imp.createEmptyStack()

    zp.doProjection()
    outstack.addSlice(zp.getProjection().getProcessor())
    imp2 = ImagePlus(title + '_' + projection_method, outstack)
    # imp2.show()
    imp3 = ImageCalculator().run("Subtract create 32-bit stack", imp, imp2)
    imp3.show()

    Startmenu()
Ejemplo n.º 23
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)
Ejemplo n.º 24
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
Ejemplo n.º 25
0
# TODO : Should work fine for CZIs but could be
# improved with default values or min/max values.
emissionWL = [0]
try:
    for x in xrange(1,nbrChannels+1,1):
        WL = int(imp.getNumericProperty("Information|Image|Channel|EmissionWavelength #" + str(x).zfill(2)))
        emissionWL.append(WL)
except ValueError:
    raise Exception("Couldn't find the EmissionWavelength info in the metadata")

# Make the maximum intensity projection
# and show it for user input.
project = ZProjector()
project.setMethod(ZProjector.MAX_METHOD)
project.setImage(imp)
project.doProjection()
projection = project.getProjection()
projection.show()

# Wait for the user to draw a line
# and check if line ROI.
IJ.setTool("line");
myWait = WaitForUserDialog ("waitForUser", "Make a line with the region of interest and press OK")
myWait.show()

roi = projection.getRoi()

# Check if roi is a line
# otherwise exit
if not (roi.isLine()):
    raise Exception("Line selection required")
Ejemplo n.º 26
0
def imageprojector(channels, timelist_unsorted, dirs):
	""" Projects .lif timepoints and saves in a common directory,
	    as well as channel separated directories. """
	
	# Defines in path
	path = str(Experiment)

	# BF Importer
	options = ImporterOptions()
	
	try:
		options.setId(path)
	except Exception(e):
		print str(e)
		
	options.setOpenAllSeries(True)
	options.setSplitTimepoints(True)
	options.setSplitChannels(True)
	imps = BF.openImagePlus(options)

	timelist = [x for item in timelist_unsorted for x in repeat(item, channels)]
	timelist, imps = zip(*sorted(zip(timelist, imps)))

	
	counter_C0 = -1
	counter_C1 = -1
	counter_C2 = -1
	# Opens all images, splits channels, z-projects and saves to disk
	for imp in (imps):
		# Projection, Sum Intensity
   		project = ZProjector()
		project.setMethod(ZProjector.SUM_METHOD)
		project.setImage(imp)
		project.doProjection()
		impout = project.getProjection()
		projection = impout.getTitle()

		try:
			# Saves channels to disk, 
			# add more channels here if desired, 
			# remember to define new counters.
			if "C=0" in projection:
				counter_C0 += 1
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections"],
				          "Scan" + str(counter_C0).zfill(3) + "C0"))
                
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections_C0"],
				          "Scan" + str(counter_C0).zfill(3) + "C0"))		
			
			elif "C=1" in projection:
				counter_C1 += 1
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections"],
				          "Scan" + str(counter_C1).zfill(3) + "C1"))
                         
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections_C1"],
				          "Scan" + str(counter_C1).zfill(3) + "C1"))

			elif "C=2" in projection:
				counter_C2 += 1
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections"],
				          "Scan" + str(counter_C2).zfill(3) + "C2"))
                         
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections_C2"],
				          "Scan" + str(counter_C2).zfill(3) + "C2"))
		
		except IOException:
			print "Directory does not exist"
			raise

	IJ.log("Images projected and saved to disk")
		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
		stack = impM.getStack()
		# crop(int x, int y, int z, int width, int height, int depth)
Ejemplo n.º 28
0
def maxZprojection(stackimp):
	zp = ZProjector(stackimp)
	zp.setMethod(ZProjector.MAX_METHOD)
	zp.doProjection()
	zpimp = zp.getProjection()
	return zpimp
Ejemplo n.º 29
0
# Initialize XML and arrays where to store the values
xml = '<?xml version="1.0" encoding="utf-8"?><DyeData>'
profiles=[]
names=[]
for idye_,imp in enumerate(imps):
	idye = idye_+1

	# Assumes names are FILENAME+" - "+SERIESNAME
	names.append(imp.title.split(" - ")[1])

	xml+="<Dye%d>"%(idye)

	# ZProject
	zp = ZProjector(imp)
	zp.setMethod(zp.MAX_METHOD)
	zp.doProjection()
	imp_mi = zp.getProjection()
	imp_mip = imp_mi.getProcessor()

	# autothreshold using the Triangle method and get the thresholds
	imp_mip.setAutoThreshold(AutoThresholder.Method.Triangle,True)
	mint = imp_mip.getMinThreshold()
	maxt = imp_mip.getMaxThreshold()

	# we don't need the MIP anymore
	imp_mi.close()

	# For each channel, get the mean value above threshold and store it
	profile=[]
	for ich in range(imp.getNChannels()):
		p = imp.getStack().getProcessor(ich+1)