Пример #1
0
def get_no_nuclei_fully_enclosed(roi, full_nuclei_imp, overlap_threshold=0.65):
    """for a given cell roi and ImagePlus with binary nuclei, return how many nuclei lie ENTIRELY within the cell"""
    bbox = roi.getBounds()
    full_nuclei_imp.setRoi(roi)
    cropped_nuc_imp = full_nuclei_imp.crop()
    roi.setLocation(0, 0)
    cropped_nuc_imp.setRoi(roi)
    cropped_nuc_imp.killRoi()
    roim = RoiManager(False)
    mxsz = cropped_nuc_imp.getWidth() * cropped_nuc_imp.getHeight()
    pa = ParticleAnalyzer(
        ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA
        | ParticleAnalyzer.SLICE | ParticleAnalyzer.CENTROID, None, 0, mxsz)
    pa.setRoiManager(roim)
    pa.analyze(cropped_nuc_imp)
    cell_imp = IJ.createImage("Cell binary", cropped_nuc_imp.getWidth(),
                              cropped_nuc_imp.getHeight(), 1, 8)
    IJ.run(cell_imp, "Select All", "")
    IJ.run(cell_imp, "Set...", "value=0 slice")
    cell_imp.setRoi(roi)
    IJ.run(cell_imp, "Set...", "value=255 slice")
    no_enclosed_nuclei = 0
    for idx, nuc_roi in enumerate(roim.getRoisAsArray()):
        test_imp = Duplicator().run(cell_imp)
        test_imp.setRoi(nuc_roi)
        IJ.run(test_imp, "Set...", "value=255 slice")
        test_imp.killRoi()
        IJ.run(test_imp, "Create Selection", "")
        IJ.run(test_imp, "Make Inverse", "")
        test_roi = test_imp.getRoi()
        test_roi_stats = test_roi.getStatistics()
        cell_roi_stats = roi.getStatistics()
        nuc_roi_stats = nuc_roi.getStatistics()
        if test_roi_stats.area < (
                cell_roi_stats.area +
            (1 - overlap_threshold) * nuc_roi_stats.area
        ):  # i.e. if more than (100*overlap_threshold)% of nucleus is inside cell...
            no_enclosed_nuclei += 1
        test_imp.changes = False
        test_imp.close()
    roi.setLocation(bbox.getX(), bbox.getY())
    cropped_nuc_imp.changes = False
    cropped_nuc_imp.close()
    cell_imp.changes = False
    cell_imp.close()
    return no_enclosed_nuclei
Пример #2
0
def cut(event):
    roi = imp.getRoi()
    if roi != None:
        newRoi = roi.clone()
        Dup = Duplicator().run(imp, 1, imp.getNChannels(), 1, imp.getNSlices(), 1, imp.getNFrames())
        newRoi.setLocation(0,0)
        Dup.setRoi(newRoi)
        Dup.setTitle(Men.getTextField() + str(Men.getCounter()))
        Dup.show()
        #Men.setCounter()
        Men.addOlay(roi)
        imp.setOverlay(Men.getOverlay())    #setOverlay(Roi roi, java.awt.Color strokeColor, int strokeWidth, java.awt.Color fillColor) 
        imp.getOverlay().drawLabels(True) # drawNumbers
        imp.deleteRoi()
        
        #make cell instance and add to position instance
        p.addCell(cell(p.getMainPath(), p, Men.getCounter(), Dup))  #  cell(mainPath, position, ID, imp):
        Dup.close()
        Men.increaseCounter()
def qc_background_regions(intensity_imp, bg_rois):
	"""allow the user to view and correct automatically-determined background regions"""
	imp = Duplicator().run(intensity_imp);
	imp.setTitle("Background region QC");
	imp.show();
	imp.setPosition(1);
	autoset_zoom(imp);
	imp.setRoi(bg_rois[0]);
	IJ.setTool("freehand");
	
	notOK = True;
	while notOK:
		listener = UpdateRoiImageListener(bg_rois, is_area=True);
		imp.addImageListener(listener);
		dialog = NonBlockingGenericDialog("Background region quality control");
		dialog.enableYesNoCancel("Continue", "Use this region for all t");
		dialog.setCancelLabel("Cancel analysis");
		dialog.addMessage("Please redraw background regions as necessary...")
		dialog.showDialog();
		if dialog.wasCanceled():
			raise KeyboardInterrupt("Run canceled");
		elif not(dialog.wasOKed()):
			this_roi = imp.getRoi();
			bg_rois = [this_roi for _ in listener.getRoiList()];
			imp.removeImageListener(listener);
		else:
			last_roi = imp.getRoi();
			qcd_bg_rois = listener.getRoiList();
			if imp.getNFrames() > imp.getNSlices():
				qcd_bg_rois[imp.getT() - 1] = last_roi;
			else:
				qcd_bg_rois[imp.getZ() - 1] = last_roi;
			notOK = False;
	imp.removeImageListener(listener);
	imp.changes = False;
	imp.close();
	
	return qcd_bg_rois;
