コード例 #1
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  
def showDialogR(R, val):
    """ Create dialog for input and save R values in settings
	"""
    gui = GenericDialog("Heterogeneous Z Correction")
    msg = "Heterogeneous Z Correction calculates an optical model\n"\
       "based on rational fluorescence intensity attenuation\n"\
       "over depth, in the form of (ax+b)/(x+c). Please specify\n"\
       "(a,b,c) for each region. You should provide a z-stack with\n"\
       "unique pixel values for each region.\n"
    gui.addMessage(msg)
    for ii in range(len(val)):
        gui.addNumericField(
            "Region " + str(ii) + " (" + str(val[ii]) + "):   a", R[ii][0], 2)
        gui.addToSameRow()
        gui.addNumericField("b", R[ii][1], 2)
        gui.addToSameRow()
        gui.addNumericField("c", R[ii][2], 2)
    gui.addHelp(
        r"https://github.com/alexandrebastien/heterogeneous-z-correction")
    gui.showDialog()
    if gui.wasOKed():
        R = []
        for ii in range(len(val)):
            R = R + [
                (gui.getNextNumber(), gui.getNextNumber(), gui.getNextNumber())
            ]
        Prefs.set("HetZCorr.R", str(R))
        return R
    else:
        return
コード例 #3
0
    def addDefaultOptions(self):
        '''
		Add default GUI items
		- checkbox runMeasurement
		- add to Manager, nextSlice, runMeasurement
		- resource message
		- help button
		'''
        # Checkbox next slice and run Measure
        self.addCheckbox("Auto next slice/image file",
                         bool(Prefs.get("annot.doNext", True)))

        if self.browseMode == "stack":
            self.addToSameRow()
            self.addChoice("- dimension (for hyperstack)", hyperstackDim,
                           Prefs.get("annot.dimension", hyperstackDim[0]))

        elif self.browseMode == "directory":
            # Add button previous/next
            self.addButton(BrowseButton.LABEL_PREVIOUS, BrowseButton())
            self.addToSameRow()
            self.addButton(BrowseButton.LABEL_NEXT, BrowseButton())

        self.addMessage(
            "Documentation and generic analysis workflows available on the GitHub repo (click Help)"
        )

        # Add Help button pointing to the github
        self.addHelp(
            r"https://github.com/LauLauThom/Fiji-QualiAnnotations#readme")
        self.hideCancelButton()
コード例 #4
0
    def actionPerformed(self, event):
        """Delete the last row"""

        # Generate a save dialog
        dialog = JFileChooser(Prefs.get("roiGroup.importDir", ""))
        dialog.setSelectedFile(File("roiGroups.txt"))
        dialog.setFileFilter(FileNameExtensionFilter("Text file", ["txt"]))
        output = dialog.showOpenDialog(
            self.groupTable)  # could be None argument too

        if output in [JFileChooser.CANCEL_OPTION, JFileChooser.ERROR_OPTION]:
            return
        selectedFile = dialog.getSelectedFile()
        directory = selectedFile.getParent()
        Prefs.set("roiGroup.importDir", directory)
        if not selectedFile.isFile(): return
        filePath = selectedFile.getPath()

        # Read comma-separated group from file
        with open(filePath, "r") as textFile:
            stringGroup = textFile.readline().rstrip()

        # Update table with content of file
        tableModel = self.groupTable.tableModel
        tableModel.setGroupColumn(stringGroup)
コード例 #5
0
ファイル: fijipytools.py プロジェクト: soyers/OAD
    def setReaderOptions(imagefile, stitchtiles=False,
                                    setflatres=True,
                                    setconcat=False,
                                    openallseries=False,
                                    showomexml=False,
                                    attach=False,
                                    autoscale=True):

        czi_options = DynamicMetadataOptions()
        czi_options.setBoolean("zeissczi.autostitch", stitchtiles)
        czi_options.setBoolean("zeissczi.attachments", attach)

        # set the option for the CZIReader
        czireader = ImportTools.setCZIReaderOptions(imagefile, czi_options, setflatres=setflatres)

        # Set the preferences in the ImageJ plugin
        # Note although these preferences are applied, they are not refreshed in the UI
        Prefs.set("bioformats.zeissczi.allow.autostitch", str(stitchtiles).lower())
        Prefs.set("bioformats.zeissczi.include.attachments", str(attach).lower())

        # set the option for the BioFormats import
        reader_options = ImporterOptions()
        reader_options.setOpenAllSeries(openallseries)
        reader_options.setShowOMEXML(showomexml)
        reader_options.setConcatenate(setconcat)
        reader_options.setAutoscale(autoscale)
        reader_options.setStitchTiles(stitchtiles)
        reader_options.setId(imagefile)

        return reader_options, czireader
