def containsRoot_(self):
     IJ.run("Clear Results")
     IJ.run("Measure")
     table = RT.getResultsTable()
     if RT.getValue(table, "Max", 0) == 0:
         return False
     return True
def executeTask_Weka(validParticles, **kwargs):
	'''execute task for microscope'''
	zk = ZeissKeys()
	msg = Message()
	if validParticles is None or len(validParticles) < kwargs["nrPart"]:
		IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_NOTHING+"] windows=REG_SZ")
		return
def threshold(imp, threshold):
	""" Threshold image """
	impout = Duplicator().run(imp)
	IJ.setThreshold(impout, threshold, 1000000000)
	IJ.run(impout, "Convert to Mask", "stack")
	impout.setTitle("Threshold");
	return impout
Exemplo n.º 4
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", "")
Exemplo n.º 5
0
def run():
    gd = GenericDialogPlus("ND2 Conversion Tool")
    gd.addMessage("This plugin uses BioFormats to convert ND2 images to JPEG for further processing in ImageJ.")
    gd.addDirectoryOrFileField("Input: ", "G:\\Subdir testing\\") #srcDir
    gd.addDirectoryOrFileField("Output: ", "G:\\Subdir testing\\") #dstDir
    gd.addStringField("File name contains: ", "") #nameContains
    gd.addCheckbox("Preserve directory structure?", True) #keepDirs
    gd.addCheckbox("Run in headless mode?", True) #anneBoleyn 
    gd.addCheckbox("Overwrite existing output files?", True)
    gd.showDialog()
    if gd.wasCanceled():
        return
    srcDir = gd.getNextString()
    dstDir = gd.getNextString()
    nameContains = gd.getNextString()
    keepDirectories = gd.getNextBoolean()
    anneBoleyn = gd.getNextBoolean()
    overOut = gd.getNextBoolean()
    IJ.run("Input/Output...", "jpeg=100")
    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            # Check for file extension
            if not filename.endswith(".nd2"):
                continue
            # Check for file name pattern
            if nameContains not in filename:
                continue
            process(srcDir, dstDir, nameContains, root, filename, keepDirectories, anneBoleyn, overOut)
def threshold(imp, lower, upper):
	duplicate=Duplicator().run(imp)
	duplicate.getProcessor().resetMinAndMax()
	IJ.setAutoThreshold(duplicate, "Default dark");
	IJ.setThreshold(duplicate, lower, upper)
	IJ.run(duplicate, "Convert to Mask", "");
	return duplicate
def run_straighten(roiWindowsize = 4):
    """ Original straightening function based on Nick's macro. Used in final version.
    Returns coordinate string used to make centerline. """
    IJ.run("Set Measurements...", "mean min center redirect=None decimal=3")
    IJ.runMacro("//setTool(\"freeline\");")
    IJ.run("Line Width...", "line=80");
    numPoints = 512/roiWindowsize
    xvals = []
    yvals = []
    maxvals = []
    counter = 0

    for i in range(0, 512, roiWindowsize):
        IJ.run("Clear Results")
        IJ.makeRectangle(i, 0, roiWindowsize, 512)
        IJ.run("Measure")
        table = RT.getResultsTable()
        xvals.append(i + roiWindowsize/2)
        yvals.append(RT.getValue(table, "YM", 0))
        maxvals.append((RT.getValue(table, "Max", 0)))

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

        counter += 1

    coords = ""
    for i in range(numPoints - 1):
        coords += str(xvals[i]) + ", " + str(yvals[i]) +", "
    coords += str(xvals[numPoints-1]) + ", " + str(yvals[numPoints-1])

    IJ.runMacro("makeLine("+coords+")")
    IJ.run("Straighten...", "line = 80")
    return coords
def measureTumor(original, locations):
	'''Returns the area from the original image with the 
	highest kurtosis which generally corresponds to the most
	in focus image. Also saves an image corresponding to a mask
	of the measurement.'''
	# Prevent ROI manager from appearing
	roiM = RoiManager(True)
	ParticleAnalyzer.setRoiManager(roiM)
	# Locate particles above a minimum size and with a desired circularity
	IJ.run(locations, "Analyze Particles...", "size=" + str(minimumCancerArea) +"-" + str(maxCancerArea) +" circularity=" + str(circularityCutoff) + "-1.00 show=Nothing exclude add stack");
	# Choose ROI with the highest kurtosis
	maxKurtosis = None
	area = None
	selectedROI = None
	for roi in roiM.getRoisAsArray():
		original.setRoi(roi)
		stats = original.getStatistics(Measurements.KURTOSIS, Measurements.AREA)
		currentKurtosis = stats.kurtosis
		if currentKurtosis > maxKurtosis:
			maxKurtosis = stats.kurtosis
			area = stats.area
			selectedROI = roi
	original.killRoi() # Remove the remaining ROI
	roiM.runCommand("Reset")
	return (area, selectedROI)
Exemplo n.º 9
0
	def __dia(self, event): 
		IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel")
		#IJ.run("Properties...", "channels=1 slices=1 frames=20 unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000 frame=[1 sec] origin=0,0");
		self.__impD = IJ.getImage()
		self.__isD = self.__impD.getImageStack()
		self.__display.text = "DIA="+self.__impD.getTitle()
		self.__initDIA = True
Exemplo n.º 10
0
def adjustScale(original):
	'''Assuming that the units outported by the Zeiss microscope are mm or \mu-m,
	adjust the units so they are in mm.'''
	pixelWidth = original.getCalibration().pixelWidth
	if pixelWidth > 1:
		newScale = 1000*(1.0/pixelWidth)
		IJ.run("Set Scale...", "distance=" + str(newScale) + " known=1 pixel=1 unit=mm")	
def run():
  srcDir = DirectoryChooser("Choose!").getDirectory()
  if not srcDir:
    # user canceled dialog
    return
  
  for root, directories, filenames in os.walk(srcDir):
    for filename in filenames:
      # Skip non-TIFF files
      if not filename.endswith(fileID):
        continue
      path = os.path.join(root, filename)
      print path
      imp = IJ.openImage(path)
      imp.show()
      if method=="contrast":
        IJ.run(imp,"Enhance Contrast", "saturated=0.35");
        time.sleep(0.2)
        IJ.save(imp,path + "_auto.jpeg")
        imp.changes = False
        imp.getWindow().close()
      elif method=="scale":
        IJ.run(imp, "Scale...", "x=0.2 y=0.2 interpolation=None create title=small");      
        impScale = IJ.getImage()
        time.sleep(0.2)
        IJ.save(impScale,path + "_thumb.jpeg")
        imp.changes = False
        imp.getWindow().close()
        impScale.changes = False
        impScale.getWindow().close()
Exemplo n.º 12
0
def extractRIM(impbin, iteration):
	IJ.run(imp, "Options...", "iterations=1 count=1 edm=Overwrite do=Nothing");
	impErode = Duplicator().run(impbin)
	impDilate = Duplicator().run(impbin)	
