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)
def bPrintLog(text, indent=0):
	msgStr = ''
	for i in (range(indent)):
		msgStr += '    '
		print '   ',
	print text #to command line
	IJ.log(msgStr + text)
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 DirList(baseDir):
	r = ImageReader()
	imgStats = {}
	for root, dirs, files in os.walk(str(baseDir)):
		for f1 in files:
			if f1.endswith(".jpg") or f1.endswith(".jpe") or f1.endswith(".jpeg"):
				id = root + "/" +  f1
				r.setId(id)
				if r is None:
					print "Couldn\'t open image from file:", id
					continue
				w = r.getSizeX()
				h = r.getSizeY()
				imgStats[str(w) + "_" + str(h)] = imgStats.get(str(w) + "_" + str(h), 0)+1
				IJ.log("Found image: " + str(id))
				#counter += 1
	r.close()
	#print summary
	summary = ''
	for k, v in imgStats.iteritems():
		dim = k.split("_")
		ratio = float(dim[0])/float(dim[1])
		IJ.log("Found " + str(v) + " images of dimension " + str(dim[0]) + "x" + str(dim[1]) + " apect ratio " + str(round(ratio, 2)))
		summary = summary + "\nFound " + str(v) + " images of dimension " + str(dim[0]) + "x" + str(dim[1]) + " apect ratio " + str(round(ratio, 2))
	return summary
Exemple #5
0
def getSettings(img):
    """This function assesses (by returning a boolean value) if the filter can
    be applied to the image passed as argument. Will ask the user for new values
    if current parameters are undefined."""
    global xradius, yradius, zradius
    canProceed = True

    if not img:
        IJ.error("No images open.")
        canProceed = False

    # Get new values if at least one of the parameters is 'null'
    if canProceed and None in (xradius, yradius, zradius):
        gd = GenericDialog("Median Filter")
        gd.addNumericField("X radius:", 2.0, 1)
        gd.addNumericField("Y radius:", 2.0, 1)
        gd.addNumericField("Z radius:", 2.0, 1)
        gd.showDialog()
        if gd.wasCanceled():
            canProceed = False
        else:
            xradius = gd.getNextNumber()
            yradius = gd.getNextNumber()
            zradius = gd.getNextNumber()
 
    return canProceed
def Dialog(imp):
	dpi = 300
	# a4 width in inches
	defaultWidth = 11.69
	defaultHeight = defaultWidth/ratio
	defaultAspectRatio = 1.41

	if imp:
		gd = GenericDialogPlus("Cover Maker")
		gd.addMessage("Input Options")
		gd.addFileField("Select image database", "", 20)
		gd.addMessage("Cover Maker Options")
		gd.addNumericField("tile width", 12, 0)
		gd.addNumericField("tile height", 9, 0)

		gd.showDialog()

		if gd.wasCanceled():
			print "User canceled dialog!"
			return
		databasepath = gd.getNextString()
		tilewidth = gd.getNextNumber()
		tileheight = gd.getNextNumber()

		print 'path:', databasepath
		return databasepath, imp.getWidth(), imp.getHeight(), int(tilewidth), int(tileheight)
	else:
		IJ.showMessage( "You should have at least one image open." )
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
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
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 
Exemple #10
0
		def resetpressed(event):
			self.__ranges.clear()
			self.__image=IJ.getImage()
			rm = RoiManager.getInstance()
			if (rm==None): rm = RoiManager()
			rm.runCommand("reset")
			self.__image.killRoi()
			IJ.setAutoThreshold(self.__image, "MaxEntropy")
			rt=ResultsTable()
			pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00)
			pa.analyze(self.__image)
			self.__roisArray=[]
			self.__roisArray=rm.getRoisAsArray()
			#rm.runCommand("Show All")
			#rm.runCommand("Select All")
			#rm.runCommand("Set Color", "blue")
			
			IJ.resetThreshold(self.__image)
			
			keys=self.__slidersDict.keys()
			for k in keys:
				if k.endswith("min"): 
					self.__slidersDict[k].setValue(0)
					self.__slidersDict[k].repaint()
				else:
					self.__slidersDict[k].setValue(self.__slidersDict[k].getMaximum())
					self.__slidersDict[k].repaint()
def test_maskArea():
	""" Test of the function maskArea """

	# 8bit test
	imp = IJ.openImage(filePathTest.getAbsolutePath())
	ip = imp.getProcessor().duplicate()
	impMask = mask( ip, 1, ip.maxValue() )
	impMask.show()
	outMaskArea = maskArea(impMask.getProcessor())
	outArea = area(impMask.getProcessor())
	print(outMaskArea)
	print(outArea)
	print(outMaskArea/outArea)

	# 16bit test
	imp = IJ.openImage(filePath.getAbsolutePath())
	stack = imp.getStack()
	ip = stack.getProcessor(1).duplicate()
	sizeZ = imp.getStackSize()
	impMask = mask( ip, 1, ip.maxValue() )
	impMask.show()
	outMaskArea = maskArea( impMask.getProcessor() )
	outArea = area( impMask.getProcessor() )
	print(outMaskArea)
	print(outArea)
	print(outMaskArea/outArea)
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()
def translate_single_stack_using_imglib2(imp, dx, dy, dz):
  # wrap into a float imglib2 and translate
  #   conversion into float is necessary due to "overflow of n-linear interpolation due to accuracy limits of unsigned bytes"
  #   see: https://github.com/fiji/fiji/issues/136#issuecomment-173831951
  img = ImagePlusImgs.from(imp.duplicate())
  extended = Views.extendBorder(img)
  converted = Converters.convert(extended, RealFloatSamplerConverter())
  interpolant = Views.interpolate(converted, NLinearInterpolatorFactory())
  
  # translate
  if imp.getNDimensions()==3:
    transformed = RealViews.affine(interpolant, Translation3D(dx, dy, dz))
  elif imp.getNDimensions()==2:
    transformed = RealViews.affine(interpolant, Translation2D(dx, dy))
  else:
    IJ.log("Can only work on 2D or 3D stacks")
    return None
  
  cropped = Views.interval(transformed, img)
  # wrap back into bit depth of input image and return
  bd = imp.getBitDepth()
  if bd==8:
    return(ImageJFunctions.wrapUnsignedByte(cropped,"imglib2"))
  elif bd == 16:
    return(ImageJFunctions.wrapUnsignedShort(cropped,"imglib2"))
  elif bd == 32:
    return(ImageJFunctions.wrapFloat(cropped,"imglib2"))
  else:
    return None    