コード例 #6
0
ファイル: Colortags.py プロジェクト: ImageJ-scripts/Libraries
	def __init__(self):

		self.window = None
		self.tags = {}
		self.prefkeys = ["{0}.{1}".format(SUBKEY, name) for name in COLORS]
		self.userprefs = Prefs()
		self.load()
		while not self.tags:
			self.edit("Please set at least one colortag.\n\n")
コード例 #7
0
	def getListCategories(self): 
		"""
		Read the new category names entered by user in the GUI.
		Save the values as a comma-separated string in persistence.
		"""
		listCategories = [] 
		for textField in self.panel.getComponents(): 
				newCategory = textField.getText() 
				if newCategory: listCategories.append(newCategory) 
		
		Prefs.set("annot.listCat", ",".join(listCategories) ) # save the new list of categories 
		 
		return listCategories 
コード例 #8
0
    def makeCategoryComponent(self, category):
        """
		Generates a checkbox with the new category name, to add to the GUI 
		Overwrite the original method 
		"""
        stringCat = Prefs.get("annot.listCat", "")
        newStringCat = stringCat + "," + category if stringCat else category
        Prefs.set("annot.listCat", newStringCat)

        # Make a new checkbox with the category name
        checkbox = Checkbox(category, False)
        checkbox.setFocusable(
            False)  # important to have the keybard shortcut working
        return checkbox
コード例 #9
0
			self.defaultActionSequence() 	 

	def makeCategoryComponent(self, category):
		"""Return a button with the new category name, and mapped to the action"""
		listCat.append(category)
		
		# Save the new category in memory
		Prefs.set("annot.listCat", ",".join(listCat) )
		
		button = JButton(category)
		button.addActionListener(categoryAction)
		button.setFocusable(False)

		# Add button tooltip if fit in the F1-F12 button range
		nCat = len(listCat)
		if nCat <= 12: button.setToolTipText("Keyboard shortcut: F" + str(nCat)) # F shortcut labels are 1-based, ie match the len value
def main(*R):
    """ Main function
	"""
    # Show intial progress bar
    IJ.showProgress(0, 50)
    IJ.showStatus("Heterogeneous Z Correction")

    # Retrieve the values R (with default values) from previous attempts
    Rstr = "[(-0.05977, 83.3, 78.73),(-0.05976, 41.65, 39.36)]"
    R = eval(Prefs.get("HetZCorr.R", Rstr))

    # Load current image and get infos
    imp = IJ.getImage()
    stk = imp.getStack()
    (sx, sy, sz) = stackSize(stk)
    cal = imp.getCalibration()

    # Get unique values
    val = getUniqueValues(stk)

    # Get R from dialog
    R = showDialogR(R, val)

    # Generate optical model
    correction = generateModel(stk, R, val)
    imp.setCalibration(cal)

    #Show model image
    correction.show()
    correction.setSlice(sz)
    IJ.run(correction, "Enhance Contrast", "saturated=0.35")
    IJ.run(correction, "Fire", "")
コード例 #11
0
def GetLastMeasureCount():
    myCount = Prefs.get("JRM.meas.counter", int(-1))
    if myCount < 0:
        # it was not set, so set it to zero
        resetLastMeasureCount()
        return 0
    else:
        myCount = int(myCount)
        return myCount
コード例 #12
0
    def actionPerformed(self, event):
        '''
		Handle buttons clicks, delegates to custom methods
		OK: save parameters in memory
		Add new category: delegate to addCategoryComponent() (should be overwritten in daughter)
		Add: delegate to addAction()
		NB: NEVER use getNext methods here, since we call them several time 
		'''
        source = event.getSource()  # test here if it is a button

        if isinstance(
                source, Button
        ):  # if type is a button get label, and check command, otherwise pass to GenericDialogPlus.actionPeformed

            sourceLabel = source.getLabel()

            if sourceLabel == CustomDialog.LABEL_OK:
                # Check options and save them in persistence
                checkboxes = self.getCheckboxes()

                doNext = checkboxes[-1].getState()
                Prefs.set("annot.doNext", doNext)

                # Save selected dimension if mode stack
                if self.browseMode == "stack":
                    Prefs.set("annot.dimension", self.getSelectedDimension())

            elif sourceLabel == "Add new category":
                self.addCategoryComponent()

            elif sourceLabel == self.LABEL_ADD:
                self.addAction()

            else:
                pass

        # Anyway do the mother class usual action handling
        GenericDialogPlus.actionPerformed(self, event)