#	resized = CanvasResizer().expandStack(impDilate.getStack(), impDilate.getWidth()+2*iteration, impDilate.getHeight()+2*iteration, iteration, iteration)
#	impDilate.setStack(None, resized);
	for j in range(impErode.getStackSize()):
		ipe = impErode.getStack().getProcessor(j+1)
		ipe.setBackgroundValue(0)
		ipd = impDilate.getStack().getProcessor(j+1)
		ipd.setBackgroundValue(0)
		for i in range(iteration):
			ipe.erode()
			ipd.dilate()
#		IJ.run(impErode, "Dilate", "stack")
#		IJ.run(impDilate, "Erode", "stack")
#	resized = CanvasResizer().expandStack(impDilate.getStack(), impDilate.getWidth()-2*iteration, impDilate.getHeight()-2*iteration, -1*iteration, -1*iteration)
#	impDilate.setStack(None, resized);
#	impErode.show()
#	Duplicator().run(impDilate).show()	
	for i in range(1, impbin.getStackSize()+1):
		impDilate.setSlice(i)
		impErode.setSlice(i)
		ImageCalculator().calculate("XOR", impDilate, impErode)
	return impDilate;
Exemplo n.º 13
0
def makeStack(stackDir, stackName = "stack"):
    IJ.run("Image Sequence...", "open="+stackDir+" file = (\"img_.*\") sort")
    imp = IJ.getImage()
    #IJ.run("8-bit")
    fs = FileSaver(imp)
    print "Saving stack"
    fs.saveAsTiff(stackDir + "/" +stackName+".tif")
Exemplo n.º 14
0
def gaussian_blur_8_bks(imp, size):
	"""
	gaussian_blur_8_bks(imp, size)

	Perform a Gaussian Blur on an 8 bit gray scale
	image, use that to do a background correction,
	and return the background corrected image. The
	blur size is 0.3*image width

	Parameters
	==========
	imp:	ImagePlus
			The 8 bit gray scale input image

	Returns
	=======
	bks:	The image plus of the backround-subtracted
			gray scale image
	size:	The size in px of the blur. Should be about
			40% of the image size	
	"""
	strSize = "sigma=%i" % (size)
	imp.show()
	IJ.run("Gaussian Blur...", strSize)
	ti = imp.getShortTitle()
	ti += "_gb"
	imp.setTitle(ti)
	return(imp)
Exemplo n.º 15
0
def run_script():
    '''Function to be run when this file is used as a script'''
    selected_mode, img1_in, img2_in = get_setup()
    if not selected_mode:
        return
    corrected_stack = drift.get_corrected_stack((img1_in, img2_in), mode=selected_mode)
    img1, img2 = tools.stack_to_list_of_imp(corrected_stack)
    img_ratio = ImageCalculator().run('Divide create', img2, img1)
    img_ratio.setTitle('Jump-ratio [%s divided by %s]' % (img2.getShortTitle(),
                                                          img1.getShortTitle())
                      )
    img_ratio.changes = True
    img_ratio.copyScale(img1_in)
    img_ratio.show()
    IJ.run(img_ratio, 'Enhance Contrast', 'saturated=0.35')
    # We want to optimise the lower displaylimit:
    minimum = img_ratio.getProcessor().getMin()
    maximum = img_ratio.getProcessor().getMax()
    stat = img_ratio.getStatistics(Stats.MEAN + Stats.STD_DEV)
    mean = stat.mean
    stdv = stat.stdDev
    if minimum < mean - stdv:
        if mean - stdv >= 0:
            img_ratio.getProcessor().setMinAndMax(mean - stdv, maximum)
        else:
            img_ratio.getProcessor().setMinAndMax(0, maximum)
        img_ratio.updateAndDraw()
Exemplo n.º 16
0
def rgb_from_r_g_b(r, g, b, title):
	"""
	rgb_from_r_g_b(r, g, b, title)

	Generate an RGB image from three 8/bit per pixel
	gray scale images

	Parameters
    ----------
    r:	An ImagePlus
        The red channel
    g:	An ImagePlus
        The green channel
    b:	An ImagePlus
        The blue channel
    title: a string
    	The title for the image
    
    Returns
    -------
    impRGB:	An ImagePlus
    	The RGB image
	"""
	tiR = r.getTitle()
	tiG = g.getTitle()
	tiB = b.getTitle()

	strTwo = "c1=[%s] c2=[%s] c3=[%s]" % (tiR, tiG, tiB)
	IJ.run("Merge Channels...", strTwo)
	impRecon = IJ.getImage()
	impRecon.show()
	return(impRecon)  
Exemplo n.º 17
0
def run_stitch(filePath):
	basePath,baseName = os.path.split(filePath)
	imagePrefix = os.path.splitext(baseName)[0]
	resizeName = basePath + "/" + baseName + "_tiles/resized/"
	checkName = basePath + "/" + baseName + "_tiles/resized/" + imagePrefix + "_seq/"
	activeName = basePath + "/" + baseName + "_tiles"
	IJ.log("Stitching " + filePath + "...")
	if (not os.path.isdir(checkName)):
		thread = Thread.currentThread()
		originalThread = thread.getName()
		thread.setName("Run$_stitch_process")
		options = "choose=" + resizeName + " select=" + activeName + "/tile_info.txt image_prefix=" + imagePrefix
		Macro.setOptions(Thread.currentThread(),options)
		try:
			IJ.run("Stitch wrapper",options)
			IJ.log("succeeded")
			returnVal = 0
		except:
			IJ.log("failed")
			os.rmdir(checkName)
			returnVal = 1
		thread.setName(originalThread)
		Macro.setOptions(thread,None)
	else:
		IJ.log("skipped")
		returnVal = 2

	return returnVal
Exemplo n.º 18
0
def autoProcAZtecImage(fwMicrons, wrkDir, barWid=0.1, barHt=9, barFnt=24, barCol="Black", barLoc="Lower Right"):
	imp = IJ.getImage()
	fName = imp.getShortTitle()
	wid = imp.getWidth()
	argThree = "distance=%g known=%f pixel=1 unit=um" % (wid, fwMicrons)
	IJ.run(imp, "Set Scale...", argThree)
	IJ.run(imp, "Enhance Contrast", "saturated=0.35")
	fs = FileSaver(imp) 
	if path.exists(wrkDir) and path.isdir(wrkDir):
		print "folder exists:", wrkDir
		tifName = fName + ".tif"
		tifPath = path.join(wrkDir, tifName)
		print(tifPath)
		if fs.saveAsTiff(tifPath):
			print "Tif saved successfully at ", tifPath  
				
	IJ.run(imp, "RGB Color", "")
	# dummy to get things set
	foo = imp.duplicate()
	s2 = "width=%g height=%g font=%g color=%s location=[%s] bold" % (barWid, barHt, barFnt, barCol, barLoc)
	IJ.run(foo, "Add Scale Bar", s2)
	# explicitly save preferences
	Prefs.savePreferences()
	foo.changes = False
	foo.close()
	IJ.run(imp, "Add Scale Bar", s2)
	fs = FileSaver(imp) 
	pngName = fName + ".png"
	pngPath = path.join(wrkDir, pngName)
	if fs.saveAsPng(pngPath):
		print "png saved successfully at ", pngPath  