Пример #4
0
def runOneFile(fullFilePath):

    global gNumChannels
    global gAlignBatchVersion

    if not os.path.isfile(fullFilePath):
        bPrintLog(
            '\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n',
            0)
        return 0

    bPrintLog(
        time.strftime("%H:%M:%S") + ' starting runOneFile(): ' + fullFilePath,
        1)

    enclosingPath = os.path.dirname(fullFilePath)
    head, tail = os.path.split(enclosingPath)
    enclosingPath += '/'

    #make output folders
    destFolder = enclosingPath + tail + '_channels/'
    if not os.path.isdir(destFolder):
        os.makedirs(destFolder)
    destMaxFolder = destFolder + 'max/'
    if not os.path.isdir(destMaxFolder):
        os.makedirs(destMaxFolder)

    if gDoAlign:
        destAlignmentFolder = destFolder + 'alignment/'
        if not os.path.isdir(destAlignmentFolder):
            os.makedirs(destAlignmentFolder)

    if gSave8bit:
        eightBitFolder = destFolder + 'channels8/'
        if not os.path.isdir(eightBitFolder):
            os.makedirs(eightBitFolder)
        eightBitMaxFolder = eightBitFolder + 'max/'
        if not os.path.isdir(eightBitMaxFolder):
            os.makedirs(eightBitMaxFolder)

    # open image
    imp = Opener().openImage(fullFilePath)

    # get parameters of image
    (width, height, nChannels, nSlices, nFrames) = imp.getDimensions()
    bitDepth = imp.getBitDepth()
    infoStr = imp.getProperty("Info")  #get all .tif tags
    if not infoStr:
        infoStr = ''
    infoStr += 'bAlignBatch_Version=' + str(gAlignBatchVersion) + '\n'
    infoStr += 'bAlignBatch_Time=' + time.strftime(
        "%Y%m%d") + '_' + time.strftime("%H%M%S") + '\n'

    msgStr = 'w:' + str(width) + ' h:' + str(height) + ' slices:' + str(nSlices) \
       + ' channels:' + str(nChannels) + ' frames:' + str(nFrames) + ' bitDepth:' + str(bitDepth)
    bPrintLog(msgStr, 1)

    path, filename = os.path.split(fullFilePath)
    shortName, fileExtension = os.path.splitext(filename)

    #
    # look for num channels in ScanImage infoStr
    if gGetNumChanFromScanImage:
        for line in infoStr.split('\n'):
            #scanimage.SI4.channelsSave = [1;2]
            scanimage4 = find(line, 'scanimage.SI4.channelsSave =') == 0
            #state.acq.numberOfChannelsSave=2
            scanimage3 = find(line, 'state.acq.numberOfChannelsSave=') == 0
            if scanimage3:
                #print 'line:', line
                equalIdx = find(line, '=')
                line2 = line[equalIdx + 1:]
                if gGetNumChanFromScanImage:
                    gNumChannels = int(line2)
                    bPrintLog(
                        'over-riding gNumChannels with: ' + str(gNumChannels),
                        2)
            if scanimage4:
                #print '   we have a scanimage 4 file ... now i need to exptract the number of channel'
                #print 'line:', line
                equalIdx = find(line, '=')
                line2 = line[equalIdx + 1:]
                for delim in ';[]':
                    line2 = line2.replace(delim, ' ')
                if gGetNumChanFromScanImage:
                    gNumChannels = len(line2.split())
                    bPrintLog(
                        'over-riding gNumChannels with: ' + str(gNumChannels),
                        2)

    # show
    imp.show()
    # split channels if necc. and grab the original window names
    if gNumChannels == 1:
        origImpWinStr = imp.getTitle()  #use this when only one channel
        origImpWin = WindowManager.getWindow(
            origImpWinStr)  #returns java.awt.Window

    if gNumChannels == 2:
        winTitle = imp.getTitle()
        bPrintLog('Deinterleaving 2 channels...', 1)
        IJ.run('Deinterleave',
               'how=2 keep')  #makes ' #1' and ' #2', with ' #2' frontmost
        origCh1WinStr = winTitle + ' #1'
        origCh2WinStr = winTitle + ' #2'
        origCh1Imp = WindowManager.getImage(origCh1WinStr)
        origCh2Imp = WindowManager.getImage(origCh2WinStr)
        origCh1File = destFolder + shortName + '_ch1.tif'
        origCh2File = destFolder + shortName + '_ch2.tif'

    # work on a copy, mostly for alignment with cropping
    copy = Duplicator().run(imp)
    #copy.copyAttributes(imp) #don't copy attributes, it copies the name (which we do not want)
    copy.show()

    #
    # crop (on copy)
    if gDoCrop:
        bPrintLog('making cropping rectangle (left,top,width,height) ', 1)
        bPrintLog(
            str(gCropLeft) + ' ' + str(gCropTop) + ' ' + str(gCropWidth) +
            ' ' + str(gCropHeight), 2)

        roi = Roi(gCropLeft, gCropTop, gCropWidth,
                  gCropHeight)  #left,top,width,height
        copy.setRoi(roi)

        time.sleep(
            0.5
        )  # otherwise, crop SOMETIMES failes. WHAT THE F**K FIJI DEVELOPERS, REALLY, WHAT THE F**K

        #bPrintLog('cropping', 1)
        IJ.run('Crop')
        infoStr += 'bCropping=' + str(gCropLeft) + ',' + str(
            gCropTop) + ',' + str(gCropWidth) + ',' + str(gCropHeight) + '\n'

    #
    # remove calibration ( on original)
    if gRemoveCalibration:
        cal = imp.getCalibration()
        calCoeff = cal.getCoefficients()
        if calCoeff:
            msgStr = 'Calibration is y=a+bx' + ' a=' + str(
                calCoeff[0]) + ' b=' + str(calCoeff[1])
            bPrintLog(msgStr, 1)

            #remove calibration
            bPrintLog('\tRemoving Calibration', 2)
            imp.setCalibration(None)

            #without these, 8-bit conversion goes to all 0 !!! what the f**k !!!
            #bPrintLog('calling imp.resetStack() and imp.resetDisplayRange()', 2)
            imp.resetStack()
            imp.resetDisplayRange()

            #get and print out min/max
            origMin = StackStatistics(imp).min
            origMax = StackStatistics(imp).max
            msgStr = '\torig min=' + str(origMin) + ' max=' + str(origMax)
            bPrintLog(msgStr, 2)

            # 20150723, 'shift everybody over by linear calibration intercept calCoeff[0] - (magic number)
            if 1:
                # [1] was this
                #msgStr = 'Subtracting original min '+str(origMin) + ' from stack.'
                #bPrintLog(msgStr, 2)
                #subArgVal = 'value=%s stack' % (origMin,)
                #IJ.run('Subtract...', subArgVal)
                # [2] now this
                #msgStr = 'Adding calCoeff[0] '+str(calCoeff[0]) + ' from stack.'
                #bPrintLog(msgStr, 2)
                #addArgVal = 'value=%s stack' % (int(calCoeff[0]),)
                #IJ.run('Add...', addArgVal)
                # [3] subtract a magic number 2^15-2^7 = 32768 - 128
                magicNumber = gLinearShift  #2^15 - 128
                msgStr = 'Subtracting a magic number (linear shift) ' + str(
                    magicNumber) + ' from stack.'
                bPrintLog(msgStr, 2)
                infoStr += 'bLinearShift=' + str(gLinearShift) + '\n'
                subArgVal = 'value=%s stack' % (gLinearShift, )
            IJ.run(imp, 'Subtract...', subArgVal)

            # 20150701, set any pixel <0 to 0
            if 0:
                ip = imp.getProcessor()  # returns a reference
                pixels = ip.getPixels()  # returns a reference
                msgStr = '\tSet all pixels <0 to 0. This was added 20150701 ...'
                bPrintLog(msgStr, 2)
                pixels = map(lambda x: 0 if x < 0 else x, pixels)
                bPrintLog('\t\t... done', 2)

            #get and print out min/max
            newMin = StackStatistics(imp).min
            newMax = StackStatistics(imp).max
            msgStr = '\tnew min=' + str(newMin) + ' max=' + str(newMax)
            bPrintLog(msgStr, 2)

            #append calibration to info string
            infoStr += 'bCalibCoeff_a = ' + str(calCoeff[0]) + '\n'
            infoStr += 'bCalibCoeff_b = ' + str(calCoeff[1]) + '\n'
            infoStr += 'bNewMin = ' + str(newMin) + '\n'
            infoStr += 'bNewMax = ' + str(newMax) + '\n'

    #
    # set up
    if gNumChannels == 1:
        impWinStr = copy.getTitle()  #use this when only one channel
        impWin = WindowManager.getWindow(impWinStr)  #returns java.awt.Window

    if gNumChannels == 2:
        winTitle = copy.getTitle()
        bPrintLog('Deinterleaving 2 channels...', 1)
        IJ.run('Deinterleave',
               'how=2 keep')  #makes ' #1' and ' #2', with ' #2' frontmost
        ch1WinStr = winTitle + ' #1'
        ch2WinStr = winTitle + ' #2'
        ch1Imp = WindowManager.getImage(ch1WinStr)
        ch2Imp = WindowManager.getImage(ch2WinStr)
        ch1File = destFolder + shortName + '_ch1.tif'
        ch2File = destFolder + shortName + '_ch2.tif'

    #
    # alignment
    if gDoAlign and gNumChannels == 1 and copy.getNSlices() > 1:
        infoStr += 'AlignOnChannel=1' + '\n'
        #snap to middle slice
        if gAlignOnMiddleSlice:
            middleSlice = int(
                math.floor(copy.getNSlices() /
                           2))  #int() is necc., python is f*****g picky
        else:
            middleSlice = gAlignOnThisSlice
        copy.setSlice(middleSlice)

        transformationFile = destAlignmentFolder + shortName + '.txt'

        bPrintLog('MultiStackReg aligning:' + impWinStr, 1)
        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)
        infoStr += 'AlignOnSlice=' + str(middleSlice) + '\n'

        #20150723, we just aligned on a cropped copy, apply alignment to original imp
        origImpTitle = imp.getTitle()
        stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % (
            origImpTitle, transformationFile)
        IJ.run('MultiStackReg', stackRegParams)

    if gDoAlign and gNumChannels == 2 and ch1Imp.getNSlices(
    ) > 1 and ch2Imp.getNSlices() > 1:
        #apply to gAlignThisChannel
        alignThisWindow = ''
        applyAlignmentToThisWindow = ''
        if gAlignThisChannel == 1:
            infoStr += 'AlignOnChannel=1' + '\n'
            transformationFile = destAlignmentFolder + shortName + '_ch1.txt'
            alignThisWindow = ch1WinStr
            applyAlignmentToThisWindow = ch2WinStr
        else:
            infoStr += 'AlignOnChannel=2' + '\n'
            transformationFile = destAlignmentFolder + shortName + '_ch2.txt'
            alignThisWindow = ch2WinStr
            applyAlignmentToThisWindow = ch1WinStr

        alignThisImp = WindowManager.getImage(alignThisWindow)
        #snap to middle slice
        if gAlignOnMiddleSlice:
            middleSlice = int(
                math.floor(alignThisImp.getNSlices() /
                           2))  #int() is necc., python is f*****g picky
        else:
            middleSlice = gAlignOnThisSlice
        alignThisImp.setSlice(middleSlice)

        infoStr += 'bAlignOnSlice=' + str(middleSlice) + '\n'

        bPrintLog('MultiStackReg aligning:' + alignThisWindow, 1)
        stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' % (
            alignThisWindow, transformationFile)
        IJ.run('MultiStackReg', stackRegParams)

        # 20150723, we just aligned on a copy, apply alignment to both channels of original
        # ch1
        bPrintLog('MultiStackReg applying alignment to:' + origCh1WinStr, 1)
        stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % (
            origCh1WinStr, transformationFile)
        IJ.run('MultiStackReg', stackRegParams)
        # ch2
        bPrintLog('MultiStackReg applying alignment to:' + origCh2WinStr, 1)
        stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % (
            origCh2WinStr, transformationFile)
        IJ.run('MultiStackReg', stackRegParams)

        #apply alignment to other window
        #bPrintLog('MultiStackReg applying alignment to:' + applyAlignmentToThisWindow, 1)
        #applyAlignThisImp = WindowManager.getImage(applyAlignmentToThisWindow)
        #stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(applyAlignmentToThisWindow,transformationFile)
        #IJ.run('MultiStackReg', stackRegParams)
    elif gDoAlign:
        bPrintLog('Skipping alignment, there may be only one slice?', 3)

    #
    # save
    if gNumChannels == 1:
        imp.setProperty("Info", infoStr)
        impFile = destFolder + shortName + '.tif'
        #bPrintLog('Saving:' + impFile, 1)
        bSaveStack(imp, impFile)
        #max project
        bSaveZProject(imp, destMaxFolder, shortName)

    if gNumChannels == 2:
        #ch1
        origCh1Imp.setProperty("Info", infoStr)
        #bPrintLog('Saving:' + ch1File, 1)
        bSaveStack(origCh1Imp, ch1File)
        #max project
        bSaveZProject(origCh1Imp, destMaxFolder, shortName + '_ch1')

        #ch2
        origCh2Imp.setProperty("Info", infoStr)
        #bPrintLog('Saving:' + ch2File, 1)
        bSaveStack(origCh2Imp, ch2File)
        #max project
        bSaveZProject(origCh2Imp, destMaxFolder, shortName + '_ch2')