コード例 #13
0
    def actionPerformed(self, event):
        """Delete the last row"""

        # Generate a save dialog
        dialog = JFileChooser(Prefs.get("roiGroup.exportDir", ""))
        dialog.setSelectedFile(File("roiGroups.txt"))
        dialog.setFileFilter(FileNameExtensionFilter("Text file", ["txt"]))

        output = dialog.showSaveDialog(
            self.groupTable)  # could be argument None too

        if output in [JFileChooser.CANCEL_OPTION, JFileChooser.ERROR_OPTION]:
            return
        selectedFile = dialog.getSelectedFile()
        directory = selectedFile.getParent()
        Prefs.set("roiGroup.exportDir", directory)
        filePath = selectedFile.getPath()
        if not ("." in filePath):
            filePath += ".txt"  # Add extension if missing

        # Write the groupString to the file
        groupString = self.groupTable.tableModel.getGroupString()
        with open(filePath, "w") as textFile:
            textFile.write(groupString)
コード例 #14
0
ファイル: prefs.py プロジェクト: imcf/python-imcflibs
def debug_mode():
    """Wrapper to check if 'imcf.debugging' is enabled.

    This is a workaround for a Jython issue in ImageJ with values that are
    stored in the "IJ_Prefs.txt" file being cast to the wrong types and / or
    values in Python. Callling Prefs.get() using a (Python) boolean as the
    second parameter always leads to the return value '0.0' (Python type float),
    no matter what is actually stored in the preferences. Doing the same in e.g.
    Groovy behaves correctly.

    Calling Prefs.get() as below with the second parameter being a string and
    subsequently checking the string value leads to the expected result.
    """
    debug = Prefs.get("imcf.debugging", "false")
    return debug == "true"
コード例 #15
0
    def readCZI(imagefile,
                metainfo,
                stitchtiles=False,
                setflatres=False,
                readpylevel=0,
                setconcat=False,
                openallseries=True,
                showomexml=False,
                attach=False,
                autoscale=True):

        options = DynamicMetadataOptions()
        options.setBoolean("zeissczi.autostitch", stitchtiles)
        options.setBoolean("zeissczi.attachments", attach)

        czireader = ZeissCZIReader()
        czireader.setFlattenedResolutions(setflatres)
        czireader.setMetadataOptions(options)
        czireader.setId(imagefile)

        # Set the preferences in the ImageJ plugin
        # Note although these preferences are applied, they are not refreshed in the UI
        Prefs.set("bioformats.zeissczi.allow.autostitch", str(stitchtiles).lower())
        Prefs.set("bioformats.zeissczi.include.attachments", str(attach).lower())

        # metainfo = {}
        metainfo['rescount'] = czireader.getResolutionCount()
        metainfo['SeriesCount_CZI'] = czireader.getSeriesCount()
        metainfo['flatres'] = czireader.hasFlattenedResolutions()
        # metainfo['getreslevel'] = czireader.getResolution()

        # Dimensions
        metainfo['SizeT'] = czireader.getSizeT()
        metainfo['SizeZ'] = czireader.getSizeZ()
        metainfo['SizeC'] = czireader.getSizeC()
        metainfo['SizeX'] = czireader.getSizeX()
        metainfo['SizeY'] = czireader.getSizeY()

        # check for autostitching and possibility to read attachment
        metainfo['AllowAutoStitching'] = czireader.allowAutostitching()
        metainfo['CanReadAttachments'] = czireader.canReadAttachments()

        # read in and display ImagePlus(es) with arguments
        options = ImporterOptions()
        options.setOpenAllSeries(openallseries)
        options.setShowOMEXML(showomexml)
        options.setConcatenate(setconcat)
        options.setAutoscale(autoscale)
        options.setId(imagefile)

        # open the ImgPlus
        imps = BF.openImagePlus(options)

        metainfo['Pyramid Level Output'] = readpylevel

        # read image data using the specified pyramid level
        imp, slices, width, height, pylevel = ImageTools.getImageSeries(imps, series=readpylevel)
        metainfo['Pyramid Level Output'] = pylevel

        metainfo['Output Slices'] = slices
        metainfo['Output SizeX'] = width
        metainfo['Output SizeY'] = height

        # calc scaling in case of pyramid
        # scale = float(metainfo['Output SizeX']) / float(metainfo['SizeX'])
        scale = float(metainfo['SizeX']) / float(metainfo['Output SizeX'])

        metainfo['Pyramid Scale Factor'] = scale
        metainfo['ScaleX Output'] = metainfo['ScaleX'] * scale
        metainfo['ScaleY Output'] = metainfo['ScaleY'] * scale

        """
        imp = MiscTools.setproperties(imp, scaleX=metainfo['ScaleX Output'],
                                      scaleY=metainfo['ScaleX Output'],
                                      scaleZ=metainfo['ScaleZ'],
                                      unit="micron",
                                      sizeC=metainfo['SizeC'],
                                      sizeZ=metainfo['SizeZ'],
                                      sizeT=metainfo['SizeT'])
        """

        imp = MiscTools.setscale(imp, scaleX=metainfo['ScaleX Output'],
                                 scaleY=metainfo['ScaleX Output'],
                                 scaleZ=metainfo['ScaleZ'],
                                 unit="micron")

        # close czireader
        czireader.close()

        return imp, metainfo