Exemplo n.º 19
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)
Exemplo n.º 20
0
 def __init__(self, img_list, params=None):
     '''Create an instance of pySIFT.
     :param img_list: All SIFT calculations are done with the given list
                      of ImagePlus objects (Classes that extend ImagePlus are allowed).
     :param params: Pass a modified instance of Param
                    to customize the SIFT detection (default: None).
     '''
     self.images = []
     def check(img):
         '''Returns True if img is a an ImagePlus or a class that extends it.'''
         # Check if the given object extends ImagePlus:
         return isinstance(img, ImagePlus)
     for img in img_list:
         if check(img):
             if img.getBitDepth() == 32:
                 # For 32-bit the images are normalized
                 # to bypass a limitation of the SIFT implementation.
                 img_dup = img.crop()
                 mean = img_dup.getProcessor().getStatistics().mean
                 IJ.run(img_dup, "Divide...", "value=%f" % (mean,))
                 IJ.run(img_dup, "Enhance Contrast", "saturated=0.1")
                 self.images.append(img_dup)
             else:
                 self.images.append(img)
     if params and isinstance(params, Param):
         self.param = params
     else:
         self.param = Param()
     self.drift_vector = [None] * len(self.images)
     self.drift_matrix = [[]] * len(self.images)
     for i, _ in enumerate(self.drift_matrix):
         self.drift_matrix[i] = [None] * len(self.images)
     self._extract_features_()
Exemplo n.º 21
0
def rankFilterMapImage(imp, radius=1.5, no=2):
  """clipNoisePixMapImage(imp, no=2)
  Clips noise pixels from an X-ray map image (typically a 16 bit gray image). 
  First, it sets the display range to a noise offset to max and removes the noise
  pixels (to get rid of isolated pixels), then converts to an 8 bit image that spans
  0 to 255 and returns an 8 bit gray scale. This is ready for a  hueLUT. It peforms
  this on a duplicate imp and returns the resultant imp. To the best of my understanding,
  this is how Oxford treats their maps w/o a 3x3 smooth. 
  Inputs:
  imp - the input ImagePlus object
  no  - the noise offset, default = 2, to remove noise pixels
  Returns:
  ret - an ImapePlus for the 8-bit, scaled, filtered image
  """
  stats = imp.getStatistics(Measurements.MIN_MAX)
  imp.setDisplayRange(0, stats.max)
  ret = imp.duplicate()
  ip = ret.getProcessor()
  data = ip.getPixels()
  l = len(data)
  for i in range(l):
    val = data[i]
    if val < no:
      data[i] = 0
  rf = RankFilters()
  rf.rank(ret.getProcessor(), radius, RankFilters.MEDIAN)
  IJ.run(ret, "8-bit", "")
  name = imp.getShortTitle()
  stats = ret.getStatistics(Measurements.MIN_MAX)
  ret.setDisplayRange(0, stats.max)
  ret.setTitle(name)
  return ret 
Exemplo n.º 22
0
def anaParticles(imp, minSize, maxSize, minCirc, bHeadless=True):
  """anaParticles(imp, minSize, maxSize, minCirc, bHeadless=True)
  Analyze particles using a watershed separation. If headless=True, we cannot
  redirect the intensity measurement to the original immage becuae it is never
  displayed. If we display the original, we can and get the mean gray level. We
  may then compute the particle contrast from the measured Izero value for the image.
  No ability here to draw outlines on the original."""
  strName = imp.getShortTitle()
  imp.setTitle("original")
  ret = imp.duplicate()
  IJ.run(ret, "Enhance Contrast", "saturated=0.35")
  IJ.run(ret, "8-bit", "")
  IJ.run(ret, "Threshold", "method=Default white")
  IJ.run(ret, "Watershed", "")
  rt = ResultsTable()
  # strSetMeas = "area mean modal min center perimeter bounding fit shape feret's redirect='original' decimal=3"
  # N.B. redirect will not work without a displayed image, so we cannot use a gray level image
  if bHeadless == True:
    strSetMeas = "area mean modal min center perimeter bounding fit shape feret's decimal=3"
  else:
    imp.show()
    strSetMeas = "area mean modal min center perimeter bounding fit shape feret's redirect='original' decimal=3"
  IJ.run("Set Measurements...", strSetMeas)
  # note this doies not get passed directly to ParticleAnalyzer, so
  # I did this, saved everything and looked for the measurement value in ~/Library/Preferences/IJ_Prefs.txt
  # measurements=27355
  # meas = Measurements.AREA + Measurements.CIRCULARITY + Measurements.PERIMETER + Measurements.SHAPE_DESCRIPTORS
  # didn't work reliably
  meas = 27355
  pa = ParticleAnalyzer(0, meas, rt, minSize, maxSize, minCirc, 1.0);
  pa.analyze(ret);
  rt.createTableFromImage(ret.getProcessor())
  return [ret, rt]
Exemplo n.º 23
0
def smoothMapImage(imp, no=2):
  """smoothMapImage(imp, no=2)
  Smooths an X-ray map image (typically a 16 bit gray image). First, it sets the
  display range to a noise offset to the max and sets pixels below the noise offset
  to zero (to get rid of isolated pixels), converts to an 8
  bit image that spans no to 255 and smooths with a 3x3 kernel. and
  converts it to an 8 bit gray scale image that spans 0-255. This is
  ready for a  hueLUT. It peforms this on a duplicate imp and returns
  the resultant imp. To the best of my understanding, this is how Oxford
  treats their maps. 
  Inputs:
  imp - the input ImagePlus object
  no  - the noise offset, default = 2, to remove noise pixels
  Returns:
  ret - an ImapePlus for the 8-bit, scaled, filtered image
  """
  stats = imp.getStatistics(Measurements.MIN_MAX)
  imp.setDisplayRange(no, stats.max)
  ret = imp.duplicate()
  ip = ret.getProcessor()
  data = ip.getPixels()
  l = len(data)
  for i in range(l):
    val = data[i]
    if val < no:
      data[i] = 0
  IJ.run(ret, "8-bit", "")
  name = imp.getShortTitle()
  ip = ret.getProcessor()
  ip.smooth()
  stats = ret.getStatistics(Measurements.MIN_MAX)
  ret.setDisplayRange(0, stats.max)
  ret.setTitle(name)
  return ret