#
    # post convert to 8-bit and save
    if gSave8bit:
        if bitDepth == 16:
            if gNumChannels == 1:
                bPrintLog('Converting to 8-bit:' + impWinStr, 1)
                IJ.selectWindow(impWinStr)
                #IJ.run('resetMinAndMax()')
                IJ.run("8-bit")
                impFile = eightBitFolder + shortName + '.tif'
                bPrintLog('Saving 8-bit:' + impFile, 2)
                bSaveStack(imp, impFile)
                #max project
                bSaveZProject(imp, eightBitMaxFolder, shortName)

            if gNumChannels == 2:
                #
                bPrintLog('Converting to 8-bit:' + origCh1WinStr, 1)
                IJ.selectWindow(origCh1WinStr)

                IJ.run("8-bit")
                impFile = eightBitFolder + shortName + '_ch1.tif'
                bPrintLog('Saving 8-bit:' + impFile, 2)
                bSaveStack(origCh1Imp, impFile)
                #max project
                bSaveZProject(origCh1Imp, eightBitMaxFolder,
                              shortName + '_ch1')

                #
                bPrintLog('Converting to 8-bit:' + origCh2WinStr, 1)
                IJ.selectWindow(origCh2WinStr)
                #IJ.run('resetMinAndMax()')
                IJ.run("8-bit")
                impFile = eightBitFolder + shortName + '_ch2.tif'
                bPrintLog('Saving 8-bit:' + impFile, 2)
                bSaveStack(origCh2Imp, impFile)
                #max project
                bSaveZProject(origCh2Imp, eightBitMaxFolder,
                              shortName + '_ch2')

    #
    # close original window
    imp.changes = 0
    imp.close()
    #copy
    copy.changes = 0
    copy.close()

    #
    # close ch1/ch2
    if gNumChannels == 2:
        #original
        origCh1Imp.changes = 0
        origCh1Imp.close()
        origCh2Imp.changes = 0
        origCh2Imp.close()
        #copy
        ch1Imp.changes = 0
        ch1Imp.close()
        ch2Imp.changes = 0
        ch2Imp.close()

    bPrintLog(
        time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath,
        1)
        # apply a threshold to detect objects (cells, nuclei,...)
        IJ.setAutoThreshold(imp, "Otsu")
        Prefs.blackBackground = False
        IJ.run(imp, "Convert to Mask", "")

        # analyse objects and put results in table
        IJ.run("Set Measurements...", "area display redirect=None decimal=5")
        IJ.run(imp, "Analyze Particles...", "exclude add")

        manager = RoiManager.getRoiManager()
        manager.runCommand("Save",
                           file.toString() + ".RoiSet.zip")

        for roi in manager.getRoisAsArray():
            copy.setRoi(roi)
            copy.show()
            IJ.run(copy, "Enlarge...", "enlarge=-2")

            # analyse the image
            statistics = copy.getStatistics()
            print("mean: " + str(statistics.mean))
            print("area:" + str(statistics.area))

            # write the analysed valurs in a table
            table = ResultsTable.getResultsTable()
            table.incrementCounter()
            table.addValue("filename", file.toString())
            table.addValue("mean_robert", statistics.mean)
            table.addValue("area", statistics.area)
            table.addValue("total instensity",
def main():
    #print (sys.version_info) # debug
    #print(sys.path) # debug
    data_root = r'C:\Users\dougk\Desktop\test'
    # debug
    output_root = r'C:\Users\dougk\Desktop\test'
    #debug
    #default_directory = r'C:\\Users\\Doug\\Desktop\\test';
    #data_root, output_root = file_location_chooser(default_directory);
    if (data_root is None) or (output_root is None):
        raise IOError("File location dialogs cancelled!")
    timestamp = datetime.strftime(datetime.now(), "%Y-%m-%d %H.%M.%S")
    output_path = os.path.join(output_root, (timestamp + " output"))
    for file_path in filterByFileType(os.listdir(data_root), '.tif'):
        subfolder_name = os.path.splitext(file_path)[0]
        output_subfolder = os.path.join(output_path, subfolder_name)
        print(output_subfolder)
        os.makedirs(output_subfolder)
        imps = bf.openImagePlus(os.path.join(data_root, file_path))
        imp = imps[0]
        imp.show()
        h = imp.height
        w = imp.width
        slices = imp.getNSlices()
        channels = imp.getNChannels()
        frames = imp.getNFrames()

        # rotation step - since using multiples of 90, TransformJ.Turn is more efficient
        IJ.run("Enhance Contrast", "saturated=0.35")
        angleZ = 1
        while ((angleZ % 90) > 0):
            gd = GenericDialog("Rotate?")
            gd.addMessage(
                "Define rotation angle - increments of 90. Apical at top")
            gd.addNumericField("Rotation angle", 0, 0)
            gd.showDialog()
            angleZ = int(gd.getNextNumber())

        if (angleZ > 1):
            IJ.run("TransformJ Turn",
                   "z-angle=" + str(angleZ) + " y-angle=0 x-angle=0")
            imp.close()
            imp = WindowManager.getCurrentImage()
            imp.setTitle(file_path)

        # trim time series
        IJ.run("Enhance Contrast", "saturated=0.35")
        imp.setDisplayMode(IJ.COLOR)
        WaitForUserDialog(
            "Scroll to the first frame of the period of interest and click OK"
        ).show()
        start_frame = imp.getT()
        WaitForUserDialog(
            "Scroll to the last frame of the period of interest and click OK"
        ).show()
        end_frame = imp.getT()
        trim_imp = Duplicator().run(imp, 1, channels, 1, slices, start_frame,
                                    end_frame)
        imp.close()
        trim_imp.show()
        dup_imp = Duplicator().run(trim_imp)

        # create images to process and find bounds for
        dup_imps = ChannelSplitter().split(dup_imp)
        myo_imp = dup_imps[1]
        mem_imp = dup_imps[0]
        FileSaver(myo_imp).saveAsTiffStack(
            os.path.join(output_subfolder, "myosin_channel.tif"))
        FileSaver(mem_imp).saveAsTiffStack(
            os.path.join(output_subfolder, "membrane_channel.tif"))

        # set basal bounds
        myo_imp.show()
        ImageConverter(myo_imp).convertToGray8()
        frames = myo_imp.getNFrames()
        gb = GaussianBlur()
        for fridx in range(0, frames):
            myo_imp.setSliceWithoutUpdate(fridx + 1)
            ip = myo_imp.getProcessor()
            gb.blurGaussian(ip, 5.0, 1.0, 0.02)
            # assymmetrical Gaussian
        IJ.run(myo_imp, "Convert to Mask",
               "method=Otsu background=Dark calculate")
        IJ.run("Despeckle", "stack")
        title = myo_imp.getTitle()

        # assume that first frame is good quality image...
        basal_edges = find_basal_edges(myo_imp)
        #myo_imp.hide()
        mem_imp.hide()

        # draw some edges for checking
        roim = RoiManager()
        xs = [x for x in range(1,
                               trim_imp.getWidth() + 1)]
        trim_imp.show()
        for fridx in range(0, myo_imp.getNFrames()):
            trim_imp.setPosition(2, 1, fridx + 1)
            IJ.run("Enhance Contrast", "saturated=0.35")

            roi = PolygonRoi(xs, basal_edges[fridx], Roi.POLYLINE)
            trim_imp.setRoi(roi)
            roim.addRoi(roi)
Пример #7
0
def runOneFile(fullFilePath):
	global gFileType
	global gNumChannels
	global gAlignBatchVersion
	
	if not os.path.isfile(fullFilePath):
		bPrintLog('\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n',0)
		return 0

	bPrintLog(time.strftime("%H:%M:%S") + ' starting runOneFile(): ' + fullFilePath, 1)
	
	enclosingPath = os.path.dirname(fullFilePath)
	head, tail = os.path.split(enclosingPath)
	enclosingPath += '/'
	
	#make output folders
	destFolder = enclosingPath + tail + '_channels/'
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)
	destMaxFolder = destFolder + 'max/'
	if not os.path.isdir(destMaxFolder):
		os.makedirs(destMaxFolder)

	if gDoAlign:
		destAlignmentFolder = destFolder + 'alignment/'
		if not os.path.isdir(destAlignmentFolder):
			os.makedirs(destAlignmentFolder)
			
	if gSave8bit:
		eightBitFolder = destFolder + 'channels8/'
		if not os.path.isdir(eightBitFolder):
			os.makedirs(eightBitFolder)
		eightBitMaxFolder = eightBitFolder + 'max/'
		if not os.path.isdir(eightBitMaxFolder):
			os.makedirs(eightBitMaxFolder)
	
	if gFileType=='tif':
		# open .tif image
		imp = Opener().openImage(fullFilePath)
	else:
		# open .lsm
		cmdStr = 'open=%s autoscale color_mode=Default view=Hyperstack stack_order=XYCZT' % (fullFilePath,)
		IJ.run('Bio-Formats Importer', cmdStr)
		lsmpath, lsmfilename = os.path.split(fullFilePath)
		lsWindow = lsmfilename
		imp = WindowManager.getImage(lsWindow)
		
	# get parameters of image
	(width, height, nChannels, nSlices, nFrames) = imp.getDimensions()
	bitDepth = imp.getBitDepth()
	infoStr = imp.getProperty("Info") #get all .tif tags
	if not infoStr:
		infoStr = ''
	infoStr += 'bAlignBatch_Version=' + str(gAlignBatchVersion) + '\n'
	infoStr += 'bAlignBatch_Time=' + time.strftime("%Y%m%d") + '_' + time.strftime("%H%M%S") + '\n'
		
	msgStr = 'w:' + str(width) + ' h:' + str(height) + ' slices:' + str(nSlices) \
				+ ' channels:' + str(nChannels) + ' frames:' + str(nFrames) + ' bitDepth:' + str(bitDepth)
	bPrintLog(msgStr, 1)
	
	path, filename = os.path.split(fullFilePath)
	shortName, fileExtension = os.path.splitext(filename)

	#
	# look for num channels in ScanImage infoStr
	if gGetNumChanFromScanImage:
		for line in infoStr.split('\n'):
			#scanimage.SI4.channelsSave = [1;2]
			scanimage4 = find(line, 'scanimage.SI4.channelsSave =') == 0
			#state.acq.numberOfChannelsSave=2
			scanimage3 = find(line, 'state.acq.numberOfChannelsSave=') == 0
			if scanimage3:
				#print 'line:', line
				equalIdx = find(line, '=')
				line2 = line[equalIdx+1:]
				if gGetNumChanFromScanImage:
					gNumChannels = int(line2)
					bPrintLog('over-riding gNumChannels with: ' + str(gNumChannels), 2)
			if scanimage4:
				#print '   we have a scanimage 4 file ... now i need to exptract the number of channel'
				#print 'line:', line
				equalIdx = find(line, '=')
				line2 = line[equalIdx+1:]
				for delim in ';[]':
					line2 = line2.replace(delim, ' ')
				if gGetNumChanFromScanImage:
					gNumChannels = len(line2.split())
					bPrintLog('over-riding gNumChannels with: ' + str(gNumChannels), 2)

	# show
	imp.show()
	# split channels if necc. and grab the original window names
	if gNumChannels == 1:
		origImpWinStr = imp.getTitle() #use this when only one channel
		origImpWin = WindowManager.getWindow(origImpWinStr) #returns java.awt.Window
	
	if gNumChannels == 2:
		winTitle = imp.getTitle()
		bPrintLog('Deinterleaving 2 channels...', 1)
		IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost
		origCh1WinStr = winTitle + ' #1'
		origCh2WinStr = winTitle + ' #2'
		origCh1Imp = WindowManager.getImage(origCh1WinStr)
		origCh2Imp = WindowManager.getImage(origCh2WinStr)
		origCh1File = destFolder + shortName + '_ch1.tif'
		origCh2File = destFolder + shortName + '_ch2.tif'

	# work on a copy, mostly for alignment with cropping
	copy = Duplicator().run(imp)
	#copy.copyAttributes(imp) #don't copy attributes, it copies the name (which we do not want)
	copy.show()
	
	#
	# crop (on copy)
	if gDoCrop:
		bPrintLog('making cropping rectangle (left,top,width,height) ',1)
		bPrintLog(str(gCropLeft) + ' ' + str(gCropTop) + ' ' +str(gCropWidth) + ' ' +str(gCropHeight), 2)
		
		roi = Roi(gCropLeft, gCropTop, gCropWidth, gCropHeight) #left,top,width,height
		copy.setRoi(roi)
		
		time.sleep(0.5) # otherwise, crop SOMETIMES failes. WHAT THE F**K FIJI DEVELOPERS, REALLY, WHAT THE F**K
		
		#bPrintLog('cropping', 1)
		IJ.run('Crop')
		infoStr += 'bCropping=' + str(gCropLeft) + ',' + str(gCropTop) + ',' + str(gCropWidth) + ',' + str(gCropHeight) + '\n'
	
	#
	# remove calibration ( on original)
	if gRemoveCalibration:
		cal = imp.getCalibration()
		calCoeff = cal.getCoefficients()
		if calCoeff:
			msgStr = 'Calibration is y=a+bx' + ' a=' + str(calCoeff[0]) + ' b=' + str(calCoeff[1])
			bPrintLog(msgStr, 1)
			
			#remove calibration
			bPrintLog('\tRemoving Calibration', 2)
			imp.setCalibration(None)
				
			#without these, 8-bit conversion goes to all 0 !!! what the f**k !!!
			#bPrintLog('calling imp.resetStack() and imp.resetDisplayRange()', 2)
			imp.resetStack()
			imp.resetDisplayRange()

			#get and print out min/max
			origMin = StackStatistics(imp).min
			origMax = StackStatistics(imp).max
			msgStr = '\torig min=' + str(origMin) + ' max=' + str(origMax)
			bPrintLog(msgStr, 2)
			
			# 20150723, 'shift everybody over by linear calibration intercept calCoeff[0] - (magic number)
			if 1:
				# [1] was this
				#msgStr = 'Subtracting original min '+str(origMin) + ' from stack.'
				#bPrintLog(msgStr, 2)
				#subArgVal = 'value=%s stack' % (origMin,)
				#IJ.run('Subtract...', subArgVal)
				# [2] now this
				#msgStr = 'Adding calCoeff[0] '+str(calCoeff[0]) + ' from stack.'
				#bPrintLog(msgStr, 2)
				#addArgVal = 'value=%s stack' % (int(calCoeff[0]),)
				#IJ.run('Add...', addArgVal)
				# [3] subtract a magic number 2^15-2^7 = 32768 - 128
				magicNumber = gLinearShift #2^15 - 128
				msgStr = 'Subtracting a magic number (linear shift) '+str(magicNumber) + ' from stack.'
				bPrintLog(msgStr, 2)
				infoStr += 'bLinearShift=' + str(gLinearShift) + '\n'
				subArgVal = 'value=%s stack' % (gLinearShift,)
			IJ.run(imp, 'Subtract...', subArgVal)
				
			# 20150701, set any pixel <0 to 0
			if 0:
				ip = imp.getProcessor() # returns a reference
				pixels = ip.getPixels() # returns a reference
				msgStr = '\tSet all pixels <0 to 0. This was added 20150701 ...'
				bPrintLog(msgStr, 2)
				pixels = map(lambda x: 0 if x<0 else x, pixels)
				bPrintLog('\t\t... done', 2)
				
			#get and print out min/max
			newMin = StackStatistics(imp).min
			newMax = StackStatistics(imp).max
			msgStr = '\tnew min=' + str(newMin) + ' max=' + str(newMax)
			bPrintLog(msgStr, 2)
			
			#append calibration to info string
			infoStr += 'bCalibCoeff_a = ' + str(calCoeff[0]) + '\n'
			infoStr += 'bCalibCoeff_b = ' + str(calCoeff[1]) + '\n'
			infoStr += 'bNewMin = ' + str(newMin) + '\n'
			infoStr += 'bNewMax = ' + str(newMax) + '\n'

	#
	# set up
	if gNumChannels == 1:
		impWinStr = copy.getTitle() #use this when only one channel
		impWin = WindowManager.getWindow(impWinStr) #returns java.awt.Window
	
	if gNumChannels == 2:
		winTitle = copy.getTitle()
		bPrintLog('Deinterleaving 2 channels...', 1)
		IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost
		ch1WinStr = winTitle + ' #1'
		ch2WinStr = winTitle + ' #2'
		ch1Imp = WindowManager.getImage(ch1WinStr)
		ch2Imp = WindowManager.getImage(ch2WinStr)
		ch1File = destFolder + shortName + '_ch1.tif'
		ch2File = destFolder + shortName + '_ch2.tif'
		
	#
	# alignment
	if gDoAlign and gNumChannels == 1 and copy.getNSlices()>1:
		infoStr += 'AlignOnChannel=1' + '\n'
		#snap to middle slice
		if gAlignOnMiddleSlice:
			middleSlice = int(math.floor(copy.getNSlices() / 2)) #int() is necc., python is f*****g picky
		else:
			middleSlice = gAlignOnThisSlice
		copy.setSlice(middleSlice)
		
		transformationFile = destAlignmentFolder + shortName + '.txt'
		
		bPrintLog('MultiStackReg aligning:' + impWinStr, 1)
		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)
		infoStr += 'AlignOnSlice=' + str(middleSlice) + '\n'

		#20150723, we just aligned on a cropped copy, apply alignment to original imp
		origImpTitle = imp.getTitle()
		stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(origImpTitle,transformationFile)
		IJ.run('MultiStackReg', stackRegParams)		
		
	if gDoAlign and gNumChannels == 2 and ch1Imp.getNSlices()>1 and ch2Imp.getNSlices()>1:
		#apply to gAlignThisChannel
		alignThisWindow = ''
		applyAlignmentToThisWindow = ''
		if gAlignThisChannel == 1:
			infoStr += 'AlignOnChannel=1' + '\n'
			transformationFile = destAlignmentFolder + shortName + '_ch1.txt'
			alignThisWindow = ch1WinStr
			applyAlignmentToThisWindow = ch2WinStr
		else:
			infoStr += 'AlignOnChannel=2' + '\n'
			transformationFile = destAlignmentFolder + shortName + '_ch2.txt'
			alignThisWindow = ch2WinStr
			applyAlignmentToThisWindow = ch1WinStr
	
		alignThisImp = WindowManager.getImage(alignThisWindow)
		#snap to middle slice
		if gAlignOnMiddleSlice:
			middleSlice = int(math.floor(alignThisImp.getNSlices() / 2)) #int() is necc., python is f*****g picky
		else:
			middleSlice = gAlignOnThisSlice
		alignThisImp.setSlice(middleSlice)

		infoStr += 'bAlignOnSlice=' + str(middleSlice) + '\n'
		
		bPrintLog('MultiStackReg aligning:' + alignThisWindow, 1)
		stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' %(alignThisWindow,transformationFile)
		IJ.run('MultiStackReg', stackRegParams)
	
		# 20150723, we just aligned on a copy, apply alignment to both channels of original
		# ch1
		bPrintLog('MultiStackReg applying alignment to:' + origCh1WinStr, 1)
		stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(origCh1WinStr,transformationFile)
		IJ.run('MultiStackReg', stackRegParams)		
		# ch2
		bPrintLog('MultiStackReg applying alignment to:' + origCh2WinStr, 1)
		stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(origCh2WinStr,transformationFile)
		IJ.run('MultiStackReg', stackRegParams)		
		
		#apply alignment to other window
		#bPrintLog('MultiStackReg applying alignment to:' + applyAlignmentToThisWindow, 1)
		#applyAlignThisImp = WindowManager.getImage(applyAlignmentToThisWindow)
		#stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(applyAlignmentToThisWindow,transformationFile)
		#IJ.run('MultiStackReg', stackRegParams)		
	elif gDoAlign:
		bPrintLog('Skipping alignment, there may be only one slice?',3)
						
	#
	# save
	if gNumChannels == 1:
		imp.setProperty("Info", infoStr);
		impFile = destFolder + shortName + '.tif'
		#bPrintLog('Saving:' + impFile, 1)
		bSaveStack(imp, impFile)
		#max project
		bSaveZProject(imp, destMaxFolder, shortName)

	if gNumChannels == 2:
		#ch1
		origCh1Imp.setProperty("Info", infoStr);
		#bPrintLog('Saving:' + ch1File, 1)
		bSaveStack(origCh1Imp, ch1File)
		#max project
		bSaveZProject(origCh1Imp, destMaxFolder, shortName+'_ch1')

		#ch2
		origCh2Imp.setProperty("Info", infoStr);
		#bPrintLog('Saving:' + ch2File, 1)
		bSaveStack(origCh2Imp, ch2File)
 		#max project
		bSaveZProject(origCh2Imp, destMaxFolder, shortName+'_ch2')
		
 	#
	# post convert to 8-bit and save
	if gSave8bit:
		if bitDepth == 16:
			if gNumChannels == 1:
				bPrintLog('Converting to 8-bit:' + impWinStr, 1)
				IJ.selectWindow(impWinStr)
				#IJ.run('resetMinAndMax()')
				IJ.run("8-bit")
				impFile = eightBitFolder + shortName + '.tif'
				bPrintLog('Saving 8-bit:' + impFile, 2)
				bSaveStack(imp, impFile)
				#max project
				bSaveZProject(imp, eightBitMaxFolder, shortName)
				
			if gNumChannels == 2:
				#
				bPrintLog('Converting to 8-bit:' + origCh1WinStr, 1)
				IJ.selectWindow(origCh1WinStr)
				
				IJ.run("8-bit")
				impFile = eightBitFolder + shortName + '_ch1.tif'
				bPrintLog('Saving 8-bit:' + impFile, 2)
				bSaveStack(origCh1Imp, impFile)
				#max project
				bSaveZProject(origCh1Imp, eightBitMaxFolder, shortName+'_ch1')

				#
				bPrintLog('Converting to 8-bit:' + origCh2WinStr, 1)
				IJ.selectWindow(origCh2WinStr)
				#IJ.run('resetMinAndMax()')
				IJ.run("8-bit")
 				impFile = eightBitFolder + shortName + '_ch2.tif'
				bPrintLog('Saving 8-bit:' + impFile, 2)
				bSaveStack(origCh2Imp, impFile)
				#max project
				bSaveZProject(origCh2Imp, eightBitMaxFolder, shortName+'_ch2')
				
	#
	# close original window
	imp.changes = 0
	imp.close()
	#copy
	copy.changes = 0
	copy.close()

	#
	# close ch1/ch2
	if gNumChannels == 2:
		#original
		origCh1Imp.changes = 0
		origCh1Imp.close()
		origCh2Imp.changes = 0
		origCh2Imp.close()
		#copy
		ch1Imp.changes = 0
		ch1Imp.close()
		ch2Imp.changes = 0
		ch2Imp.close()

	bPrintLog(time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath, 1)