コード例 #16
0
def setLastMeasureCount(count):
    count = int(count)
    Prefs.set("JRM.meas.counter", count)
コード例 #17
0
IJ.open(imgPath);
IJ.run("Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.03143555 pixel_height=0.03144531 voxel_depth=1.0000000");
orig = IJ.getImage();

ti = orig.getShortTitle();
pngPath = homDir + relDir + "/" + ti + ".png"

strBar = "width=%g height=%g font=%g color=%s location=[%s] bold" % (barW, barH, barF, barC, barL)
# a hack to get the scale bars to work reliably
IJ.run(orig, "RGB Color", "")

# dummy to get things set
foo = orig.duplicate()
IJ.run(foo, "Add Scale Bar", strBar)
# explicitly save preferences
Prefs.savePreferences()
foo.changes = False
foo.close()

IJ.run(orig, "Add Scale Bar", strBar)
print(pngPath)

fs = FileSaver(orig)
if fs.saveAsPng(pngPath):
	print "png saved successfully at ", pngPath  

time.sleep(sleepTime)

orig.close()
コード例 #18
0
def main():

    Interpreter.batchMode = True

    if (lambda_flat == 0) ^ (lambda_dark == 0):
        print ("ERROR: Both of lambda_flat and lambda_dark must be zero,"
               " or both non-zero.")
        return
    lambda_estimate = "Automatic" if lambda_flat == 0 else "Manual"

    print "Loading images..."

    # For multi-scene .CZI files, we need raw tiles instead of the
    # auto-stitched mosaic and we don't want labels or overview images.  This
    # only affects BF.openImagePlus, not direct use of the BioFormats reader
    # classes which we also do (see below)
    Prefs.set("bioformats.zeissczi.allow.autostitch",  "false")
    Prefs.set("bioformats.zeissczi.include.attachments", "false")

    # Use BioFormats reader directly to determine dataset dimensions without
    # reading every single image. The series count (num_images) is the one value
    # we can't easily get any other way, but we might as well grab the others
    # while we have the reader available.
    dyn_options = DynamicMetadataOptions()
    # Directly calling a BioFormats reader will not use the IJ Prefs settings
    # so we need to pass these options explicitly.
    dyn_options.setBoolean("zeissczi.autostitch", False)
    dyn_options.setBoolean("zeissczi.attachments", False)
    bfreader = ImageReader()
    bfreader.setMetadataOptions(dyn_options)
    bfreader.id = str(filename)
    num_images = bfreader.seriesCount
    num_channels = bfreader.sizeC
    width = bfreader.sizeX
    height = bfreader.sizeY
    bfreader.close()

    # The internal initialization of the BaSiC code fails when we invoke it via
    # scripting, unless we explicitly set a the private 'noOfSlices' field.
    # Since it's private, we need to use Java reflection to access it.
    Basic_noOfSlices = Basic.getDeclaredField('noOfSlices')
    Basic_noOfSlices.setAccessible(True)
    basic = Basic()
    Basic_noOfSlices.setInt(basic, num_images)

    # Pre-allocate the output profile images, since we have all the dimensions.
    ff_image = IJ.createImage("Flat-field", width, height, num_channels, 32);
    df_image = IJ.createImage("Dark-field", width, height, num_channels, 32);

    print("\n\n")

    # BaSiC works on one channel at a time, so we only read the images from one
    # channel at a time to limit memory usage.
    for channel in range(num_channels):
        print "Processing channel %d/%d..." % (channel + 1, num_channels)
        print "==========================="

        options = ImporterOptions()
        options.id = str(filename)
        options.setOpenAllSeries(True)
        # concatenate=True gives us a single stack rather than a list of
        # separate images.
        options.setConcatenate(True)
        # Limit the reader to the channel we're currently working on. This loop
        # is mainly why we need to know num_images before opening anything.
        for i in range(num_images):
            options.setCBegin(i, channel)
            options.setCEnd(i, channel)
        # openImagePlus returns a list of images, but we expect just one (a
        # stack).
        input_image = BF.openImagePlus(options)[0]

        # BaSiC seems to require the input image is actually the ImageJ
        # "current" image, otherwise it prints an error and aborts.
        WindowManager.setTempCurrentImage(input_image)
        basic.exec(
            input_image, None, None,
            "Estimate shading profiles", "Estimate both flat-field and dark-field",
            lambda_estimate, lambda_flat, lambda_dark,
            "Ignore", "Compute shading only"
        )
        input_image.close()

        # Copy the pixels from the BaSiC-generated profile images to the
        # corresponding channel of our output images.
        ff_channel = WindowManager.getImage("Flat-field:%s" % input_image.title)
        ff_image.slice = channel + 1
        ff_image.getProcessor().insert(ff_channel.getProcessor(), 0, 0)
        ff_channel.close()
        df_channel = WindowManager.getImage("Dark-field:%s" % input_image.title)
        df_image.slice = channel + 1
        df_image.getProcessor().insert(df_channel.getProcessor(), 0, 0)
        df_channel.close()

        print("\n\n")

    template = '%s/%s-%%s.tif' % (output_dir, experiment_name)
    ff_filename = template % 'ffp'
    IJ.saveAsTiff(ff_image, ff_filename)
    ff_image.close()
    df_filename = template % 'dfp'
    IJ.saveAsTiff(df_image, df_filename)
    df_image.close()

    print "Done!"