Exemplo n.º 24
0
def bSaveZProject(imp, dstFolder, shortname):
	#bring to front
	impWinStr = imp.getTitle()
	IJ.selectWindow(impWinStr)
	
	bPrintLog('Making Z-Project from ' + impWinStr, 2)
	madez = 0
	z1 = 1
	z2 = imp.getNSlices()
	if z2>1:
		paramStr = 'start=%s stop=%s projection=[Max Intensity]' % (z1, z2)
		IJ.run('Z Project...', paramStr) #makes 'MAX_' window
		zWinStr = 'MAX_' + impWinStr
		zImp = WindowManager.getImage(zWinStr)
		madez = 1
	else:
		zImp = imp
			
	if dstFolder != None:
		dstFile = dstFolder + 'max_' + shortname + '.tif'
		bPrintLog('Saving Z-Project: ' + dstFile, 2)
		bSaveStack(zImp, dstFile)

	if madez:
		zImp.changes = 0
		zImp.close()
Exemplo n.º 25
0
	def __fluo(self, event): 
		IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel")
		IJ.run("Set Measurements...", "area mean standard modal min centroid shape integrated median skewness kurtosis stack limit display redirect=None decimal=3")
		self.__impF = IJ.getImage()
		self.__isF = self.__impF.getImageStack()
		self.__display.text = "FLUO="+self.__impF.getTitle()
		self.__initFLUO = True
def Make8bit_UsingMinMax(_imp):
    imp = _imp.duplicate()
    stats = StackStatistics(imp)
    IJ.setMinAndMax(imp, stats.min, stats.max)
    IJ.run(imp, "8-bit", "")
    IJ.setMinAndMax(imp, 0, 255)
    return imp
Exemplo n.º 27
0
def createOutputImg(image, rois, particle, ptsFcs=None):
    """create an output image which as overlay of channel"""
    IJ.setForegroundColor(255, 0, 0)

    IJ.run(image, "Enhance Contrast", "saturated=0")
    IJ.run(image, "RGB Color", "")
    IJ.setForegroundColor(255, 0, 0)
    ip = image.getProcessor()

    ip.setColor(Color.red)
    for roi in rois:
        ip.draw(roi)
    ip.setColor(Color.green)
    if particle is not None:
        for part in particle:
            ip.draw(rois[part])

    ip.setLineWidth(2)
    ip.setColor(Color.white)
    if ptsFcs is not None:
        print "Some fcs points"
        for i, pt in enumerate(ptsFcs):
            drawCross(ip, pt, 8)
            ip.drawString(str(i + 1), pt[0] + 1, pt[1] - 1)
    image.setProcessor(ip)
    return image
Exemplo n.º 28
0
def run():

    print '======================'
    print 'running'

    if len(sys.argv)<2:
        print 'bAlignCrop will align a stack.'
        print 'Usage: ./fiji'
        filePath = '/Users/cudmore/Desktop/X20150214_a156_010_ch1_c.tif'
        #return
    else:
        filePath = sys.argv[1]
    
    #check that file exists
    if not os.path.isfile(filePath):
        print 'Error: did not find file ', filePath
        return
        
    #open file
    print 'opening file:', filePath
    imp = IJ.openImage(filePath)

    if imp is None:
        print 'Error opening file'
        return

    imp.show()
    winTitle = imp.getTitle()

    transformationFile = filePath + '.txt'
    
    print 'running multistack reg'
    #IJ.run(imp, "MultiStackReg", "stack_1=X20150214_a156_010_ch1_c.tif action_1=Align file_1=[] stack_2=None action_2=Ignore file_2=[] transformation=Translation save");
    stackRegParams = 'stack_1=%s action_1=[Align] file_1=[%s] transformation=[Translation] save' %(winTitle, transformationFile)
    IJ.run('MultiStackReg', stackRegParams)
Exemplo n.º 29
0
def mask(ip, valueA, valueB):
	""" Mask the image with a threshold value ranging between valueA and valueB"""
	ip.setThreshold(valueA, valueB, ImageProcessor.NO_LUT_UPDATE)
	imp = ImagePlus('Mask', ip)
	IJ.run(imp, "Convert to Mask", "")
	
	return imp
Exemplo n.º 30
0
def test_HD():

	imp = IJ.openImage(filePath.getAbsolutePath())
	stack = imp.getStack()
	ip1 = stack.getProcessor(1).duplicate()
	ip2 = stack.getProcessor(2).duplicate()
	[ip1, s] = scaleLongSide(ip1, longSide)
	if (Scale == 1):
		ip2 = scale(ip2, s)
	maskA = impMask1.duplicate()
	maskB = impMask2.duplicate()

#	IJ.run(maskA, "Invert", "")
#	IJ.run(maskB, "Invert", "")
	IJ.run(maskA, "Outline", "")
	IJ.run(maskB, "Outline", "")
#	IJ.run(maskA, "Invert", "")
#	IJ.run(maskB, "Invert", "")
	maskA.show()
	maskB.show()

	impMask1.show()
	MaskArea1 = maskArea( impMask1.getProcessor() )
	impMask2.show()
	MaskArea2 = maskArea( impMask2.getProcessor() )
	hd = Hausdorff_Distance()
	hd.exec( maskA, maskB )
	print(hd.getAveragedHausdorffDistance())
	print(hd.getHausdorffDistance())
Exemplo n.º 31
0
def XYTCZL(directory_load, directory_save, chl, frames, z_planes, loops, total,
           pat, title):
    def pattern_closer(pat):
        impopen = [WM.getImage(id) for id in WM.getIDList()]
        for wind in impopen:
            imp2close = wind
            if "" + pat + "_R" in str(wind):
                imp2close.close()

    def hyperSC(num, istr):
        imp2 = impl[num]
        imp2 = HyperStackConverter.toHyperStack(imp2, 2, 1, 50, "xytcz",
                                                "Color")
        if (num - 2) < 10:
            numstr = "000" + str(num - 2)
        elif (num - 2) < 100:
            numstr = "00" + str(num - 2)
        elif (num - 2) > 99:
            numstr = "0" + str(num - 2)
        IJ.saveAs(
            imp2, "Tiff",
            "" + directory_save + title + "_R" + istr + "_Z" + numstr + ".tif")

    IJ.run("Close All", "")
    #Calculated variables
    range_rep = total / loops
    rangeDef = loops + 1

    IJ1.batchMode = True
    imp = IJ.run(
        "Bio-Formats", "open=" + directory_load +
        " color_mode=Default rois_import=[ROI manager] view=[Standard ImageJ] stack_order=Default use_virtual_stack series_2"
    )

    for i in range(loops):
        start = str(1 + i * range_rep)
        end = str(range_rep + i * range_rep)

        if i < 10:
            istr = "000" + str(i)
        elif i < 100:
            istr = "00" + str(i)
        elif i > 99:
            istr = "0" + str(i)

        impDup = IJ.run(
            imp, "Duplicate...", "title=" + title + "_R" + istr +
            " duplicate range=" + start + "-" + end + "")

        IJ.run(impDup, "Stack Splitter", "number=" + str(z_planes) + "")

        impl = [WM.getImage(id) for id in WM.getIDList()]

        a = [hyperSC(num, istr) for num in range(2, z_planes + 2)]
        pattern_closer(pat)
    IJ1.batchMode = False