Exemple #14
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 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")	
Exemple #16
0
	if len(position) > 2:
		IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_zpos+" value=["+str(position[2])+"] windows=REG_SZ")

def saveOutputImg(impOut, filepath, diranalyzed):
	if impOut is not None:
			analyzeDir = os.path.join(os.path.dirname(filepath), diranalyzed)
			if not os.path.isdir(analyzeDir):
Exemple #17
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)
def run():
  srcDir = DirectoryChooser("Choose!").getDirectory()
  if not srcDir:
    # user canceled dialog
    return
  # Assumes all files have the same size
  filepaths = []
  pattern = re.compile('ch1(.*)_(.*)transformed.mha')
  for root, directories, filenames in os.walk(srcDir):
    for filename in filenames:
      # Skip non-TIFF files
      match = re.search(pattern, filename)
      if (match == None) or (match.group(1) == None):
	    continue
      print(filename)
      path = os.path.join(root, filename)
      filepaths.append(path)
      # Upon finding the first image, initialize the VirtualStack
  
  vs = None
  sorted_filepaths = sorted(filepaths)
  
  for f in sorted(filepaths):
      IJ.openImage(f)
      print(f.split('\\')[-1])
      imp = IJ.getImage()  
      if vs is None:
        vs = ImageStack(imp.width, imp.height)
      # Add a slice, relative to the srcDir
      vs.addSlice(f.split('\\')[-1],imp.getProcessor())
      imp.hide()

  ImagePlus("Stack from subdirectories", vs).show()
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()
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()
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]
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
def run():
  projects = Project.getProjects()
  if projects is None or projects.isEmpty():
    IJ.log('No project open!')
    return
  ls = projects.get(0).getRootLayerSet()
  trees = ls.getZDisplayables(Treeline)
  trees.addAll(ls.getZDisplayables(AreaTree))
  if trees.isEmpty():
    IJ.log('No trees to process!')
    return
  dc = DirectoryChooser('Target folder')
  targetFolder = dc.getDirectory()
  if targetFolder is None:
    return # user canceled
  if targetFolder[len(targetFolder) -1] != '/':
    targetFolder += '/'
  fdir = File(targetFolder)
  for f in fdir.listFiles():
    if f.isHidden():
      continue
    yn = YesNoCancelDialog(IJ.getInstance(), "WARNING", "Folder not empty! Continue?")
    if yn.yesPressed():
      break
    else:
      return
  process(trees, targetFolder)
Exemple #24
0
def segmentNuc(impc2):
	impdup = Duplicator().run(impc2)
	IJ.run(impdup, "8-bit", "")
	IJ.run(impdup, "Gaussian Blur...", "sigma=1.5 stack")
#	AutoThresholder().getThreshold(AutoThresholder.Method.valuOf('Otsu'), int[] histogram) 
	IJ.setAutoThreshold(impdup, "Otsu dark")
	IJ.run(impdup, "Convert to Mask", "stack")
 	#IJ.setAutoThreshold(impdup, "Otsu dark")
	#opt = PA.SHOW_MASKS + PA.SHOW_RESULTS + PA.EXCLUDE_EDGE_PARTICLES + PA.INCLUDE_HOLES # option for stack missing
	opt = PA.SHOW_MASKS + PA.EXCLUDE_EDGE_PARTICLES + PA.INCLUDE_HOLES # option for stack missing
	##area mean centroid bounding integrated stack redirect=None decimal=4
	meas = Meas.AREA + Meas.MEAN + Meas.CENTROID + Meas.RECT + Meas.INTEGRATED_DENSITY + Meas.STACK_POSITION
	rt = ResultsTable().getResultsTable()
	pa = PA(opt, meas, rt, 10.0, 300000.0, 0, 1.0)
	PA.processStack = True
	pa.setHideOutputImage(True)
	##run("Analyze Particles...", "size=800-Infinity circularity=0.00-1.00 pixel show=Masks display exclude include stack");
	outstack = ImageStack(impdup.getWidth(), impdup.getHeight())
	for i in range(1,impdup.getStackSize()+1):
		impdup.setSlice(i)
		pa.analyze(impdup)
		impbin = pa.getOutputImage()
		outstack.addSlice(impbin.getProcessor())
 	impbin = ImagePlus("out", outstack)
	IJ.run(impbin, "Invert LUT", "")
	#IJ.run(impbin, "Fill Holes", "stack")
	return impbin, rt
Exemple #25
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;
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)
Exemple #27
0
 def saveMask(self, maskdir):
     imp = self.mask
     imp.getProcessor().invert()
     filebasename = os.path.basename(self.filename)
     maskfilename = os.path.join(maskdir, "mask_%s" % filebasename)
     IJ.save(imp, maskfilename)
     IJ.log("Mask image: %s\n" % maskfilename)
def run():
    global pmWin
    global imgData
    helpText = "This is Point Marker, " + \
               "a program for marking points in images.\n\n" + \
               ">> Press OK to Select a file for storing points infomation.\n"+\
               ">> TIF-Images within the same directory will be auto-loaded."
    MessageDialog(IJ.getInstance(),"Point Marker Guide", helpText)

    fileChooser = OpenDialog("Point Marker: Choose working directory and file")
    outfilePath = fileChooser.getPath()
    imgDir = fileChooser.getDirectory()
    if not imgDir:  return
    imgPaths = []
    if imgDir:
        for root, directories, filenames in os.walk(imgDir):
            for filename in filenames:
                if not filename.endswith(".tif"):
                    continue
                imgPaths.append(os.path.join(root, filename))

    pointsTable1 = readPoints(outfilePath)

    imgData = PointMarkerData(imgPaths, outfilePath, pointsTable1)

    IJ.setTool("multipoint")
    PointRoi.setDefaultSize(3)

    pmWin = PointMarkerWin(imgData)
    pmWin.win.setLocation(IJ.getInstance().getLocation())
    prepareNewImage(imgData)