コード例 #19
0
def getCategoriesFromPersistence():
    """Return categories saved in memory as a list."""
    stringCat = Prefs.get(
        "annot.listCat", "Category1"
    )  # Retrieve the list of categories as a comma separated list, if not defined default to Category1
    return stringCat.split(",") if stringCat else []
コード例 #20
0
"""
getPrefsDirImageJ.py

ImageJ Jython - J. R. Minter - 2018-07-09

Modifications
 
   Date     Who   Ver                      What
----------  ---  ------  ---------------------------------------------
2018-07-09  JRM  0.1.00  First implementation


"""
from ij import IJ, Prefs

st = Prefs.getPrefsDir()
print(st)
コード例 #21
0
def measureFeatureLength(imp, lw = 2, csvPath=None, bAppend=True,
                         offset = -30, digits = 3,
                         font = 18, linCol = Color.YELLOW,
                         labCol = Color.WHITE,
                         bDebug = False):
    """
    measureFeatureLength(imp, lw = 2, csvPath=None, bAppend=True,
                         offset = -30, digits = 3,
                         font = 18, linCol = Color.YELLOW,
                         labCol = Color.WHITE,
                         bDebug = False)

    Manually measure the length of a feature in a calibrated ImagePlus
    and write the results to the overlay.

    Version of 2016-08-04

    Parameters
    ----------

    imp: ImagePlus
        The image to process
    lw: int (2)
        The linewidth for the line
    csvPath: string (None)
        The path to a csv file to write measurements
    bAppend: Boolean (True)
        A flag. If True new results are appended to the file 
    offset: int (-30)
        The Y offset for the label. If negative, the label will
        be written above the measurement, if positive below.
    digits: int (3)
        Round the output (in calibrated units) to this number of decimal
        points.
    font: int (18)
        The font size for the measurement.
    linCol: A color constant (Color.YELLOW)
        The color for the line in the overlay.
    labCol: A color constant (Color.WHITE)
        The color for the label
    bDebug: A Boolean (False)
        A flag to print diagnostic incormation

    Returns
    -------
    None - it does draw in the overlay of the image and write an
           optional .csv file.

    Known Issues
    ------------
    With large line widths the length of the drawn line appears lw 
    pixels too long.
    """

    # First define some convenience functions
    def resetLastMeasureCount():
        Prefs.set("JRM.meas.counter", 0)

    def GetLastMeasureCount():
        myCount = Prefs.get("JRM.meas.counter", int(-1))
        if myCount < 0:
            # it was not set, so set it to zero
            resetLastMeasureCount()
            return 0
        else:
            myCount = int(myCount)
            return myCount

    def setLastMeasureCount(count):
        count = int(count)
        Prefs.set("JRM.meas.counter", count)


    imp = IJ.getImage()
    if imp == None:
        print("You need an image...")
        return
    else:
        roi = imp.getRoi()
        if roi != None:
            if roi.getType() == Roi.LINE:
                # print(roi)
                cal = imp.getCalibration()
                # print(cal)
                unit = cal.getUnits()
                width = cal.pixelWidth
                height = cal.pixelHeight
                x1 = roi.x1 * width
                y1 = roi.y1 * height
                x2 = roi.x2 * width
                y2 = roi.y2 * height
                length = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
                if bDebug:
                    sOut = "X1: %d Y1 %d X2 %d Y2 %d" % (roi.x1, roi.y1,
                                                         roi.x2, roi.y2)
                    print(sOut)
                    print(length, unit)
                    
                ip = imp.getProcessor()
                ip.setColor(linCol)
                oldLW = ip.getLineWidth()
                ip.setLineWidth(lw)
                ip.drawLine(roi.x1, roi.y1, roi.x2, roi.y2)
                ip.setLineWidth(oldLW)
                imp.updateAndDraw()
                ol = imp.getOverlay()
                if ol == None:
                    ol = Overlay()
                res = imp.duplicate()
                # first a dummy text ROI to set the font
                tr = TextRoi(10, 10, "Foo")
                tr.setColor(labCol)
                tr.setFont("SanSerif", font, 1) 
                tr.setJustification(TextRoi.CENTER)
                tr.setAntialiased(True)
                # explicitly save preferences
                Prefs.savePreferences()
                xL = roi.x1 + roi.x2
                xL /= 2
                if offset < 0:
                    yL = min(roi.y1, roi.y2)
                    yL += offset
                else:
                    yL = max(roi.y1, roi.y2)
                    yL += offset
                length = round(length, 3)
                label = "%g %s" % (length, unit)
                tr = TextRoi(xL, yL, label)
                tr.setColor(labCol)
                tr.setFont("SanSerif", font, 1) 
                tr.setJustification(TextRoi.CENTER)
                tr.setAntialiased(True)
                ol.add(tr)
                imp.setOverlay(ol)
                imp.show()
                if csvPath != None:
                    if bAppend:
                        if os.path.isfile(csvPath):
                            theCount = GetLastMeasureCount() + 1
                            f=open(csvPath, 'a')
                        else:
                            f=open(csvPath, 'w')
                            resetLastMeasureCount()
                            theCount = 1
                            strLine = 'img, num, length (%s)\n' % unit
                            f.write(strLine)
                    else:
                        f=open(csvPath, 'w')
                        resetLastMeasureCount()
                        theCount = 1
                        strLine = 'img, num, length (%s)\n' % unit
                        f.write(strLine)
                    strLine = "%s, %d, %.6f\n" % (imp.getShortTitle(), theCount, length)
                    f.write(strLine)
                    f.close()
                    setLastMeasureCount(theCount)
                strMsg = "measured %s count = %d" % (imp.getShortTitle(), theCount)
                print(strMsg)

            else:
                print("You need a line ROI")

            # finally deselect
            IJ.run("Select None")