Exemplo n.º 32
0
def run():

    print '======================'
    print 'running'

    if len(sys.argv) < 2:
        print 'bAlignCrop will align a stack.'
        print 'Usage: ./fiji'
        filePath = '/Users/cudmore/Desktop/X20150214_a156_010_ch1_c.tif'
        #return
    else:
        filePath = sys.argv[1]

    #check that file exists
    if not os.path.isfile(filePath):
        print 'Error: did not find file ', filePath
        return

    #open file
    print 'opening file:', filePath
    imp = IJ.openImage(filePath)

    if imp is None:
        print 'Error opening file'
        return

    imp.show()
    winTitle = imp.getTitle()

    transformationFile = filePath + '.txt'

    print 'running multistack reg'
    #IJ.run(imp, "MultiStackReg", "stack_1=X20150214_a156_010_ch1_c.tif action_1=Align file_1=[] stack_2=None action_2=Ignore file_2=[] transformation=Translation save");
    stackRegParams = 'stack_1=%s action_1=[Align] file_1=[%s] transformation=[Translation] save' % (
        winTitle, transformationFile)
    IJ.run('MultiStackReg', stackRegParams)
Exemplo n.º 33
0
def ana_particles(imp, minSize, maxSize, minCirc, bHeadless=True):
    """ana_particles(imp, minSize, maxSize, minCirc, bHeadless=True)
	Analyze particles using a watershed separation. If headless=True, we cannot
	redirect the intensity measurement to the original image because it is never
	displayed. If we display the original, we can and get the mean gray level. We
	may then compute the particle contrast from the measured Izero value for the image.
	No ability here to draw outlines on the original.
	"""
    strName = imp.getShortTitle()
    imp.setTitle("original")
    ret = imp.duplicate()
    ret.setTitle("work")
    IJ.run(ret, "Enhance Contrast", "saturated=0.35")
    IJ.run(ret, "8-bit", "")
    IJ.run(ret, "Threshold", "method=Default white")
    IJ.run(ret, "Watershed", "")
    rt = ResultsTable()
    # strSetMeas = "area mean modal min center perimeter bounding fit shape feret's redirect='original' decimal=3"
    # N.B. redirect will not work without a displayed image, so we cannot use a gray level image
    if bHeadless == True:
        strSetMeas = "area mean modal min center perimeter bounding fit shape feret's decimal=3"
    else:
        imp.show()
        strSetMeas = "area mean modal min center perimeter bounding fit shape feret's redirect='original' decimal=3"

    IJ.run("Set Measurements...", strSetMeas)
    # note this does not get passed directly to ParticleAnalyzer, so
    # I did this, saved everything and looked for the measurement value in ~/Library/Preferences/IJ_Prefs.txt
    # measurements=27355
    # meas = Measurements.AREA + Measurements.CIRCULARITY + Measurements.PERIMETER + Measurements.SHAPE_DESCRIPTORS
    # didn't work reliably
    meas = 27355
    pa = ParticleAnalyzer(0, meas, rt, minSize, maxSize, minCirc, 1.0)
    pa.analyze(ret)
    rt.createTableFromImage(ret.getProcessor())
    return [ret, rt]
Exemplo n.º 34
0
def Generate_segmented_image(imp, channel):
    imp_Threshold_1 = ExtractChannel(imp1, channel)
    imp_Threshold_1.setTitle(("Threshold" + "Channel" + str(channel)))
    imp_Threshold_1.show()
    IJ.run(imp_Threshold_1, "Median...", "radius=1")
    IJ.run(imp_Threshold_1, "Subtract Background...", "rolling=50")
    IJ.setAutoThreshold(imp_Threshold_1, "Triangle dark")
    #Prefs.blackBackground = True;
    IJ.run(imp_Threshold_1, "Convert to Mask", "")
    return imp_Threshold_1
 def preprocess(self):
     IJ.run(self.imp, "Gaussian Blur...", "sigma=" + str(gaussianVal))
     IJ.run(self.imp, "8-bit", "")
     imp_tmp = self.imp.duplicate()
     IJ.run(self.imp, "Gray Morphology",
            "radius=" + str(tophatSize) + " type=circle operator=open")
     ImageCalculator().run("Subtract", imp_tmp, self.imp)
     self.imp.changes = False
     self.imp.close()
     self.imp = imp_tmp
Exemplo n.º 36
0
def duplicateMaskInRoi(imp, roi, duplicateStack=False):
    imp.setRoi(roi)
    if duplicateStack:
    	WindowManager.setCurrentWindow(imp.getWindow())
        impMT1 = IJ.run("Duplicate...", "duplicate")
        impMT1 = WindowManager.getCurrentImage()
    else:
        impMT1 = imp.crop()
    IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel")
    IJ.run(impMT1, "Create Selection", "")
    roi1 = impMT1.getRoi()
    bounds = roi1.getBounds()
    if duplicateStack:
       	WindowManager.setCurrentWindow(impMT1.getWindow())
        IJ.run("Duplicate...", "duplicate")
        impMT = WindowManager.getCurrentImage()
        impMT1.close()
    else:
        impMT = impMT1.crop()
    IJ.run(impMT, "Canvas Size...", "width="+str(bounds.width+2)+" height="+str(bounds.height+2)+" position=Center zero")  
    return impMT, bounds
Exemplo n.º 37
0
def Generate_segmented(imp, channel, threshold_method, filtersize):
    imp_Threshold_1 = ExtractChannel(imp1, channel)
    imp_Threshold_1.setTitle(("Threshold" + "Channel" + str(channel)))
    imp_Threshold_1.show()
    IJ.run(imp_Threshold_1, "Median...", "radius=" + str(filtersize))
    IJ.run(imp_Threshold_1, "Subtract Background...", "rolling=50")
    IJ.setAutoThreshold(imp_Threshold_1, threshold_method + " dark")
    #Prefs.blackBackground = True;
    IJ.run(imp_Threshold_1, "Convert to Mask", "")
    return imp_Threshold_1
Exemplo n.º 38
0
def Generate_segmented_fixedThreshold(imp, channel, thres_min):
    imp_Threshold_1 = ExtractChannel(imp1, channel)
    imp_Threshold_1.setTitle(("Threshold" + "Channel" + str(channel)))
    imp_Threshold_1.show()
    IJ.run(imp_Threshold_1, "Median...", "radius=1")
    IJ.run(imp_Threshold_1, "Subtract Background...", "rolling=50")

    IJ.setThreshold(imp_Threshold_1, thres_min, 100000)
    #Prefs.blackBackground = True;
    IJ.run(imp_Threshold_1, "Convert to Mask", "")
    return imp_Threshold_1