Exemple #29
0
 def saveImp(self, filePath, imp):
     cDir = path.split(filePath)[0]
     if not path.exists(cDir):
         print "Making directory " + cDir
         mkdir(cDir)
     IJ.saveAs(imp, ".tiff", filePath)
     print "Saved as " + filePath + ".tiff"
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())
 def translate_(self, dx, dy):
     IJ.runMacro("roiManager(\"translate\", " + str(dx) + ", " + str(dy) +
                 ")")
     self.center = (self.center[0] + dx, self.center[1] + dy)

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


imp = IJ.getImage()

outimp = Zproj(imp, "SUM", imp.getZ(), 10)
outimp.show()

#print "dim:", imp.getDimensions()
#print "title:", imp.title
#print "current z", imp.getZ() # get current z
#print "current index",imp.getCurrentSlice()
#
#print "position", imp.convertIndexToPosition(imp.getCurrentSlice())
Exemple #33
0
# Fiji Jython interpreter implements Python 2.5 which does not
# provide support for argparse.
error_log = sys.argv[-10]
input = sys.argv[-9]
threshold_min = float(sys.argv[-8])
threshold_max = float(sys.argv[-7])
method = sys.argv[-6]
display = sys.argv[-5]
black_background = jython_utils.asbool(sys.argv[-4])
# TODO: this is not being used.
stack_histogram = jython_utils.asbool(sys.argv[-3])
tmp_output_path = sys.argv[-2]
output_datatype = sys.argv[-1]

# Open the input image file.
input_image_plus = IJ.openImage(input)

# Create a copy of the image.
input_image_plus_copy = input_image_plus.duplicate()
image_processor_copy = input_image_plus_copy.getProcessor()

try:
    # Convert image to binary if necessary.
    if not image_processor_copy.isBinary():
        # Convert the image to binary grayscale.
        IJ.run(input_image_plus_copy, "Make Binary",
               "iterations=1 count=1 edm=Overwrite do=Nothing")
    # Set the options.
    if black_background:
        method_str = "%s dark" % method
    else:
Exemple #34
0
from ij import IJ, ImageJ

ImageJ()
IJ.run("MRI Stack (528K)")
IJ.runMacro("setVoxelSize(1, 1, 4, 'mm')")
IJ.run("3D Viewer",
       "display=Volume color=None threshold=0 resampling=1 red green blue")
def import_and_straighten(imgDir):
    """
    Core function. Opens images in given directory in series and calls a straightening function.
    Thresholds using weka if stddev of pixel intensities is too high (bright field), otherwise uses
    histogram based segmentation.
    """
    targetWidth = 800  #adjustable
    make_directory(imgDir)
    index = "000000000"
    filename = imgDir + "/img_" + index + "__000.tif"
    if path.exists(filename):
        weka = Weka_segmentor(IJ.openImage(filename))
    while path.exists(filename):
        IJ.run("Set Measurements...",
               "mean standard min center redirect=None decimal=3")
        IJ.run("Clear Results")
        imp = IJ.openImage(filename)
        imp.show()
        IJ.run("Rotate 90 Degrees Left")
        IJ.run("Measure")
        table = RT.getResultsTable()
        stddev = RT.getValue(table, "StdDev", 0)

        if stddev < 20:
            segmented = weka.getThreshold(imp)
            segmented.show()
            IJ.run("8-bit")
            IJ.run("Invert")
            imp.close()
            imp = segmented

        else:
            IJ.run(imp, "Auto Threshold", "method=Li white")  #threshold

        imp = preProcess_(imp)

        #straighten_roi_rotation()
        coords = run_straighten()

        newImp = IJ.getImage()
        """
        fs = FileSaver(newImp)
        fs.saveAsTiff(imgDir + "/straightened" + "/img_" + index + "__000-straight.tif")
        """

        IJ.run("Image Padder",
               "pad_right=" + str(targetWidth - newImp.getWidth()))
        paddedImp = IJ.getImage()
        fs = FileSaver(paddedImp)
        fs.saveAsTiff(imgDir + "/binary" + "/img_" + index +
                      "__000-padded.tif")

        IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}")

        #use same centerline for original greyscale image
        imp = IJ.openImage(filename)
        imp.show()
        IJ.run("Rotate 90 Degrees Left")
        IJ.run("8-bit")
        IJ.runMacro("makeLine(" + coords + ")")
        IJ.run("Straighten...", "line = 80")
        newImp = IJ.getImage()
        IJ.run("Image Padder",
               "pad_right=" + str(targetWidth - newImp.getWidth()))
        paddedImp = IJ.getImage()
        IJ.run("8-bit")
        fs = FileSaver(paddedImp)
        fs.saveAsTiff(imgDir + "/greyscale" + "/img_" + index +
                      "__000-padded.tif")
        IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}")

        index = to_9_Digits(str(int(index) + 1))
        filename = filename = imgDir + "/img_" + index + "__000.tif"
 def unrotateRoot_(self):  # dTheta):
     IJ.runMacro("run(\"Rotate...\",\"  angle=" + str((-1) * self.dTheta) +
                 "\");")
 def rotate_(self):  # dTheta):
     IJ.runMacro("run(\"Rotate...\",\"  angle=" + str(self.dTheta) + "\");")