Пример #8
0
def do_angular_projection(imp,
                          max_r_pix=60,
                          min_r_pix=10,
                          generate_roi_stack=True):
    """perform ray-based projection of vessel wall, c.f. ICY TubeSkinner (Lancino 2018)"""
    Prefs.blackBackground = True
    print("do angular projection input imp = " + str(imp))
    split_chs = ChannelSplitter().split(imp)
    mch_imp = split_chs[0]
    IJ.setAutoThreshold(mch_imp, "IsoData dark stack")
    egfp_imp = split_chs[1]
    proj_imp = Duplicator().run(egfp_imp)
    cl_imp = split_chs[2]
    if generate_roi_stack:
        egfp_imp_disp = Duplicator().run(egfp_imp)
        roi_stack = IJ.createImage("rois", egfp_imp.getWidth(),
                                   egfp_imp.getHeight(), egfp_imp.getNSlices(),
                                   16)

    centres = []
    projected_im_pix = []
    ring_rois = []
    for zidx in range(cl_imp.getNSlices()):
        if ((zidx + 1) % 100) == 0:
            print("Progress = " +
                  str(round(100 * (float(zidx + 1) / cl_imp.getNSlices()))))
        projected_im_row = []
        proj_imp.setZ(zidx + 1)
        mch_imp.setZ(zidx + 1)
        bp = mch_imp.createThresholdMask()
        bp.dilate()
        bp.erode()
        bp.erode()
        bp.erode()
        mask_imp = ImagePlus("mask", bp)
        IJ.run(mask_imp, "Create Selection", "")
        roi = mask_imp.getRoi()
        proj_imp.setRoi(roi)
        IJ.run(proj_imp, "Set...", "value=0 slice")
        IJ.run(proj_imp, "Make Inverse", "")
        roi = proj_imp.getRoi()
        centre = (roi.getStatistics().xCentroid, roi.getStatistics().yCentroid)
        centres.append(centre)
        ring_roi_xs = []
        ring_roi_ys = []
        for theta in range(360):
            pt1 = (centre[0] + min_r_pix * math.cos(math.radians(theta)),
                   centre[1] + min_r_pix * math.sin(math.radians(theta)))
            pt2 = (centre[0] + max_r_pix * math.cos(math.radians(theta)),
                   centre[1] + max_r_pix * math.sin(math.radians(theta)))
            roi = Line(pt1[0], pt1[1], pt2[0], pt2[1])
            proj_imp.setRoi(roi)
            profile = roi.getPixels()
            projected_im_row.append(max(profile))
            try:
                ring_roi_xs.append(roi.getContainedPoints()[profile.index(
                    max(profile))].x)
            except IndexError:
                ring_roi_xs.append(pt2[0])
            try:
                ring_roi_ys.append(roi.getContainedPoints()[profile.index(
                    max(profile))].y)
            except IndexError:
                ring_roi_ys.append(pt2[1])
            proj_imp.killRoi()
        ring_roi = PolygonRoi(ring_roi_xs, ring_roi_ys, Roi.FREELINE)
        ring_rois.append(ring_roi)
        if generate_roi_stack:
            roi_stack.setZ(zidx + 1)
            roi_stack.setRoi(ring_roi)
            IJ.run(roi_stack, "Line to Area", "")
            IJ.run(
                roi_stack, "Set...",
                "value=" + str(roi_stack.getProcessor().maxValue()) + " slice")
        #egfp_imp.setRoi(ring_roi);
        projected_im_pix.append(projected_im_row)