コード例 #22
0
ファイル: Colortags.py プロジェクト: ImageJ-scripts/Libraries
class Colortags:
'''
This class handles persistence of the name of different color channels.
It instantiates a GUI window to capture and show the color names in use.
Other classes such as ColorMerger needs this to determine the color of the channel being processed.
'''
	def __init__(self):

		self.window = None
		self.tags = {}
		self.prefkeys = ["{0}.{1}".format(SUBKEY, name) for name in COLORS]
		self.userprefs = Prefs()
		self.load()
		while not self.tags:
			self.edit("Please set at least one colortag.\n\n")


	def load(self):
		'''
		Tries to load IBPlib colortags from IJ prefs.
		'''
		for i in range(7):
			storedtags = self.userprefs.getString(".{0}".format(self.prefkeys[i]), "")
			if not storedtags:
				continue
			trimmedtagslist = [t.strip() for t in storedtags.split(",")]
			self.tags.update({i:trimmedtagslist})


	def edit(self, msg=""):
		'''
		Opens the color tags dialog to update color tags
		'''
		self.window = GenericDialog("ColorMerger - Edit color tags")
		self.window.addMessage("{0}Separate tags with a comma.\nBlank values will be ignored.".format(msg))
		for i in range(7):
			try:
				self.window.addStringField(COLORS[i], ", ".join(self.tags[i]), 30)
			except KeyError:
				self.window.addStringField(COLORS[i], "", 30)
		self.window.setOKLabel("Save")
		self.window.showDialog()
		if self.window.wasOKed():
			self.__savetags()
			self.load()


	def __validate(self):

		fields = self.window.getStringFields()
		newvalues = {}
		for i in range(len(fields)):
			txt = fields[i].getText()
			newvalues.update({i: txt.strip()})
		return newvalues


	def __savetags(self):

		newvalues = self.__validate()
		for i, tags in newvalues.items():
			key = self.prefkeys[i]
			self.userprefs.set(key, tags)
			self.userprefs.savePreferences()