def straighten_with_centerpoints(roiWindowsize=4):
    """ Failed straightening method utilizing ROI rotation. """
    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 = []

    imp = IJ.getImage().getProcessor()

    for i in range(0, 512, roiWindowsize):
        topLeft = find_first_pixel(i, imp)
        bottomLeft = find_last_pixel(i, imp)
        #print "topLeft:", topLeft, "bottomLeft:", bottomLeft
        #sleep(.2)

        if not topLeft == None and not bottomLeft == None:
            xvals.append(i)
            yvals.append((topLeft[1] + bottomLeft[1]) / 2)

        topRight = find_first_pixel(i + roiWindowsize, imp)
        bottomRight = find_last_pixel(i + roiWindowsize, imp)

        if not topRight == None and not bottomRight == None:
            xvals.append(i + roiWindowsize)
            yvals.append((topRight[1] + bottomRight[1]) / 2)

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

    IJ.runMacro("makeLine(" + coords + ")")
    IJ.run("Straighten...", "line = 80")
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 measure_growth(imgDir, filename="Fiji_Growth.txt"):
    """ Collects measurement data in pixels and writes to a file. Uses straightened binary images"""
    f = open(imgDir + filename, 'w')
    f.write("Img number\tEnd point (pixels)\n")
    IJ.run("Set Measurements...",
           "area mean min center redirect=None decimal=3")
    index = "000000000"
    filename = imgDir + "/binary" + "/img_" + index + "__000-padded.tif"
    while path.exists(filename):
        imp = IJ.openImage(filename)
        imp.show()
        IJ.run("Clear Results")
        for i in xrange(800):  #hard coded to target length for now
            IJ.makeRectangle(i, 0, 1, 80)
            IJ.run("Measure")
            table = RT.getResultsTable()
            #print "i:", i, "counter:", table.getCounter()
            maxi = RT.getValue(table, "Max", i)
            if maxi == 0:
                f.write(str(int(index)) + "\t" + str(i) + "\n")
                break

        IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}")
        index = to_9_Digits(str(int(index) + 1))
        filename = imgDir + "/padded" + "/img_" + index + "__000-padded.tif"
    f.close()
from loci.formats import ImageReader, MetadataTools
from ij.measure import ResultsTable


startTime = [time.strftime("%a, %d %b %Y %H:%M:%S"), time.time()]
imageCount=0
## The following lines are the settings for particle size and circularity, change if needed
particle_size_min = 150
particle_size_max = "Infinity"
particle_circ_min = 0.00
particle_circ_max = 1.00

particle_size = str(particle_size_min) + "-" + str(particle_size_max)
particle_circ = str(particle_circ_min) + "-" + str(particle_circ_max)

in_dir = IJ.getDirectory("Choose Directory Containing Input Files (ND2)")
out_dir = IJ.getDirectory("Choose Directory For Output")

def saveImage(img, out_file):
	FileSaver(img).saveAsTiff(out_file)

def maxZprojection(stackimp):
	zp = ZProjector(stackimp)
	zp.setMethod(ZProjector.MAX_METHOD)
	zp.doProjection()
	zpimp = zp.getProjection()
	return zpimp
	
for root, dirs, files in os.walk(in_dir):
	for file in files:
		if file.endswith(".nd2"):
def straighten_roi_rotation(roiWindowsize=8):
    """ Root straightening function that rotates ROI to follow root slope.
    Does not work properly.
    """
    IJ.run("Set Measurements...",
           "mean standard min center redirect=None decimal=3")
    IJ.runMacro("//setTool(\"freeline\");")
    IJ.run("Line Width...", "line=80")
    #numPoints = 512/roiWindowsize
    xvals = []
    yvals = []
    maxvals = []
    counter = 0
    maxIters = 800 / roiWindowsize
    minIters = 10

    imp = IJ.getImage().getProcessor()

    rm = RoiManager()
    if find_first_pixel(0, imp) == None or find_last_pixel(0, imp)[1] == None:
        return
    y = (find_first_pixel(0, imp)[1] + find_last_pixel(0, imp)[1]) / 2
    roi = roiWindow_(imp,
                     center=(roiWindowsize / 2, y),
                     width=roiWindowsize,
                     height=512)
    xvals.append(roiWindowsize / 2)
    yvals.append(y)
    maxvals.append(0)
    roi.findTilt_()
    i = 0
    while i < maxIters and roi.containsRoot_():
        roi.advance_(roiWindowsize)
        IJ.run("Clear Results")
        IJ.run("Measure")
        table = RT.getResultsTable()

        x = RT.getValue(table, "XM", 0)
        y = RT.getValue(table, "YM", 0)
        if imp.getPixel(int(x), int(y)) != 0:
            xvals.append(x)
            yvals.append(y)
            maxvals.append((RT.getValue(table, "Max", 0)))

    #roi.advance_(roiWindowsize)
        print "here"
        roi.unrotateRoot_()
        IJ.run("Clear Results")
        IJ.run("Measure")
        roi.restoreCenter_(RT.getValue(table, "XM", 0),
                           RT.getValue(table, "YM", 0))
        #exit(1)
        sleep(.5)
        roi.findTilt_()
        i += 1
    coords = ""
    for i in range(len(xvals) - 1):
        coords += str(xvals[i]) + ", " + str(yvals[i]) + ", "
    coords += str(xvals[len(xvals) - 1]) + ", " + str(yvals[len(xvals) - 1])

    IJ.runMacro("makeLine(" + coords + ")")
    IJ.run("Straighten...", "line = 80")
from ij import IJ

hMin = 500
thresh = 500
peakFlooding = 80
IJ.run(
    "HWatershed", "impin=2DEmbryoSection_Mette.tif hmin=" + str(hMin) +
    " thresh=" + str(thresh) + " peakflooding=" + str(peakFlooding))
Exemple #44
0
@String(label="Image Directory", style="") img_dir

"""
Rewrote in python from:
https://forum.image.sc/t/create-tif-with-4-channels-per-pixel/26457/8

The only thing I can't figure out how to do is apply
a different LUT to each slice in a stack...

"""

from ij import IJ, ImagePlus, ImageStack

# start clean
IJ.run("Close All")

# returned is an array of ImagePlus, in many cases just one imp.
src = img_dir + "/VS_demo.tif"
stack = IJ.openImage(src)
stack.show()

ip_red = stack.getProcessor(1)
imp_red = ImagePlus('red', ip_red)
imp_red.show()
imp_r = imp_red.duplicate()
# IJ.saveAs(imp_red, "Tiff", img_dir + "/R.tif")