def draw(i, j, array, color):
    if color == "white":
        antiColor = "black"
    else:
        antiColor = "white"
    path(i, j, array)
    setColor(color)
    IJ.run("Fill")
    setColor(antiColor)
    IJ.run("Draw")
    IJ.run("Select None")
Exemplo n.º 40
0
def extract_frame_process_roi(imp, frame, channel, process, background, roi, z_min, z_max):
  # 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");

  # return
  return imp_frame
Exemplo n.º 41
0
def prepros2(folder_in,folder_out):
	for filename in os.listdir(folder_in):
		imp =IJ.openImage(os.path.join(folder_in,filename))
		IJ.run(imp, "TransformJ Rotate", "z-angle=9 y-angle=-6 x-angle=0.0 interpolation=Linear background=0.0")
		imp = IJ.getImage()
		stack = imp.getImageStack()
		stackcropped  = stack.crop(118,98,70,1364,1304,904)
		imp = ImagePlus("2",stackcropped)
		output = "nrrd=["+folder_out+filename+"]"
		IJ.run(imp, "Nrrd ... ", output)
		imp.close()
		IJ.run("Collect Garbage", "")
Exemplo n.º 42
0
def process_folder(foldername, dataset="dataset.xml"):
    xmlname = foldername + "/" + dataset
    # this one is for a single well of projected images
    IJ.run(
        "Calculate pairwise shifts ...", "select=" + xmlname +
        " process_angle=[All angles] process_channel=[All channels] process_illumination=[All illuminations] process_tile=[All tiles] process_timepoint=[All Timepoints] method=[Phase Correlation] downsample_in_x=4 downsample_in_y=4"
    )
    IJ.run(
        "Filter pairwise shifts ...", "select=" + xmlname +
        " min_r=0.6 max_r=1 max_shift_in_x=0 max_shift_in_y=0 max_shift_in_z=0 max_displacement=0"
    )
    IJ.run(
        "Optimize globally and apply shifts ...", "select=" + xmlname +
        " process_angle=[All angles] process_channel=[All channels] process_illumination=[All illuminations] process_tile=[All tiles] process_timepoint=[All Timepoints] relative=2.500 absolute=3.500 global_optimization_strategy=[Two-Round using Metadata to align unconnected Tiles] fix_group_0-0"
    )
    IJ.run(
        "Fuse dataset ...", "select=" + xmlname +
        " process_angle=[All angles] process_channel=[All channels] process_illumination=[All illuminations] process_tile=[All tiles] process_timepoint=[All Timepoints] bounding_box=[Currently Selected Views] downsampling="
        + str(downsample) +
        " pixel_type=[16-bit unsigned integer] interpolation=[Linear Interpolation] image=[Precompute Image] interest_points_for_non_rigid=[-= Disable Non-Rigid =-] blend produce=[Each timepoint & channel] fused_image=[Save as (compressed) TIFF stacks] output_file_directory="
        + foldername + " filename_addition=_larged")
Exemplo n.º 43
0
def mkMask(imp, prePick, numRep, nStacks):
    file_name = imp.getTitle()
    IJ.selectWindow(file_name)
    IJ.setSlice(prePick)
    tempFileNames = []
    for pp in range(0, numRep):
        tempFileNames.append('temp' + str(pp))
        IJ.run(imp, "Duplicate...", "title=" + tempFileNames[pp])
        IJ.run("8-bit", "")
    cont_imgs = " ".join('image%d=%s' % (c + 1, w)
                         for c, w in enumerate(tempFileNames))
    IJ.run("Concatenate...", "title=tempStack " + cont_imgs)
    tempStack = IJ.getImage()
    IJ.run(
        tempStack, "Make Montage...", "columns=" + str(numRep / nStacks) +
        " rows=" + str(nStacks) + " scale=1 first=1 last=" + str(numRep) +
        " increment=1 border=1 font=12")
    m2_imp = IJ.getImage()
    m2_imp.setTitle("Mask")
    tempStack.close()
    return m2_imp
Exemplo n.º 44
0
def bunwarpjFIJI(ref, reg):
    directName = 'direct_transformation'
    inverseName = 'inverse_transformation'
    regStack = reg.getStack()
    sizeZ = reg.getStackSize()
    source = ImagePlus('source', ref.duplicate())
    for i in range(1, sizeZ):
        ip = regStack.getProcessor(i).duplicate()
        target = ImagePlus('target', ip)
        directFileName = os.path.join(saveDir.getAbsolutePath(),
                                      directName + '_' + str(i))
        inverseFileName = os.path.join(saveDir.getAbsolutePath(),
                                       inverseName + '_' + str(i))
        imp = IJ.run(
            source, "bUnwarpJ",
            "source_image=source target_image=target registration=Accurate image_subsample_factor=0 initial_deformation=[Very Coarse] final_deformation=Fine divergence_weight=0 curl_weight=0 landmark_weight=0 image_weight=1 consistency_weight=10 stop_threshold=0.01 save_transformations save_direct_transformation=["
            + directFileName + "] save_inverse_transformation=[" +
            inverseFileName + "]")
    return imp
def extract_frame_process_roi(imp, frame, channel, process, roi):
  # extract frame and channel 
  imp_frame = ImagePlus("", extract_frame(imp, frame, channel)).duplicate()
  # check for roi and crop
  if roi != None:
    #print roi.getBounds()
    imp_frame.setRoi(roi)
    IJ.run(imp_frame, "Crop", "")
  # process  
  if process:
    IJ.run(imp_frame, "Mean 3D...", "x=1 y=1 z=0");
    IJ.run(imp_frame, "Find Edges", "stack");
  # return
  return imp_frame
Exemplo n.º 46
0
def prepros1(folder_in,folder_out,firstFolder):
	for x in range(1):
		fnum = firstFolder+x
		folder = folder_in+str(fnum)
		output = "nrrd=["+folder_out+str(fnum)+".nrrd]"
		imp = FolderOpener.open(folder)
		stack = imp.getImageStack()
		stackcropped  = stack.crop(404,644,538,1604,1476,1200)
		imp = ImagePlus("1",stackcropped)
		IJ.run(imp, "Stack Contrast Adjustment", "is")
		imp = IJ.getImage()
		IJ.run(imp, "Nrrd ... ", output);
		imp.close()
		IJ.run("Collect Garbage", "")