コード例 #23
0
def readczi(imagefile,
            stitchtiles=True,
            setflatres=False,
            readpylevel=0,
            setconcat=True,
            openallseries=True,
            showomexml=False,
            attach=False,
            autoscale=True):

    log.info('Filename : ' + imagefile)

    metainfo = {}
    # checking for thr file Extension
    metainfo['Extension'] = MiscTools.getextension(MiscTools.splitext_recurse(imagefile))
    log.info('Detected File Extension : ' + metainfo['Extension'])

    # initialize the reader and get the OME metadata
    reader = ImageReader()
    omeMeta = MetadataTools.createOMEXMLMetadata()
    #metainfo['ImageCount_OME'] = omeMeta.getImageCount()
    reader.setMetadataStore(omeMeta)
    reader.setId(imagefile)
    metainfo['SeriesCount_BF'] = reader.getSeriesCount()
    reader.close()

    # get the scaling for XYZ
    physSizeX = omeMeta.getPixelsPhysicalSizeX(0)
    physSizeY = omeMeta.getPixelsPhysicalSizeY(0)
    physSizeZ = omeMeta.getPixelsPhysicalSizeZ(0)

    if physSizeX is not None:
        metainfo['ScaleX'] = round(physSizeX.value(), 3)
        metainfo['ScaleY'] = round(physSizeX.value(), 3)

    if physSizeX is None:
        metainfo['ScaleX'] = None
        metainfo['ScaleY'] = None

    if physSizeZ is not None:
        metainfo['ScaleZ'] = round(physSizeZ.value(), 3)
    if physSizeZ is None:
        metainfo['ScaleZ'] = None

    options = DynamicMetadataOptions()
    options.setBoolean("zeissczi.autostitch", stitchtiles)
    options.setBoolean("zeissczi.attachments", attach)

    czireader = ZeissCZIReader()
    czireader.setFlattenedResolutions(setflatres)
    czireader.setMetadataOptions(options)
    czireader.setId(imagefile)

    # Set the preferences in the ImageJ plugin
    # Note although these preferences are applied, they are not refreshed in the UI
    Prefs.set("bioformats.zeissczi.allow.autostitch", str(stitchtiles).lower())
    Prefs.set("bioformats.zeissczi.include.attachments", str(attach).lower())

    # metainfo = {}
    metainfo['rescount'] = czireader.getResolutionCount()
    metainfo['SeriesCount_CZI'] = czireader.getSeriesCount()
    #metainfo['flatres'] = czireader.hasFlattenedResolutions()
    #metainfo['getreslevel'] = czireader.getResolution()

    # Dimensions
    metainfo['SizeT'] = czireader.getSizeT()
    metainfo['SizeZ'] = czireader.getSizeZ()
    metainfo['SizeC'] = czireader.getSizeC()
    metainfo['SizeX'] = czireader.getSizeX()
    metainfo['SizeY'] = czireader.getSizeY()

    # check for autostitching and possibility to read attachment
    metainfo['AllowAutoStitching'] = czireader.allowAutostitching()
    metainfo['CanReadAttachments'] = czireader.canReadAttachments()

    # read in and display ImagePlus(es) with arguments
    options = ImporterOptions()
    options.setOpenAllSeries(openallseries)
    options.setShowOMEXML(showomexml)
    options.setConcatenate(setconcat)
    options.setAutoscale(autoscale)
    options.setId(imagefile)

    # open the ImgPlus
    imps = BF.openImagePlus(options)
    metainfo['Pyramid Level Output'] = readpylevel + 1

    try:
        imp = imps[readpylevel]
        pylevelout = metainfo['SeriesCount_CZI']
    except:
        # fallback option
        log.info('PyLevel=' + str(readpylevel) + ' does not exist.')
        log.info('Using Pyramid Level = 0 as fallback.')
        imp = imps[0]
        pylevelout = 0
        metainfo['Pyramid Level Output'] = pylevelout

    # get the stack and some info
    imgstack = imp.getImageStack()
    metainfo['Output Slices'] = imgstack.getSize()
    metainfo['Output SizeX'] = imgstack.getWidth()
    metainfo['Output SizeY'] = imgstack.getHeight()

    # calc scaling in case of pyramid
    scale = float(metainfo['SizeX']) / float(metainfo['Output SizeX'])
    metainfo['Pyramid Scale Factor'] = scale
    metainfo['ScaleX Output'] = metainfo['ScaleX'] * scale
    metainfo['ScaleY Output'] = metainfo['ScaleY'] * scale

    # set the correct scaling
    imp = MiscTools.setscale(imp, scaleX=metainfo['ScaleX Output'],
                             scaleY=metainfo['ScaleX Output'],
                             scaleZ=metainfo['ScaleZ'],
                             unit="micron")

    # close czireader
    czireader.close()

    return imp, metainfo