ip_green = stack.getProcessor(2)
imp_green = ImagePlus('green', ip_green)
imp_green.show()
imp_g = imp_green.duplicate()
    def run(self):
        # make output folder
        if not os.path.isdir(self.dstFolder):
            os.makedirs(self.dstFolder)

        tifFileName = os.path.split(self.tifFilePath)[1]
        isCh1 = self.tifFilePath.endswith('_ch1.tif')
        isCh2 = self.tifFilePath.endswith('_ch2.tif')

        doThisFilePath = ''
        if self.alignmentChannel == 1 and isCh1:
            doThisFilePath = self.tifFilePath
        elif self.alignmentChannel == 2 and isCh2:
            doThisFilePath = self.tifFilePath

        if (doThisFilePath):
            ###
            ###
            bPrintLog('Loading file: ' + doThisFilePath, 3)
            imp = IJ.openImage(doThisFilePath)

            if imp is None:
                print "ERROR: could not open image from file:", doThisFilePath
                return -1

            d = imp.getDimensions(
            )  # Returns the dimensions of this image (width, height, nChannels, nSlices, nFrames) as a 5 element int array.
            logStr = 'dimensions are w:' + str(d[0]) + ' h:' + str(
                d[1]) + ' channels:' + str(d[2]) + ' slices:' + str(
                    d[3]) + ' frames:' + str(d[4])
            bPrintLog(logStr, 3)
            '''
			this is not designed to handle stacks that have frames !!!
			'''
            ##
            numSlices = imp.getNSlices()
            if numSlices > 1:
                pass
            else:
                numFrames = imp.getNFrames()

                if numFrames > 1:
                    # swap nFrames with nSLices
                    numSlices = numFrames
                    numFrames = 1
                    nChannels = 1

                    bPrintLog(
                        'Swapping frames for slices. numSlices=' +
                        str(numSlices) + ' numFrames=' + str(numFrames), 3)
                    imp.setDimensions(nChannels, numSlices, numFrames)
                else:
                    bPrintLog(
                        'ERROR: number of slices must be more than one, file: '
                        + tifFileName)
                    return -1
            ##

            # get the stack header (e.g. infoStr)
            infoStr = imp.getProperty("Info")  #get all tags
            if infoStr is None:
                infoStr = ''

            ## median filter
            if self.medianFilter > 0:
                bPrintLog('Running median filter: ' + str(self.medianFilter),
                          3)
                medianArgs = 'radius=' + str(self.medianFilter) + ' stack'
                IJ.run(imp, "Median...", medianArgs)
                infoStr += 'bMedianFilter=' + str(self.medianFilter) + '\n'
                imp.setProperty("Info", infoStr)

            #add to stack header
            infoStr += 'b_AlignFolder=v0.0\n'
            imp.setProperty("Info", infoStr)

            imp.show()
            impWin = imp.getTitle()

            #show the slice we start alignment on
            middleSlice = int(math.floor(numSlices / 2))
            imp.setSlice(middleSlice)

            transformationFile = self.dstFolder + tifFileName + '.txt'

            if run_alignment:
                bPrintLog('Running MultiStackReg for: ' + tifFileName, 3)
                stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' % (
                    impWin, transformationFile)
                IJ.run('MultiStackReg', stackRegParams)
            else:
                bPrintLog(
                    'DEBUG: NOT running MultiStackReg for: ' + tifFileName, 3)

            # save alignment
            bPrintLog('Saving aligned stack():' + self.dstFolder + tifFileName,
                      3)
            fs = FileSaver(imp)
            if numSlices > 1:
                fs.saveAsTiffStack(self.dstFolder + tifFileName)
            else:
                fs.saveAsTiff(self.dstFolder + tifFileName)

            imp.changes = 0
            imp.close()

            ###
            ###
            #open and run alignment on other channel
            if isCh1:
                otherFilePath = self.tifFilePath.strip('_ch1.tif') + '_ch2.tif'
            elif isCh2:
                otherFilePath = self.tifFilePath.strip('_ch2.tif') + '_ch1.tif'

            if os.path.isfile(otherFilePath):
                otherFileName = os.path.split(otherFilePath)[1]

                bPrintLog('Loading [OTHER] file: ' + doThisFilePath, 3)
                imp = IJ.openImage(otherFilePath)

                if imp is None:
                    print "ERROR: could not open other image from file:", otherFilePath
                    return -1

                ##
                numSlices = imp.getNSlices()
                if numSlices > 1:
                    pass
                else:
                    numFrames = imp.getNFrames()

                    if numFrames > 1:
                        # swap nFrames with nSLices
                        numSlices = numFrames
                        numFrames = 1
                        nChannels = 1

                        bPrintLog(
                            'Swapping frames for slices. numSlices=' +
                            str(numSlices) + ' numFrames=' + str(numFrames), 3)
                        imp.setDimensions(nChannels, numSlices, numFrames)
                    else:
                        bPrintLog(
                            'ERROR: number of slices must be more than one, file: '
                            + tifFileName)
                        return -1
                ##

                #add to stack header
                infoStr = imp.getProperty("Info")  #get all tags
                if infoStr is None:
                    infoStr = ''
                infoStr += 'b_AlignFolder=v0.0' + '\n'
                imp.setProperty("Info", infoStr)

                imp.show()
                impWin = imp.getTitle()

                if run_alignment:
                    bPrintLog('Running MultiStackReg for: ' + otherFileName, 3)
                    stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % (
                        impWin, transformationFile)
                    IJ.run('MultiStackReg', stackRegParams)
                else:
                    bPrintLog(
                        'DEBUG: Not running MultiStackReg for: ' +
                        otherFileName, 3)

                #save alignment
                bPrintLog(
                    'Saving aligned stack():' + self.dstFolder + otherFileName,
                    3)
                fs = FileSaver(imp)
                if numSlices > 1:
                    fs.saveAsTiffStack(self.dstFolder + otherFileName)
                else:
                    fs.saveAsTiff(self.dstFolder + otherFileName)

                imp.changes = 0
                imp.close()
Exemple #46
0
from ij import IJ
from ij.plugin.frame import RoiManager
from ij.gui import Roi
from ij.gui import GenericDialog

gui = GenericDialog("ROI warning")