Exemplo n.º 47
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
Exemplo n.º 48
0
def countobjects(imp, rt,
                 subtractBackground=False, watershed=False, dilate=False,
                 threshMethod="Otsu", physicalUnits=True,
                 minSize=0.00, maxSize=float("inf"),
                 minCirc=0.00, maxCirc=1.00):
    """Threshold and count objects in channel 'channelNumber'.
        This function splits an image in the separate channels, and counts the number of objects in the thresholded
        channel.

        Args:
            imp: An ImagePlus with 1 frame, 1 slice.

        Returns:
            A list of filepaths.
        """
    cal = imp.getCalibration()

    if subtractBackground:
        IJ.run(imp, "Subtract Background...", "rolling=50")
    IJ.setAutoThreshold(imp, "{} dark".format(threshMethod))
    IJ.run(imp, "Convert to Mask", "")
    if dilate:
        IJ.run(imp, "Dilate", "")
    if watershed:
        IJ.run(imp, "Watershed", "")
    if physicalUnits: # Convert physical units to pixels for the current calibration.
        minSize = cal.getRawX(math.sqrt(minSize)) ** 2
        maxSize = cal.getRawX(math.sqrt(maxSize)) ** 2

    pa = ParticleAnalyzer(
            ParticleAnalyzer.SHOW_OVERLAY_OUTLINES|ParticleAnalyzer.DISPLAY_SUMMARY, #int options
            Measurements.AREA|Measurements.SHAPE_DESCRIPTORS|Measurements.MEAN|Measurements.CENTROID|Measurements.LABELS, #int measurements
            rt, #ResultsTable
            minSize, #double
            maxSize, #double
            minCirc, #double
            maxCirc) #double
    pa.analyze(imp)
    return imp
Exemplo n.º 49
0
def drawSpot(point, diam):
    '''
    point: list of 2 integer values
    diam: float indicating the diameter of a cell in pixels
    Draws a filled circle on the selected channel of the current image at the indicated point
    '''
    xcenter = point[0]
    ycenter = point[1]
    # print("Drawing spot at "+str(xcenter)+", "+str(ycenter))
    IJ.run(
        imp2, "Specify...", "width=" + str(diam) + " height=" + str(diam) +
        " x=" + str(xcenter) + " y=" + str(ycenter) + " oval")
    IJ.run(imp2, "Fill", "slice")
    IJ.run(imp2, "Select None", "")
    return
Exemplo n.º 50
0
def process(inputpath, outputpath):

    imp = IJ.openImage(inputpath)
    IJ.run(
        imp, "Properties...",
        "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001"
    )

    IJ.setThreshold(imp, t1, 255)
    #imp.show()
    #WaitForUserDialog("Title", "Look at image").show()
    IJ.run(imp, "Convert to Mask", "")
    IJ.run(imp, "Watershed", "")

    # Counts and measures the area of particles and adds them to a table called areas. Also adds them to the ROI manager

    table = ResultsTable()
    roim = RoiManager(True)
    ParticleAnalyzer.setRoiManager(roim)
    pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA,
                          table, 50, 9999999999999999, 0.2, 1.0)
    pa.setHideOutputImage(True)
    pa.analyze(imp)

    imp.changes = False
    imp.close()

    areas = table.getColumn(0)

    summary = {}

    if areas:

        summary['Image'] = filename
        summary['Nuclei.count'] = len(areas)
        summary['Area.Covered'] = sum(areas)

    fieldnames = list(summary.keys())

    with open(outputpath, 'a') as csvfile:

        writer = csv.DictWriter(csvfile,
                                fieldnames=fieldnames,
                                extrasaction='ignore',
                                lineterminator='\n')
        if os.path.getsize(outputDirectory + "/" + outputname + ".csv") < 1:
            writer.writeheader()
        writer.writerow(summary)
def identifyRed(imp):
	# Clear ROI manager
	rm = RoiManager.getInstance()
	if rm is not None:
		rm.reset()
	
	# Get hue from HSB stack
	impHue = ProcessHSB.getHue(imp)
	width = impHue.width
	height = impHue.height
	
	# Get processor for hue
	ipHue = impHue.getProcessor().convertToFloat()
	huePixels = ipHue.getPixels()

	# Bring brightness into the equation
	impBrightness = ProcessHSB.getBrightness(imp)
	IJ.run(impBrightness, "Auto Threshold", "method=Default white")
	#IJ.run(impBrightness, "Analyze Particles...", "size=10000-Infinity circularity=0.00-1.00 show=Masks in_situ")
	
	# If hue < 30 and hue > 225, True
	newPixels = map(ProcessHSB.redHue, huePixels)
	
	# Pause: Do this later
	ipNew = FloatProcessor(width, height, newPixels)
	impRed = ImagePlus("RedHue", ipNew)
	IJ.run(impRed, "8-bit", "") # convert to 8-bit
	
	# Logic AND pictures together
	ic = ImageCalculator()
	impRedMask = ic.run("AND create", impRed, impBrightness)
	IJ.run(impRedMask, "8-bit", "") # convert to 8-bit
	IJ.run(impRedMask, "Analyze Particles...", "size=10000-Infinity circularity=0.00-1.00 show=Masks add in_situ") # "add" right after "include" to include roi to manager
	
	impHue.close()
	impBrightness.close()
	impRed.close()
	impRedMask.close()
Exemplo n.º 52
0
def rescale(folder_in, folder_out):
    """Function to rescale 3D NRRD image series"""
    for filename in os.listdir(folder_in):
        imp = IJ.openImage(os.path.join(folder_in, filename))
        img = ImgLib.wrap(imp)
        img2 = Resample(img, 0.25)
        imp = ImgLib.wrap(img2)
        output = "nrrd=[" + folder_out + filename + "]"
        IJ.run(imp, "Nrrd ... ", output)
        imp = None
        img = None
        img2 = None
        gc.collect()
        time.sleep(15)
        gc.collect()
        IJ.run("Collect Garbage", "")
        IJ.run("Collect Garbage", "")
def extract_frame_process_roi(imp, frame, channel, process, roi, roiz):
  
  if( imp.getStack().getClass().getName() == "ct.vss.VirtualStackOfStacks"):
    imp_frame = extract_cropped_frame_from_VirtualStackOfStacks(imp, frame-1, channel, roi, roiz)
  else:
    # extract frame and channel 
    imp_frame = ImagePlus("", extract_frame(imp, frame, channel, roiz)).duplicate()
    # check for roi and crop
    if roi != None:
      #print roi.getBounds()
      imp_frame.setRoi(roi)
      IJ.run(imp_frame, "Crop", "")
  # process  
  if process:
    IJ.run(imp_frame, "Mean 3D...", "x=1 y=1 z=0");
    IJ.run(imp_frame, "Find Edges", "stack");
  # return
  return imp_frame
Exemplo n.º 54
0
def pairwise_stitching(tiff_1, tiff_2, temp_dir):
	IJ.open(tiff_1)
	tiff_1_title = os.path.basename(tiff_1)
	IJ.open(tiff_2)
	tiff_2_title = os.path.basename(tiff_2)
	new_fused_image = "" + tiff_1_title.split("_")[0] + "-" + tiff_2_title.split("_")[0] + "_.tiff"

	IJ.run("Pairwise stitching", "first_image=" + tiff_1_title +  " second_image=" + tiff_2_title + " fusion_method=[Linear Blending] fused_image=" + new_fused_image + " check_peaks=1 compute_overlap x=0.0000 y=0.0000 z=0.0000 registration_channel_image_1=[Average all channels] registration_channel_image_2=[Average all channels]")
	IJ.selectWindow(tiff_1_title)
	IJ.run("Close")
	os.remove(tiff_1)
	IJ.selectWindow(tiff_2_title)
	IJ.run("Close")
	os.remove(tiff_2)
	IJ.selectWindow(new_fused_image)
	imp = IJ.getImage()
	IJ.saveAsTiff(imp, os.path.join(temp_dir, new_fused_image))
	imp.close()