コード例 #24
0
# for Ambro 2016-05-16
# gLo = 500
# gHi = 3800

# for Kang LM  2016-05-24
gLo = 730
gHi = 2850

bDoTiltCorrect = False


mu = IJ.micronSymbol
scaUm	= mu + "m"


lastPath = Prefs.get("Last.Image.Dir", "None")
if os.path.exists(lastPath):
	os.chdir(lastPath)

dc = DirectoryChooser("Choose directory")
basePath = dc.getDirectory()

print(basePath)
Prefs.set("Last.Image.Dir", basePath)

names = []
for file in os.listdir(basePath):
	if file.endswith(".tif"):
		name = os.path.splitext(file)[0]
		names.append(name)
コード例 #25
0
def resetLastMeasureCount():
    Prefs.set("JRM.meas.counter", 0)
コード例 #26
0
ファイル: czi_to_tif.py プロジェクト: brigidar/FIJI
def getCZIinfo(imagefile, showimage=False, setreslevel=0, setflat2=False, openallseries=True, showomexml=False,setconcat=False,filepath1="./"):
    options = DynamicMetadataOptions()
    options.setBoolean("zeissczi.attachments", False)
    czireader = ZeissCZIReader()
    czireader.setFlattenedResolutions(setflat2)
    czireader.setMetadataOptions(options)
    czireader.setId(imagefile)
    lc = czireader.getSeriesCount()
    #get the first occurence of each pyramid stack
    location=list()
    for i in range(0, int(seriesCount)-2):
        location.append(czireader.coreIndexToSeries(i))
        c=0
    #log.info(location)
    loc2=list()
    for i,v in enumerate(location):
    	if i==0:
        	loc2.append(i)
    	elif i>0 and v!=c:
        	loc2.append(i)
        	c=v
    log.info(str(loc2))
    # get OME data
    omeMeta = MetadataTools.createOMEXMLMetadata()
    # Set the preferences in the ImageJ plugin
    Prefs.set("bioformats.zeissczi.include.attachments", str(True).lower())
    if showimage:

        # read in and display ImagePlus(es) with arguments
        options = ImporterOptions()
        options.setOpenAllSeries(openallseries)
        options.setShowOMEXML(showomexml)
        options.setConcatenate(setconcat)
        options.setId(imagefile)

        # open the ImgPlus
        imps = BF.openImagePlus(options)
        name_list=imagefile.split('/')
        name=name_list[len(name_list)-1]
        out_path=filepath1  + "/"+name+"_Preview.tif"
        log.info(name)
        imp=getImageSeries(imps, seriesCount-1)
        imp.show()
        IJ.run("RGB Color")
        imp.close()
        IJ.saveAs("tiff", out_path)
        IJ.run("Close")
        out_path=filepath1  + "/"+name+"_Label.tif"
        imp=getImageSeries(imps, (seriesCount-2))
        imp.show()
        IJ.run("RGB Color")
        imp.close()
        IJ.saveAs("tiff", out_path)
        IJ.run("Close")
        c=1
        for series in loc2:
        	out_path=filepath1  + "/"+name+"Scene_" + str(c) + ".tif"
        	imp=getImageSeries(imps, series)
        	imp.show()
        	IJ.run("RGB Color")
        	imp.close()
        	IJ.saveAs("tiff", out_path)
        	IJ.run("Close")
        	c+=1
    czireader.close()