# Get the active image, its title, and the directory where it lies
imp = IJ.getImage()
imp_title = imp.getTitle()[:-4]
N_imp_frames = imp.getNSlices()
path = IJ.getDirectory("image")
IJ.log("Active image source: {}{}".format(path, imp_title))

# Instantiate RoiManager as rm, select all rois and measure them
roim = RoiManager.getInstance()
# Run the sort and interpolate commands. Before running "save rois" the
# user should have define first and last ROIs and a few in between.
roim.runCommand("Sort")
roim.runCommand("Interpolate ROIs")
# Get the roi count for quality control loop below
rois_count = roim.getCount()
if rois_count == N_imp_frames:
    roi_save_path = str("{}{}_measurement_rois.zip".format(path, imp_title))
    roim.runCommand("Select All")
    roim.runCommand("Save", roi_save_path)
    print("ROIs saved at {}".format(roi_save_path))

else:
    print(
        "ROI array was {} frames long, active image was {} frames long".format(
Exemple #47
0
#Modification of the plugin _ISCH_ Made by John Waller.
#Modifications made by Robin Pranter

from ij.gui import WaitForUserDialog, GenericDialog
from ij import IJ, ImagePlus, ImageJ
import math
import os

# ImageJ()

IJ.run("Open...")

imp = IJ.getImage()
title = imp.getWindow()


def distance(x1, y1, x2, y2):
    sq1 = (x1 - x2) * (x1 - x2)
    sq2 = (y1 - y2) * (y1 - y2)
    dis = math.sqrt(sq1 + sq2)
    return (dis)


while True:

    checkbox = False
    while checkbox == False:
        gd = GenericDialog("Title here")
        gd.addStringField("id", "")
        gd.addCheckbox("Same Image", True)
        gd.showDialog()
Exemple #48
0
# spotDetection3D.py
# ==================
#
# This script demonstrates spot detection
# in 3D on the GPU
#
# Author: Robert Haase, [email protected]
#         October 2019
#########################################

from ij import IJ;
from net.haesleinhuepf.clij import CLIJ;
from net.haesleinhuepf.clijx import CLIJx;


IJ.run("Close All");

# load/create example images
# imp = IJ.openImage("C:/structure/data/Nantes_000646.tif");
# imp = IJ.openImage("C:/structure/data/Riga_000512.tif");
# imp = IJ.openImage("C:/structure/data/Pau_001130.tif");
imp = IJ.openImage("C:/structure/data/Finsterwalde_001250.tif");


IJ.run(imp, "32-bit", "");
# IJ.run(imp, "Rotate 90 Degrees Right", "");
imp.show();

# Init GPU
clijx = CLIJx.getInstance();
clijx.stopWatch("");
fragments_group_name = "Isolated synaptic terminals"

# FIXME: And also hardcode the separation:

x_separation = 4.0
z_separation = 50.0

radius_node_class = Class.forName('ini.trakem2.display.Treeline$RadiusNode')

# Set up the JDBC connection:

try:
    Class.forName("org.postgresql.Driver")
except:
    IJ.log("Failed to find the postgresql driver...")
    raise

conf = {}
fp = open(os.path.join(os.environ['HOME'], '.catmaid-db'))
for line in fp:
    line = line.strip()
    if len(line) == 0:
        continue
    m = re.search('(\S*)\s*:\s*(\S*)', line)
    if m:
        conf[m.group(1)] = m.group(2)
fp.close()

database_url = "jdbc:postgresql://%s/%s" % (conf['host'], conf['database'])
pos = slicePositionToImageMin

while (True):
    # acquire another image and put it in the window of the first one
    pos = pos + 5
    if (pos > slicePositionToImageMax):
        pos = slicePositionToImageMin

    singlePlaneImager.setMinZ(pos)

    image = singlePlaneImager.acquire()
    updatedImagePlus = clij.converter(image).getImagePlus()
    imagePlus.setProcessor(updatedImagePlus.getProcessor())
    imagePlus.updateAndDraw()
    imagePlus.killRoi()
    IJ.run(imagePlus, "Enhance Contrast", "saturated=0.35")

    # do online post-processing wiht ImageJ
    # IJ.run(imagePlus, "Find Maxima...", "noise=200 output=[Point Selection]");

    # sleep and potentially exit the loop if the user closed the window
    Thread.sleep((int)(frameDelayInSeconds * 1000))
    if (imagePlus.getWindow() is None):
        print("Window closed")
        break

#thats always a good idea by the end
scope.shutDownAllLasers()

#BScope.cleanup();
def run():
    '''This is the main function run when the plugin is called.'''

    #print dir(IJ)
    ip = IJ.getProcessor()

    imp = IJ.getImage()  # get the current Image, which is an ImagePlus object
    #print "imp=", type(imp), imp
    #print dir(imp)

    roi = imp.getRoi()  # get the drawn ROI
    #print "roi=", roi, roi.getClass()

    # check ROI type
    if roi == None:
        gd = GenericDialog("Draw Measurement - Line")
        gd.addMessage("Please draw a straight-line first!")
        gd.showDialog()
        return
        #raise Exception(  "Please draw a line ROI first!" )
    if roi.getTypeAsString() != "Straight Line":
        gd = GenericDialog("Draw Measurement - Line")
        gd.addMessage("Please draw a straight-line first!")
        gd.showDialog()
        return
        #raise Exception(  "Not a Line ROI!  (type="+roi.getTypeAsString()+")"  )

    # Add auto calibration from text file
    if sets.autoupdatecal:

        newcal = imp.getCalibration().copy(
        )  # make a copy of current calibration object

        if MC_DEBUG: print("Assume calibration is a custom function.")
        # call the class' `classObj.cal( ImagePlusObject )` function to get the scale value:
        try:
            calObject = sets.autoupdatecal_name
            calName = calObject.name
            newPixelPerUnit = calObject.cal(imp)
        except AttributeError:
            raise ValueError(
                'This calibration Name value is invalid, please check your Settings.py file!/n/tFor Calibration Number %i, got: `'
                % (CalIdx) + str(cal.names[CalIdx]) +
                '`. Expected a String or a Class instance with ".cal()" method, but got type '
                + str(type(cal.names[CalIdx])) + ' with no ".cal()" method.')
        #end try

        newUnit = calObject.unit
        newAspect = calObject.aspect_ratio

        newPixelWidth = 1. / newPixelPerUnit
        newPixelHeight = newPixelWidth * newAspect

        # the following translated from "Microscope_Scale.java":
        newcal.setUnit(newUnit)
        newcal.pixelWidth = newPixelWidth
        newcal.pixelHeight = newPixelHeight

        imp.setGlobalCalibration(None)
        imp.setCalibration(newcal)  # set the new calibration
        imp.getWindow().repaint()  # refresh the image?

    # Added - add the measurement to the list...
    a = Analyzer(imp)
    a.measure()
    a.displayResults()

    # from ij.measure import ResultsTable
    # rt = ResultsTable.getResultsTable()

    p1 = [int(roi.x1d), int(roi.y1d)]  # point 1 (x,y)
    p2 = [int(roi.x2d), int(roi.y2d)]  # point 2
    #print "DrawMeas(): Line Points: p1=", p1, " & p2=", p2
    pm = midpoint(p1, p2)  # get midpoint coord

    # set ROI params from settings:
    ''' Using new method - used ip.drawLine instead of roi.draw, since roi.draw didn't always apply the line thickness.  Would be best to use the ROI method, in case other types of ROI's could be annotated.
     
    roi.setStrokeWidth( sets.linethickness ) 
    roi.setStrokeColor(  jColor(float(sets.linecolor[0]), float(sets.linecolor[1]), float(sets.linecolor[2]), float(sets.linecolor[3]))  ) 
     
    #roi.drawPixels( ip )   # draw along the ROI - only draws outline unfortunately 
    ip.drawRoi(roi)     # draw the ROI on the image 
    '''

    ip.setLineWidth(int(sets.linethickness))
    ip.setColor(
        jColor(float(sets.linecolor[0]), float(sets.linecolor[1]),
               float(sets.linecolor[2]), float(sets.linecolor[3])))

    #ip.draw(roi)   # changed to ip.drawLine()
    ip.drawLine(int(roi.x1d), int(roi.y1d), int(roi.x2d), int(roi.y2d))
    '''Draw text annotation'''
    unit = imp.getCalibration().getUnit().encode(
        'utf8')  # get the unit as UTF-8 (for \mu)
    #print "Draw_Meas(): Unit (raw) = `", unit,"`", type(unit),
    if unit[0] == u'\xc2': unit = unit[1:]  # strip weird char at start of \mu

    # format of measurement text (eg. 3 decimal points):
    lenstr = "%0.3f" % roi.getLength() + " %s" % (
        unit)  # string to print as length
    print "DrawMeas(): Line length= %s" % lenstr
    #print "x,y=", p2[0], p2[1]
    '''determine position of text from line coords, eg "bottom right" or "top left" etc.   '''
    # y-coord:
    if p2[1] > p1[1]:
        posstr = 'bottom'
    else:
        posstr = 'top'

    # x-coord:
    if p2[0] > p1[0]:
        posstr += ' right'
    else:
        posstr += ' left'

    drawText(lenstr, p2[0], p2[1], position=posstr)

    imp.updateAndDraw()  #update the image
Exemple #52
0
from ij import IJ, ImagePlus

# create a empty image with the same dimensions, bitdepth
imp = IJ.getImage()
dims = imp.getDimensions()
depth = imp.getBitDepth()
dims = list(dims)
dims.append(depth)

new_imp = IJ.createHyperStack("new", *dims)
new_imp.show()

Exemple #53
0
from ij import IJ

IJ.run("Line Width...", "line=2")
Exemple #54
0
def confirmLoading():
    """Acknowledges accessibility to this file"""
    from ij import IJ
    IJ.showMessage("BAR lib successfully loaded!")
print("in_file: {}".format(in_file))
print("out_dir: {}".format(out_dir))
if write_fused in (1, 2):
    fusion_method = "Linear Blending"
else:
    fusion_method = "Do not fuse images (only write TileConfiguration)"
print("fusion method: {}".format(fusion_method))

options = ("type=[Positions from file] "
           "order=[Defined by TileConfiguration] "
           "multi_series_file=" + in_file + " "
           "output_directory=" + out_dir + " "
           "fusion_method=[" + fusion_method + "] "
           "regression_threshold=0.30 "
           "max/avg_displacement_threshold=2.50 "
           "absolute_displacement_threshold=3.50 "
           "use_virtual_input_images "
           "computation_parameters=[Save memory (but be slower)] "
           "image_output=[Write to disk] ")
if write_fused in (0, 2):
    options += "compute_overlap "
    IJ.run("Quit")
else:
    # keep ImageJ/Fiji open so the user can review image alignments in the
    # tile configuration file and manually close the app, after which any
    # enclosing script can continue, including re-running this script with
    # write flag on
    print("\nLeaving ImageJ/Fiji open for review of alignments")

print(options)
IJ.run("Grid/Collection stitching", options)
def drawText(text, x, y, position='bottom right'):
    '''Draw a text string at the specified coordinates & relative position, ensuring text doesn't go over the edge of the image. 
     
    Parameters: 
    ----------- 
    text : string 
        The text string to write on the image. 
     
    x, y : int 
        The coordinates at which to draw the text. 
     
    position : { 'bottom right', 'top right', 'top left', 'bottom left' }, case-insensitive, optional 
        Where to draw the text, with respect to the coordinates given. 
        Synonyms for 'bottom right' are 'br'.  This is the default. 
        Synonyms for 'top right' are 'tr'. 
        Synonyms for 'bottom left' are 'bl'. 
        Synonyms for 'top left' are 'tl'. 
    '''
    print "drawText(): original (x,y)=(%i,%i)" % (x, y)

    ip = IJ.getProcessor()  # Image Processor
    imp = IJ.getImage()  # get the current Image, which is an ImagePlus object
    '''Acquire arguments'''
    position = position.strip().lower()
    if position == 'bottom right' or position == 'br':
        pos = 'br'
    elif position == 'bottom left' or position == 'bl':
        pos = 'bl'
    elif position == 'top left' or position == 'tl':
        pos = 'tl'
    elif position == 'top right' or position == 'tr':
        pos = 'tr'
    else:
        raise ValueError('drawText(): Invalid `position` argument: "%s".' %
                         (position))
    '''Setup text annotation'''
    # set font:
    ip.setFont(jFont('SansSerif', 0, sets.textsize))
    ip.setColor(
        jColor(float(sets.textcolor[0]), float(sets.textcolor[1]),
               float(sets.textcolor[2]), float(sets.textcolor[3])))
    '''determine text position'''
    margin = 6  # space in pixels away from edge of image
    spacer = 4  # space in pixels to add between point & text
    strw = ip.getStringWidth(text)
    strh = ip.getFontMetrics().getHeight()
    imgw = ip.getWidth()
    imgh = ip.getHeight()
    '''
    print "strw =", strw 
    print "strh =", strh 
    print "imgw =", imgw 
    print "imgh =", imgh 
    '''

    # set coords (x,y) based on `position` argument
    ''' By default, text is horizontally centered at point (x), and vertically above the point (y).  We then modify these default coords.  '''

    if pos[0] == 'b':
        y = y + spacer + strh  # moves down
    elif pos[0] == 't':
        y = y - spacer

    if pos[1] == 'r':
        x = x + spacer  # moves right
    elif pos[1] == 'l':
        x = x - spacer - int(strw)

    print "drawText(): %s " % (pos) + "(x,y)=(%i,%i)" % (x, y)
    '''Correct for edge of image'''
    if y - strh < 0:
        y = 0 + strh + margin
    elif y > imgh:
        y = imgh - margin

    if (x) < 0:
        x = 0 + margin
    elif (x + strw) > imgw:
        x = imgw - strw - margin

    print "drawText(): final (x,y)=(%i,%i)" % (x, y)

    if sets.textbackgroundcolor:
        ip.drawString(text, x, y,
                      jColor(float(sets.textbackgroundcolor[0]),
                             float(sets.textbackgroundcolor[1]),
                             float(sets.textbackgroundcolor[2]),
                             float(sets.textbackgroundcolor[3]))
                      )  # write the text w/ BG color
    else:
        ip.drawString(text, x, y)  # write the text alone

    imp.updateAndDraw()  #update the image
def displayResults(imp, mr_pos, ncc_pos):
    imp.show()
    mr_ncc_pos_idx = []

    IJ.run("Overlay Options...", "stroke=red width=1 fill=red set")
    for idx_mr in mr_pos:
        rm.select(idx_mr)
        IJ.run(imp, "Add Selection...", "")

    IJ.run("Overlay Options...", "stroke=green width=2 fill=[]")
    for idx_ncc in ncc_pos:
        rm.select(idx_ncc)
        if idx_ncc in mr_pos:
            IJ.run("Overlay Options...", "stroke=orange width=2 fill=yellow")
            IJ.run(imp, "Add Selection...", "")
            mr_ncc_pos_idx.append(idx_ncc)
        else:
            IJ.run("Overlay Options...", "stroke=green width=2 fill=[]")
            IJ.run(imp, "Add Selection...", "")

    IJ.run("Show Overlay", "")
    IJ.log("Number of MR+ AND NCC+ cells: " + str(len(mr_ncc_pos_idx)))
    gateway.connect(credentials)
    return gateway


def download_image(gateway, image_id, path):
    "Download the files composing the image"

    transfer = gateway.getFacility(TransferFacility)
    user = gateway.getLoggedInUser()
    ctx = SecurityContext(user.getGroupId())
    return transfer.downloadImage(ctx, path, Long(image_id))


# Connect to OMERO
gateway = connect_to_omero()

# Download the image. This could be composed of several files
tmp_dir = tempfile.mkdtemp()
print(tmp_dir)

files = download_image(gateway, image_id, tmp_dir)
for f in files:
    options = "open=" + f.getAbsolutePath()
    options += " autoscale color_mode=Default "
    options += "view=[Standard ImageJ] stack_order=Default"
    IJ.run("Bio-Formats Importer", options)
    break

shutil.rmtree(tmp_dir)
gateway.disconnect()
def detect_NCC_pos(nuclei, thickness):

    IJ.selectWindow("NCC")
    imp = IJ.getImage()
    IJ.run("Remove Overlay", "")
    IJ.run("Overlay Options...", "stroke=green width=0 fill=green set")
    IJ.run("Set Measurements...", "area mean redirect=NCC decimal=3")
    pos_idx = []
    neg_idx = []
    idx = 0
    #IJ.log("nuclei :"+str(len(nuclei)))
    IJ1.batchMode = True
    for idx in nuclei:
        #IJ.log("idx: "+str(idx))
        ncc_roi = rm.select(idx)
        IJ.run("Make Band...", "band=" + str(thickness))
        #rm.runCommand("Update")
        if IJ.getValue(wm.getImage("NCC"), "Mean") > ncc_threshold:
            pos_idx.append(idx)
            rm.rename(idx, str(idx) + "-NCC-POS")
            IJ.run(imp, "Add Selection...", "")
            IJ.run(imp, "Select None", "")
        else:
            neg_idx.append(idx)
            rm.rename(idx, str(idx) + "-NCC-NEG")
    IJ1.batchMode = False

    IJ.run("Show Overlay", "")
    IJ.log("Number of NCC+ cells: " + str(len(pos_idx)))
    IJ.log("Number of NCC- cells: " + str(len(neg_idx)))
    return pos_idx
def initialize():
    #Step 0: cleanup and sanity check
    IJ.log("Parameters used:")
    IJ.log("thickness: " + str(band_thickness))
    IJ.log("min area: " + str(min_nucleus_area))
    IJ.log("max area: " + str(max_nucleus_area))
    IJ.log("NCC threshold: " + str(ncc_threshold))
    IJ.log("MR threshold: " + str(mr_threshold))
    IJ.log("----")

    IJ.log("Initialize started...")
    rm.runCommand("reset")
    IJ.run("Clear Results")
    IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel")
    IJ.log("Initialize done.")