#	for ch in split_chs:
#		ch.close();

    out_imp = ImagePlus(
        "projected", FloatProcessor([list(x) for x in zip(*projected_im_pix)]))

    if generate_roi_stack:
        roi_stack.show()
        egfp_imp_disp.show()
        # merge?
    else:
        roi_stack = None
    return out_imp, roi_stack, ring_rois, centres
def generate_background_rois(input_mask_imp,
                             params,
                             membrane_edges,
                             dilations=5,
                             threshold_method=None,
                             membrane_imp=None):
    """automatically identify background region based on auto-thresholded image, existing membrane edges and position of midpoint anchor"""
    if input_mask_imp is None and membrane_imp is not None:
        segmentation_imp = Duplicator().run(membrane_imp)
        # do thresholding using either previous method if threhsold_method is None or using (less conservative?) threshold method
        if (threshold_method is None
                or not (threshold_method in params.listThresholdMethods())):
            mask_imp = make_and_clean_binary(segmentation_imp,
                                             params.threshold_method)
        else:
            mask_imp = make_and_clean_binary(segmentation_imp,
                                             threshold_method)
        segmentation_imp.close()
    else:
        input_mask_imp.killRoi()
        mask_imp = Duplicator().run(input_mask_imp)

    rois = []
    IJ.setForegroundColor(0, 0, 0)
    roim = RoiManager(True)
    rt = ResultsTable()

    for fridx in range(mask_imp.getNFrames()):
        mask_imp.setT(fridx + 1)
        # add extra bit to binary mask from loaded membrane in case user refined edges...
        # flip midpoint anchor across the line joining the two extremes of the membrane,
        # and fill in the triangle made by this new point and those extremes
        poly = membrane_edges[fridx].getPolygon()
        l1 = (poly.xpoints[0], poly.ypoints[0])
        l2 = (poly.xpoints[-1], poly.ypoints[-1])
        M = (0.5 * (l1[0] + l2[0]), 0.5 * (l1[1] + l2[1]))
        Mp1 = (params.manual_anchor_midpoint[0][0] - M[0],
               params.manual_anchor_midpoint[0][1] - M[1])
        p2 = (M[0] - Mp1[0], M[1] - Mp1[1])
        new_poly_x = list(poly.xpoints)
        new_poly_x.append(p2[0])
        new_poly_y = list(poly.ypoints)
        new_poly_y.append(p2[1])
        mask_imp.setRoi(PolygonRoi(new_poly_x, new_poly_y, PolygonRoi.POLYGON))
        IJ.run(mask_imp, "Fill", "slice")
        mask_imp.killRoi()

        # now dilate the masked image and identify the unmasked region closest to the midpoint anchor
        ip = mask_imp.getProcessor()
        dilations = 5
        for d in range(dilations):
            ip.dilate()
        ip.invert()
        mask_imp.setProcessor(ip)
        mxsz = mask_imp.getWidth() * mask_imp.getHeight()
        pa = ParticleAnalyzer(
            ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.SHOW_PROGRESS,
            ParticleAnalyzer.CENTROID, rt, 0, mxsz)
        pa.setRoiManager(roim)
        pa.analyze(mask_imp)
        ds_to_anchor = [
            math.sqrt((x - params.manual_anchor_midpoint[0][0])**2 +
                      (y - params.manual_anchor_midpoint[0][1])**2)
            for x, y in zip(
                rt.getColumn(rt.getColumnIndex("X")).tolist(),
                rt.getColumn(rt.getColumnIndex("Y")).tolist())
        ]
        if len(ds_to_anchor) > 0:
            roi = roim.getRoi(ds_to_anchor.index(min(ds_to_anchor)))
            rois.append(roi)
        else:
            rois.append(None)
        roim.reset()
        rt.reset()
    roim.close()
    mask_imp.close()
    return rois