Exemplo n.º 55
0
def setThreshold(img, outDir, out_name, thresholdPref):
    if thresholdPref == thresholdChoices[2]:
        img2 = img.duplicate()
        m, f = getThresholdOptions(thresholdChoices[0])
        IJ.run(img, "Auto Threshold", "method=" + m)
        out_file = os.path.join(outDir, f, out_name)
        checkDirs(os.path.join(outDir, f))
        saveImage(img, out_file)
        m, f = getThresholdOptions(thresholdChoices[1])
        IJ.run(img2, "Auto Threshold", "method=" + m)
        out_file = os.path.join(outDir, f, out_name)
        checkDirs(os.path.join(outDir, f))
        saveImage(img2, out_file)
    else:
        m, f = getThresholdOptions(thresholdPref)
        IJ.run(img, "Auto Threshold", "method=" + m)
        out_file = os.path.join(outDir, out_name)
        saveImage(img, out_file)
def identifyTunicate(imp):
    # Clear ROI manager
    rm = RoiManager.getInstance()
    if rm is not None:
        rm.reset()

    # Get hue from HSB stack
    impHue = ProcessHSB.getHue(imp)
    width = impHue.width
    height = impHue.height

    # Get processor
    ipHue = impHue.getProcessor().convertToFloat()
    huePixels = ipHue.getPixels()

    # Get macro hue because it is the same color
    newPixels = map(ProcessHSB.macroHue, huePixels)
    ipNew = FloatProcessor(width, height, newPixels)
    impTunicate = ImagePlus("MacroHue", ipNew)

    # Bring brightness into the equation
    impBrightness = ProcessHSB.getBrightness(imp)
    IJ.run(impBrightness, "Auto Threshold", "method=MaxEntropy white")
    #IJ.run(impBrightness, "Analyze Particles...", "size=10000-Infinity circularity=0.10-1.00 show=Masks in_situ") # "add" right after "include" to include roi to manager

    # Logic AND pictures together
    ic = ImageCalculator()
    impTunicateMask = ic.run("AND create", impTunicate, impBrightness)
    IJ.run(impTunicateMask, "8-bit", "")  # convert to 8-bit
    impTunicate.close()
    impBrightness.close()
    IJ.run(impTunicateMask, "Analyze Particles...",
           "size=10000-Infinity circularity=0.50-1.00 show=Masks add in_situ"
           )  # "add" right after "include" to include roi to manager

    impTunicateMask.close()
    #imp.show()
    #rm = RoiManager.getInstance()
    #return rm


#testImp = IJ.getImage()
#result = identifyTunicate(testImp)
#print type(result)
Exemplo n.º 57
0
def processImage():
	imp = IJ.getImage()
	image_name = imp.title
	image_dir = IJ.getDirectory("image")
	IJ.run(imp, "Measure", "")
	marker_dir = os.path.join(image_dir, "markers" + os.path.sep)
	processed_marker_dir = os.path.join(image_dir, "processed_markers" + os.path.sep)
	makeDir(marker_dir, processed_marker_dir)
	csv_file = saveResults(imp, marker_dir)
	imp.deleteRoi()

	tiff_save_name = os.path.join(processed_marker_dir, image_name)
	IJ.saveAsTiff(imp, tiff_save_name)
	remove_duplicate_counter(csv_file, processed_marker_dir)
#	file_dir = os.path.dirname(os.path.abspath(__file__))
	IJ.run(imp, "setRoi ", "");
	IJ.run("Save")
	imp.close()
	return image_dir
Exemplo n.º 58
0
def identifyRed(imp):
    # Clear ROI manager
    rm = RoiManager.getInstance()
    if rm is not None:
        rm.reset()

    # set results table


#	rt = ResultsTable.getResultsTable()

# Get hue from HSB stack
    impHue = ProcessHSB.getHue(imp)
    width = impHue.width
    height = impHue.height

    # Get processor for hue
    ipHue = impHue.getProcessor().convertToFloat()
    huePixels = ipHue.getPixels()

    # Bring brightness into the equation
    impBrightness = ProcessHSB.getBrightness(imp)
    IJ.run(impBrightness, "Auto Threshold", "method=MaxEntropy white")
    IJ.run(impBrightness, "Analyze Particles...",
           "size=10000-Infinity circularity=0.00-1.00 show=Masks in_situ")

    # Get processor for brightness
    ipBrightness = impBrightness.getProcessor().convertToFloat()
    brightnessPixels = ipBrightness.getPixels()

    # Do the thing now
    newPixels = map(ProcessHSB.redHueBackground, brightnessPixels, huePixels)

    # If hue < 30 and hue > 225, True
    #newNewPixels = map(ProcessHSB.redHue, newPixels)

    # Pause: Do this later
    ipNew = FloatProcessor(width, height, newPixels)
    impRed = ImagePlus("RedHue", ipNew)
    IJ.run(impRed, "8-bit", "")  # convert to 8-bit
    #IJ.run(imp, "Options...", "iterations=20 count=1 black do=[Fill Holes]");
    impRed.show()
Exemplo n.º 59
0
def tag(imp, roiMan, roiTotal, color):
	print "Inside of UrchinTag..."
	print "imp " + str(imp)
	# Set the color and line options for tagging
	IJ.run(imp, "Line Width...", "line=10")
	IJ.run("Colors...", "foreground=" + color + " background=black selection=magenta")

	if roiMan is not None:
		# Iterate through the ROIs
		for roi in xrange(roiTotal):
			# Select the ROI
			roiMan.select(roi)
			selectRoi = roiMan.getRoi(roi)
			
			# Tag the ROI
			IJ.run(imp, "Draw", "slice")
		# end for loop
		return 1
	else:
		return 0
Exemplo n.º 60
0
def process(filename, output_path):
    # if multiple channels
    #IJ.run("Make Composite");
    IJ.run("Z Project...", "projection=[Max Intensity]")
    # the number of channels is one (orig image) less than the number of images opened

    # add scale bar to image
    IJ.run(
        "Scale Bar...",
        "width=50 height=20 font=18 color=White background=None location=[Lower Right] hide overlay"
    )
    # save scale bar to stack
    IJ.run("Flatten")

    IJ.saveAs("Tiff", os.path.join(output_path, 'maxint_w_scale' + filename))
    # close all the images
    num_channels = WM.getImageCount()
    for i in range(0, num_channels):
        curr_img = WM.getCurrentImage()
        curr_img.close()
    return