Пример #10
0
	def __addroi(self, event) :
		if ( not self.__init) : 
			IJ.showMessage("", "please start a new stack")
			return
		if ( not self.__initDIA) :
			IJ.showMessage("", "please select an image for DIA")
			return

		if ( not self.__initFLUO) :
			IJ.showMessage("", "please select an image for FLUO")
			return

		twres = TextWindow("measures-"+self.__name, "label\tname\tsol\tarea\tcirc\tAR\tFeret\taxis\traf\tdMajor\tdFeret\tdArea", "", 300, 450)
		tab="\t"
		
		self.__widthl = self.__display2.getText()
		IJ.selectWindow(self.__impF.getTitle())

		self.__rm = RoiManager.getInstance()
		if (self.__rm==None): self.__rm = RoiManager()

		if self.__impF.getImageStackSize() > 1 :
			roisarray =[(roi, self.__rm.getSliceNumber(roi.getName())) for roi in self.__rm.getRoisAsArray()]
		else : 
			roisarray =[(roi, 1) for roi in self.__rm.getRoisAsArray()]
			
		self.__rm.runCommand("reset")
		#self.__rm.runCommand("Delete")
		IJ.selectWindow(self.__impF.getTitle())

		self.__maxraf=float(self.__display19.text)
		self.__minraf=float(self.__display20.text)

		count=1

		for roielement in roisarray :
			roi = roielement[0]
			pos = roielement[1]
			lab = self.__impF.getImageStack().getShortSliceLabel(pos)

			if lab==None : lab=str(pos)
			
			if self.__conEllipses :
				IJ.selectWindow(self.__impF.getTitle())
				self.__impF.setSlice(pos)
				self.__impF.setRoi(roi)
				self.__rm.runCommand("Add")
				IJ.run(self.__impF,  "Fit Ellipse", "")
				ellipse=self.__impF.getRoi()
				params = ellipse.getParams()
				ferets = ellipse.getFeretValues()
				imp2 = Duplicator().run(self.__impF,pos,pos)
				IJ.run(imp2, "Rotate... ", "angle="+str(ferets[1])+" grid=0 interpolation=Bilinear enlarge slice")
				temproi=Roi((imp2.getWidth()-ferets[0])/2.0,(imp2.getHeight()-ferets[2])/2.0,ferets[0],ferets[2])
				imp2.setRoi(temproi)
				imp3 = Duplicator().run(imp2,1,1)
				ip3=imp3.getProcessor()

				if int(self.__display5.text) < ip3.getWidth() < int(self.__display6.text) : 
					self.__iplist.append(ip3)
					self.__display.text = self.__name + " cell " + str(len(self.__iplist))
					fer=Line(params[0],params[1],params[2],params[3])
					self.__cellsrois.append((fer, pos))
					self.__labels.append(self.__isF.getShortSliceLabel(pos))

				m=Morph(self.__impF, roi)

				twres.append(lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(fer.getLength())+tab+str(1)+tab+str(0)+tab+str(0)+tab+str(0))
				self.__dictCells[count]=(str(roi.getName()), lab, roi)
				count=count+1
				continue
			
			if roi.getType() in [6,7] : 
				self.__impF.setSlice(pos)
				self.__impF.setRoi(roi)
				self.__rm.runCommand("Add")

			elif roi.getType() in [2,4] :
				self.__impF.setSlice(pos)
				self.__impF.setRoi(roi)
				m=Morph(self.__impF, roi)
				m.setMidParams(10, 2)
				midroi=m.MidAxis
				if midroi == None : continue

				raf = m.MaxFeret/midroi.getLength()
				
				if (self.__maxraf < raf) or (raf < self.__minraf) : continue

				maxsol = float(self.__display7.text)
				minsol = float(self.__display8.text)
				maxarea = float(self.__display9.text)
				minarea = float(self.__display10.text)
				maxcirc = float(self.__display11.text)
				mincirc = float(self.__display12.text)
				maxar = float(self.__display13.text)
				minar = float(self.__display14.text)
				maxfer = float(self.__display15.text)
				minfer = float(self.__display16.text)
				maxmean = float(self.__display17.text)
				minmean = float(self.__display18.text)
				maxmferet = float(self.__display21.text)
				minmferet = float(self.__display22.text)

				testsol = (minsol<= m.Solidity <= maxsol)
				testarea = (minarea<= m.Area <= maxarea)
				testcirc = (mincirc<= m.Circ <= maxcirc)
				testar = (minar<= m.AR <= maxar)
				testfer = (minfer<= m.MaxFeret <= maxfer)
				testmean = (minmean <= m.Mean <= maxmean)
				testmferet = (minmferet <= m.MinFeret <= maxmferet)
				
				#print minmferet , m.MinFeret , maxmferet

				test = (testsol+testarea+testcirc+testar+testfer+testmean+testmferet)/7	

				if test : 				
					fmaj, ffmx, fa =[],[],[]
					for r in m.getMidSegments(10, 40, 0)[0] :
						if r == None : continue
						m2=Morph(self.__impF, r)
						fmaj.append(m2.Major)
						ffmx.append(m2.MaxFeret)
						fa.append(m2.Area)

					diffmajor, diffferet, diffarea = 0,0,0
					
					if len(fa) > 4 :
						medfmaj = self.listmean(fmaj[1:-1])
						medffmx = self.listmean(ffmx[1:-1])
						medfa   = self.listmean(fa[1:-1])

						diffmajor = (max(fmaj[1:-1])-medfmaj)/medfmaj
						diffferet = (max(ffmx[1:-1])-medffmx)/medffmx
						diffarea = (max(fa[1:-1])-medfa)/medfa

					twres.append(lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(midroi.getLength())+tab+str(m.MaxFeret/midroi.getLength())+tab+str(diffmajor)+tab+str(diffferet)+tab+str(diffarea))
					#print lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(midroi.getLength())+tab+str(m.MaxFeret/midroi.getLength())+tab+str(diffmajor)+tab+str(diffferet)+tab+str(diffarea)

					self.__impF.setRoi(roi)
					self.__rm.runCommand("Add")
					self.__impF.killRoi()
					self.__impF.setRoi(midroi)
					
					#self.__dictCells[str(roi.getName())]=(str(roi.getName()), lab, roi)
					self.__dictCells[count]=(str(roi.getName()), lab, roi)
					count=count+1
					
				else : 
					#print "test falls"
					continue

			else : 
				print "out loop"
				continue
			
			straightener = Straightener()
			new_ip = straightener.straighten(self.__impF, midroi, int(self.__widthl))
			if int(self.__display5.text) < new_ip.getWidth() < int(self.__display6.text) : 
				self.__iplist.append(new_ip.convertToShort(False))
				self.__display.text = self.__name + " cell " + str(len(self.__iplist))
				#print "add", roi.getName(), roi.getType()
				self.__cellsrois.append((midroi, pos))
				self.__labels.append(self.__isF.getShortSliceLabel(pos))


		#roisarray=self.__rm.getRoisAsArray()		
		#self.__rm.runCommand("reset")
		#self.__rm.runCommand("Delete")
		

		self.__impD.killRoi()
		self.__impF.killRoi()
		IJ.selectWindow(self.__impD.getTitle())