Exemple #1
0
    def newVideoStack(self, imageData, videoHeader):
        """
		imageData: numpy image
		videoHeader: dict with (motor, um widht/height, date/time)
		"""
        print('bCanvas.newVideoStack() imageData:', imageData.shape,
              'videoHeader:', videoHeader)

        # strip down imageData
        if len(imageData.shape) == 2:
            # ok
            pass
        elif len(imageData.shape) == 3:
            # assume last axis is r/g/b planes
            imageData = imageData[:, :, 0]

        xPixels, yPixels = imageData.shape

        # make _video folder if necc
        if not os.path.isdir(self.videoFolderPath):
            os.mkdir(self.videoFolderPath)

        # construct file path/name and save
        numVideoFiles = len(self.videoFileList)
        fileNumStr = str(numVideoFiles).zfill(3)
        saveVideoFile = 'v' + self.enclosingFolder + '_' + fileNumStr + '.tif'
        saveVideoPath = os.path.join(self.videoFolderPath, saveVideoFile)

        # fill in more of header
        videoHeader['bitDepth'] = 8
        videoHeader['xVoxel'] = videoHeader['umHeight'] / xPixels
        videoHeader['yVoxel'] = videoHeader['umWidth'] / yPixels
        videoHeader['zVoxel'] = 1
        videoHeader['unit'] = 'um'

        # save stack
        bimpy.util.bTiffFile.imsave(saveVideoPath,
                                    imageData,
                                    tifHeader=videoHeader)

        # load as bStack
        newVideoStack = bimpy.bStack(saveVideoPath, loadImages=True)

        # append to list
        self.appendVideo(newVideoStack)

        # save canvas file
        self.save()

        return newVideoStack
Exemple #2
0
def convert(path):

    headerList = []  # used to generate one csv file for folder

    tmpPath, enclosingFolder = os.path.split(path)

    with javabridge.vm(run_headless=True, class_path=bioformats.JARS):

        # turn off logging, see:
        # ./bStack_env/lib/python3.7/site-packages/bioformats/log4j.py
        log4j = javabridge.JClassWrapper("loci.common.Log4jTools")
        log4j.enableLogging()
        log4j.setRootLevel("WARN")

        # build a list of oir header dictionaries
        for file in sorted(os.listdir(path)):
            if file.startswith('.'):
                continue
            if file.endswith('.oir'):

                filePath = os.path.join(path, file)

                myStack = bStack(filePath)
                myStack.loadHeader()
                myStack.header.prettyPrint()  # print to command line
                headerList.append(myStack.header.header
                                  )  # used to generate one csv file for folder

                # save the .txt file
                baseFileName = os.path.basename(file)
                baseFileName, ext = baseFileName.split('.')
                textFilePath = os.path.join(path, baseFileName + '.txt')
                with open(textFilePath, 'w') as textFile:
                    textFile.write(myStack.header.getMetaData())
        #
        # generate one file with one row for each oir header
        if len(headerList) > 0:
            outFilePath = os.path.join(path, enclosingFolder + '.csv')
            with open(outFilePath, 'w') as outFile:
                print('saving file:', outFilePath)
                for idx, header in enumerate(headerList):
                    if idx == 0:
                        columnNames = ''
                        for k, v in header.items():
                            columnNames += k + ','
                        outFile.write(columnNames + '\n')
                    for k, v in header.items():
                        outFile.write(str(v) + ',')
                    outFile.write('\n')
Exemple #3
0
def main(path):
    myStack = bimpy.bStack(path, loadImages=False, loadTracing=True)

    app = QtWidgets.QApplication(sys.argv)
    '''
	print(2)
	myPlot = bPyQtPlot(None, myStack)
	myPlot.show()
	'''

    myPlotWidget = bScatterPlotWidget(myStack, None)
    myPlotWidget.show()

    print(3)
    sys.exit(app.exec_())  # this will loop
Exemple #4
0
def main(path):
    myStack = bimpy.bStack(path, loadImages=False, loadTracing=True)

    app = QtWidgets.QApplication(sys.argv)
    '''
	print(2)
	myPlot = bPyQtPlot(None, myStack)
	myPlot.show()
	'''

    #myPlotWidget = bCaimanPlotWidget(parent=None, stackObject=myStack)
    myPlotWidget = bCaimanPlotWidget0(parent=None, stackObject=myStack)
    myPlotWidget.show()

    sys.exit(app.exec_())  # this will loop
Exemple #5
0
	def loadFolder(self):
		for file in sorted(os.listdir(self.folderPath)):
			if file.startswith('.'):
				continue
			try:
				fileExtension = file.split('.')[1]
			except: #IndexError
				continue
			if fileExtension in acceptableExtensions:
				fullStackPath = os.path.join(self.folderPath, file)
				print('fullStackPath:', fullStackPath)

				newStack = bStack(fullStackPath, loadImages=False)
				newStack.loadHeader()

				self.stackList.append(newStack)

				newStack.header.prettyPrint()
Exemple #6
0
            this_lpMinList[idx] = one_lpMin
            this_lpMaxList[idx] = one_lpMax
            this_lpSNRList[idx] = one_lpSNR
            #self.d2[slabIdx] = retDict['diam']

    #print('  done my_mpWorker() edgeIdx:', edgeIdx)
    return edgeIdx, slabIdxList, thisDiamList, this_lpMinList, this_lpMaxList, this_lpSNRList


if __name__ == '__main__':

    path = '/home/cudmore/data/nathan/SAN4/aicsAnalysis/testing/SAN4_tail_ch2.tif'
    channelToAnalyze = 2

    # load the stack
    myStack = bimpy.bStack(path=path, loadImages=True, loadTracing=True)

    #
    # test worker
    '''
	global gStackObject
	gStackObject = myStack
	detectionDict = myStack.myLineProfile.getDefaultDetectionParams()
	detectionDict['displayThisStack'] = channelToAnalyze
	#
	edgeIdx = 5
	my_mpWorker(edgeIdx, detectionDict)
	'''

    runDiameterPool(myStack, channelToAnalyze)
Exemple #7
0
        #xArray = np.array(xList)
        #intensityProfileList = np.array(intensityProfileList)
        #fwhm = np.array(fwhm)
        return np.asarray(xList), np.asarray(intensityProfileList), np.asarray(
            fwhmList)

    def euclideanDistance(self, pnt1, pnt2):
        """
		given 2d/3d points, return the straight line (euclidean) distance btween them

		remeber, this is not accurate for 3d points as our Z is huge in scanning microscopy!!!
		"""
        if len(pnt1) == 2:
            return math.sqrt((pnt1[0] - pnt2[0])**2 + (pnt1[1] - pnt2[1])**2)
        elif len(pnt1) == 3:
            return math.sqrt((pnt1[0] - pnt2[0])**2 + (pnt1[1] - pnt2[1])**2 +
                             +(pnt1[2] - pnt2[2])**2)


if __name__ == '__main__':
    import bimpy
    path = '/Users/cudmore/box/data/nathan/EC-GCaMP-Test-20190920/ach-analysis/ach-aligned-8bit.tif'
    path = '/Users/cudmore/box/data/nathan/EC-GCaMP-Test-20190920/ach-analysis/ach-aligned-8bit-short2.tif'
    bs = bimpy.bStack(path)
    ba = bAnalysis(bs)
    slice = 0
    src = [0, 0]
    dst = [100, 100]
    ans = ba.lineProfile(slice, src, dst, linewidth=2)
    print('ans:', ans)
Exemple #8
0
    def load(self, thisFile=None):
        """
		Load a saved Python canvas

		todo: there should be some fields in saved json that are global to the canvas
		for example, window position
		"""
        #loadFilePath = os.path.join(self._folderPath, self.enclosingFolder + '_canvas.txt')

        print('=== bCanvas.load() thisFile:', thisFile)

        if thisFile is not None:
            if os.path.isfile(thisFile):
                self._filePath = thisFile
                self._folderPath, tmpFilename = os.path.split(self._filePath)
                with open(self._filePath) as f:
                    data = json.load(f)
            else:
                print('Warning: bCanvasApp.load() did not load thisFile:',
                      thisFile)
                return
        '''
		print(' ')
		print ('bCanvas.load() loaded:')
		print('data:', json.dumps(data, indent=4))
		'''

        # iterate through keys in data and take action
        # e.g. ('canvasOptions', 'videofiles', 'scopefiles')
        for key, item in data.items():
            #print(key,item)
            if key == 'canvasOptions':
                print('bCanvas.load() key:', key, 'item:', item)
            elif key == 'videoFiles':
                for fileName, fileDict in item.items():
                    videoFilePath = os.path.join(self.videoFolderPath,
                                                 fileName)
                    print('  bCanvas.load() is loading videoFilePath:',
                          videoFilePath)
                    videoStack = bimpy.bStack(videoFilePath, loadImages=True)

                    for headerStr, headerValue in fileDict.items():
                        if headerStr in videoStack.header.header.keys():
                            videoStack.header.header[headerStr] = headerValue
                        else:
                            # todo: put this back in
                            #print('warning: bCanvas.load() did not find VideoFile key "' + headerStr + '" in file', fileName)
                            videoStack.header.header[headerStr] = headerValue
                    #videoStack.printHeader()
                    # append to list
                    self._videoFileList.append(videoStack)

            elif key == 'scopeFiles':
                for fileName, fileDict in item.items():
                    #folderPath = fileDict['folderPath'] # to load from folder
                    scopeFilePath = os.path.join(self._folderPath, fileName)
                    print('  bCanvas.load() is loading scopeFilePath:',
                          scopeFilePath)

                    # todo: we need to load from folder

                    # folderPath will trump scopeFilePath
                    scopeStack = bimpy.bStack(scopeFilePath, loadImages=False)
                    scopeStack.loadMax()

                    for headerStr, headerValue in fileDict.items():
                        if headerStr in scopeStack.header.header.keys():
                            # don't do this
                            scopeStack.header.header[headerStr] = headerValue
                            pass
                        else:
                            # todo: put this back in
                            #print('warning: bCanvas.load() did not find ScopeFile key "' + headerStr + '" in file', fileName)
                            scopeStack.header.header[headerStr] = headerValue
                    #scopeStack.printHeader()

                    # append to list
                    self._scopeFileList.append(scopeStack)
Exemple #9
0
    def old_buildFromScratch(self, folderPath=''):
        """
		Given a folder path, build canvas from scratch
		"""
        if len(folderPath) > 0:
            self._folderPath = folderPath
        if not os.path.isdir(self._folderPath):
            # error
            print('error: bCanvas.buildFromScratch() did not find folderPath:',
                  self._folderPath)

        #
        # video
        self._videoFileList = []

        videoFolderPath = self.videoFolderPath
        for videoFile in sorted(os.listdir(videoFolderPath)):
            if videoFile.startswith('.'):
                continue
            videoFilePath = os.path.join(videoFolderPath, videoFile)
            if not os.path.isfile(videoFilePath):
                continue

            print('bCanvas.buildFromScratch() videoFilePath:', videoFilePath)
            #videoTif = self.openVideoFile(videoFilePath)
            # 20190708, was this
            #videoFile = bVideoFile(self, videoFilePath)
            videoFile = bimpy.bStack(videoFilePath)
            videoFile.loadHeader()  # at least makes default bStackHeader()
            #videoFile.getHeaderFromDict(self.import_stackDict)
            videoFile.header.importVideoHeaderFromIgor(self.import_stackDict)
            videoFile.loadStack()
            # this is only for import from igor
            # append to list
            self._videoFileList.append(videoFile)

        #
        # scope
        self._scopeFileList = []

        possibleImageFiles = ['.tif', '.oir']

        for scopeFile in sorted(os.listdir(self._folderPath)):
            if scopeFile.startswith('.'):
                continue

            baseScopeFileName, fileExtension = os.path.splitext(scopeFile)
            if fileExtension not in possibleImageFiles:
                continue

            scopeFilePath = os.path.join(self._folderPath, scopeFile)

            if not os.path.isfile(scopeFilePath):
                continue

            #print('bCanvas.buildFromScratch() scopeFilePath:', scopeFilePath)
            tmpStack = bimpy.bStack(scopeFilePath, loadImages=False)
            tmpStack.loadHeader()

            #print('tmpStack.header.prettyPrint():', tmpStack.header.prettyPrint())
            #print('tmpStack.header.getMetaData():', tmpStack.header.getMetaData())

            #if scopeFile in fakeMotorPositons.keys():
            baseScopeFileName = 'X' + baseScopeFileName
            print('baseScopeFileName:', baseScopeFileName)
            if baseScopeFileName in self.import_stackDict.keys():
                print(
                    '   **************** bCanvas.buildFromScratch() is adding motor position to header [[[FAKE DATA]]]'
                )
                tmpStack.header.header['xMotor'] = self.import_stackDict[
                    baseScopeFileName].header['xMotor']
                tmpStack.header.header['yMotor'] = self.import_stackDict[
                    baseScopeFileName].header['yMotor']
                #tmpStack.header.header['xMotor'] = fakeMotorPositons[scopeFile]['xMotor']
                #tmpStack.header.header['yMotor'] = fakeMotorPositons[scopeFile]['yMotor']
            else:
                print('   WARNING: scopeFile', baseScopeFileName,
                      'does not have an x/y motor position')

            self._scopeFileList.append(tmpStack)
Exemple #10
0
    def importNewScopeFiles(self, watchDict=None):
        """
		look through files in our hard-drive folder and look for new files.
		A new file is one that is not already in self.scopeFileList

		watchDict: dictionary mapping file name to x/y/z motor position
					passed when we are on Olympus

		Return list of files/folders we imported
		"""
        newStackList = []  # build a list of new files
        listDir = os.listdir(self._folderPath)
        theseFileExtensions = ['.tif', '.oir']

        print('bCanvas.importNewScopeFiles()')
        print('  Looking in self._folderPath:', self._folderPath)
        print('  looking for files ending in theseFileExtensions:',
              theseFileExtensions)

        for potentialNewFile in listDir:
            tmpFile, fileExt = os.path.splitext(potentialNewFile)

            # adding option to load from folder of .tif
            folderPath = ''
            potentialFolder = os.path.join(self._folderPath, tmpFile)
            if os.path.isdir(potentialFolder):
                # todo: make this more precise like <canvas>_video
                videoFolderPath = self.videoFolderPath  # todo: stop using properties !!!
                tmpVideoFolderPath, videoFolderName = os.path.split(
                    videoFolderPath)
                #if potentialFolder.endswith('_video'):
                if tmpFile == videoFolderName:
                    # don't load _video folder
                    continue
                if tmpFile == 'max':
                    # don't load max folder
                    continue
                print('  tmpFile is a folder, potentialFolder:',
                      potentialFolder)
                # load from folder of tif
                fileList = glob.glob(potentialFolder + '/*.tif')
                fileList = sorted(fileList)
                if len(fileList) == 0:
                    print('  did not find any .tif files in folder:',
                          potentialFolder)
                    continue
                #folderPath = potentialFolder
                #potentialNewFile = fileList[0]
                print('  loading from folder potentialNewFile:',
                      potentialNewFile)
            # was this
            elif not fileExt in theseFileExtensions:
                continue
            #if not potentialNewFile.endswith(thisFileExtension):
            #	continue
            print('  bCanvas.importNewScopeFiles() considering file:',
                  potentialNewFile)  # check if file is in self.scopeFileList
            isInList = False
            for loadedScopeFile in self.scopeFileList:
                if loadedScopeFile.getFileName() == potentialNewFile:
                    print(
                        '    already in self.scopeFileList, potentialNewFile:',
                        potentialNewFile)
                    isInList = True
                    break
            if not isInList:
                # found a file that is not in scopeFileList
                # we need to find it in bLogFilePosition
                print('   New file:', potentialNewFile,
                      'find it in bLogFilePosition')
                newFilePath = os.path.join(self._folderPath, potentialNewFile)

                # load stack with images and save max
                newScopeStack = bimpy.bStack(newFilePath, loadImages=True)
                newScopeStack.saveMax()

                # abb removed southwest
                # try and flip any/all motor in display widget?
                '''
				if self.myCanvasWidget.myCanvasApp.xyzMotor.swapxy:
					tmp = newScopeStack.header.header['xMotor']
					newScopeStack.header.header['xMotor'] = newScopeStack.header.header['yMotor']
					newScopeStack.header.header['yMotor'] = tmp
				'''
                '''
				print('FAKE MOTOR POSITION FOR mp285')
				newScopeStack.header.header['xMotor'] = -2235
				newScopeStack.header.header['yMotor'] = -844.56
				'''

                # append to header
                # todo: on windows use os.path.getctime(path_to_file)
                # see: https://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python
                cTime = os.path.getctime(newFilePath)
                dateStr = time.strftime('%Y%m%d', time.localtime(cTime))
                timeStr = time.strftime('%H:%M:%S', time.localtime(cTime))
                newScopeStack.header.header[
                    'date'] = dateStr  #time.strftime('%Y%m%d')
                newScopeStack.header.header[
                    'time'] = timeStr  #datetime.now().strftime("%H:%M:%S.%f")[:-4]
                newScopeStack.header.header['seconds'] = cTime  #time.time()
                print('   newScopeStack:', newScopeStack.print())

                # get motor position from dict
                if watchDict is not None:
                    print(
                        '\n   when we are watching a folder, get motor position from myLogFilePositon'
                    )
                    print(
                        '  bCanvas.importNewScopeFiles is getting x/y motor for potentialNewFile:',
                        potentialNewFile)
                    print('  watchDict:', watchDict)
                    #xPos, yPos = self.myCanvasWidget.myLogFilePositon.getFilePositon(potentialNewFile)
                    # zPos is ignored on olympus (it is controlled by olympus software)
                    xPos, yPos, zPos = self.getFilePositon(
                        watchDict, potentialNewFile)
                    print('  got xPos:', xPos, 'yPos:', yPos)
                    if xPos is None or yPos is None:
                        print(
                            '\n\nCRITICAL ERROR IN bCanvas.import newScopeFile()\n\n'
                        )
                    if xPos is not None and yPos is not None:
                        newScopeStack.header.header['xMotor'] = xPos
                        newScopeStack.header.header['yMotor'] = yPos
                    else:
                        print(
                            '   error: bCanvas.importNewScopeFiles() did not find file position for file:',
                            potentialNewFile)
                        newScopeStack.header.header['xMotor'] = None
                        newScopeStack.header.header['yMotor'] = None

                # append to return list
                newStackList.append(newScopeStack)

                self._scopeFileList.append(newScopeStack)
                #print('*** importNewScopeFiles() REMEMBER TO SAVE !!!')

        return newStackList
Exemple #11
0
	def searchDisconnectedEdges(self, params=None):
		"""
		params: Not used, placeholder for other search functions
		"""
		self.initSearch('searchDisconnectedEdges')
		for edgeIdx, edge in enumerate(self.slabList.edgeIter()):
			if not self.continueSearch:
				break
			if self.slabList.isDanglingEdge(edgeIdx):
				#hitDict = self._defaultSearchDict2() # just includes 'idx'
				#hitDict['edge1'] = int(edgeIdx)
				hitDict = edge
				self.addFound(hitDict)

			# debug quiting search with Key_Q
			#time.sleep(0.3)
			#print('edgeIdx:', edgeIdx)

		if not self.continueSearch:
			print('search cancelled')

		self.finishSearch(verbose=False)
		return self.hitDictList

if __name__ == '__main__':
	path = '/Users/cudmore/box/Sites/DeepVess/data/20191017/blur/20191017__0001_z.tif'
	stack = bimpy.bStack(path, loadImages=False)

	mySearch = bSearchAnnotations(stack.slabList)
	mySearch.searchDeadEnd()
Exemple #12
0
    def __init__(self, path='', theStack=None, myStackWidget=None):

        print('=== bNapari.__init__() path:', path)

        self.myStackWidget = myStackWidget

        filename = os.path.basename(path)

        # load stack if neccessary
        if theStack is not None:
            self.mySimpleStack = theStack
        else:
            self.mySimpleStack = bimpy.bStack(path)

        #
        title = filename

        # todo oct 2020, add all open channels/masks
        stack = self.mySimpleStack.getStack('raw', channel=1)
        stack_nDim = len(stack.shape)

        self.viewer = napari.Viewer(title=title, ndisplay=stack_nDim)

        #
        # abb 20191216 removed
        self.bShapeAnalysisWidget = None
        #self.bShapeAnalysisWidget = bShapeAnalysisWidget(self.viewer, self.mySimpleStack)
        #

        xVoxel = self.mySimpleStack.xVoxel
        yVoxel = self.mySimpleStack.yVoxel
        zVoxel = self.mySimpleStack.zVoxel

        colormap = 'gray'
        if stack_nDim == 2:
            scale = (xVoxel, yVoxel)
        elif stack_nDim == 3:
            scale = (zVoxel, xVoxel, yVoxel)  # (z, x, y)
        else:
            print('error: napari got stack dim it does not understand')

        colorMaps = ['green', 'red', 'blue']

        # raw data
        for idx in range(self.mySimpleStack.numChannels):
            channel = idx + 1
            colormap = colorMaps[idx]
            stack = self.mySimpleStack.getStack('raw', channel=channel)
            self.viewer.add_image(stack,
                                  name=str(channel),
                                  blending='additive',
                                  colormap=colormap,
                                  scale=scale)

        # mask data
        for idx in range(self.mySimpleStack.numChannels):
            channel = idx + 1
            colormap = colorMaps[idx]
            stack = self.mySimpleStack.getStack('mask', channel=channel)
            self.viewer.add_image(stack,
                                  name='mask ' + str(channel),
                                  blending='additive',
                                  colormap=colormap,
                                  scale=scale)
        '''
		dvMask = self.mySimpleStack.getDeepVessMask()
		if dvMask is not None:
			self.viewer.add_image(data=dvMask, contrast_limits=[0,1], opacity=0.8, colormap='gray', scale=scale, name='dvMask')
		'''
        '''
		@self.viewer.bind_key('u')
		def keyboard_u(viewer):
			shapeType, data = self._getSelectedLine()
			print('   keyboard_u()', shapeType, data)
			if shapeType == 'line':
				src = data[0]
				dst = data[1]
				self.bShapeAnalysisWidget.updateStackLineProfile(src, dst)
			if shapeType in ['rectangle', 'polygon']:
				self.bShapeAnalysisWidget.updateStackPolygon(data)
		'''

        if self.mySimpleStack.slabList is not None:
            x = self.mySimpleStack.slabList.x * xVoxel
            y = self.mySimpleStack.slabList.y * yVoxel
            z = self.mySimpleStack.slabList.z * zVoxel
            d = self.mySimpleStack.slabList.d * xVoxel  # use x
            d2 = self.mySimpleStack.slabList.d2 * xVoxel  # use x
            nodeIdx = self.mySimpleStack.slabList.nodeIdx

            # this has nans which I assume will lead to some crashes ...
            points = np.column_stack((
                z,
                x,
                y,
            ))

            scaleFactor = 0.6
            print(
                'warning: bNapari is scaling diameters by scaleFactor ... d = d *',
                scaleFactor)
            dCopy = d * scaleFactor
            d2Copy = d2 * scaleFactor

            fixedNodeSize = 4

            #
            size_myNodes = []
            face_color_myNodes = []
            slabs_nodes = []
            #
            size_myEdges = []
            face_color_myEdges = []
            slabs_edge = []
            for idx in range(len(x)):
                if np.isnan(dCopy[idx]):
                    thisSize = 5
                else:
                    thisSize = dCopy[idx]
                if nodeIdx[idx] >= 0:
                    intNodeIdx = int(float(nodeIdx[idx]))
                    nEdges = self.mySimpleStack.slabList.nodeDictList[
                        intNodeIdx]['nEdges']
                    #nodeSize = thisSize # dynamic size
                    nodeSize = fixedNodeSize  # fixed size
                    slabs_nodes.append(idx)
                    size_myNodes.append(nodeSize)
                    if nEdges == 1:
                        # dead end
                        face_color_myNodes.append('orange')
                    else:
                        face_color_myNodes.append('red')
                else:
                    slabSize = thisSize
                    #slabSize = 5 # fixed size
                    slabs_edge.append(idx)
                    size_myEdges.append(slabSize)
                    face_color_myEdges.append('cyan')
            # remember, (size, face_color), etc. Can be a scalar to set one value

            # debug
            if 0:
                print('   points:', points.shape)
                print('   len(size)', len(size))
                print('   len(face_color)', len(face_color))

            # nodes
            points_nodes = np.column_stack((
                z[slabs_nodes],
                x[slabs_nodes],
                y[slabs_nodes],
            ))
            self.pointLayer = self.viewer.add_points(
                points_nodes, size=size_myNodes,
                face_color=face_color_myNodes)  #, n_dimensional=False)
            self.pointLayer.name = 'Nodes'

            # edges
            points_edges = np.column_stack((
                z[slabs_edge],
                x[slabs_edge],
                y[slabs_edge],
            ))
            self.pointLayer = self.viewer.add_points(
                points_edges, size=size_myEdges,
                face_color=face_color_myEdges)  #, n_dimensional=False)
            self.pointLayer.name = 'Edges'

            #
            # connect edges with shape layer of 'path'
            print(
                'making edge vector layer ... WE WILL ONLY DO THIS FOR 800 edges !!!'
            )
            defaultWidth = 2
            masterEdgeList = []
            myPathColors = []
            myPathEdgeWidths = []
            for idx, edge in enumerate(self.mySimpleStack.slabList.edgeIter()):
                if idx > 800:
                    continue
                edgeColor = edge[
                    'color']  # when i make edges, i was not assigning color
                if edgeColor is None:
                    edgeColor = 'cyan'
                slabList = edge['slabList']
                #print('edge idx:', idx, 'edgeColor:', edgeColor, 'len(slabList):', len(slabList))
                currentEdgeList = []
                for slab in slabList:
                    slabWidth = d2Copy[
                        slab]  #* xVoxel # my slab width is still in pixels
                    if np.isnan(slabWidth):
                        #print('edge', idx, 'slab', slab, 'has nan width')
                        slabWidth = defaultWidth
                    currentEdgeList.append([z[slab], x[slab], y[slab]])
                    myPathColors.append(edgeColor)
                    myPathEdgeWidths.append(slabWidth)
                masterEdgeList.append(
                    currentEdgeList)  # this will be list of list

            myEdgesPaths = [
                np.array(xx) for xx in masterEdgeList
            ]  # always give napari a list where each[i] is a np.array ???
            #
            self.myShapePathLayer = self.viewer.add_shapes(
                myEdgesPaths,
                shape_type='path',
                edge_width=myPathEdgeWidths,
                edge_color=myPathColors,
                name='Edges Paths')
            self.myShapePathLayer.editable = True

        self.connectNapari()  # connect signals and slots

        #
        # make selection layers
        if self.mySimpleStack.slabList is not None:
            # edge selection
            selectionSize = 7 * xVoxel  #np.column_stack((6,6,6,))
            face_color = 'yellow'
            tmpData = np.column_stack((
                np.nan,
                np.nan,
                np.nan,
            ))  #todo: fix this
            self.edgeSelectionLayer = self.viewer.add_points(
                tmpData,
                size=selectionSize,
                face_color=face_color,
                n_dimensional=False)
            self.edgeSelectionLayer.name = 'Edge Selection'
            #
            flashSize = 10 * xVoxel
            flashColor = 'magenta'
            self.edgeSelectionLayerFlash = self.viewer.add_points(
                tmpData,
                size=flashSize,
                face_color=flashColor,
                n_dimensional=False)
            self.edgeSelectionLayerFlash.name = 'Flash Selection'

            # node selection
            selectionSize = 7 * xVoxel  #np.column_stack((6,6,6,))
            face_color = 'yellow'
            tmpData = np.column_stack((
                np.nan,
                np.nan,
                np.nan,
            ))  #todo: fix this
            self.nodeSelectionLayer = self.viewer.add_points(
                tmpData,
                size=selectionSize,
                face_color=face_color,
                n_dimensional=False)
            self.nodeSelectionLayer.name = 'Node Selection'
            #
            flashSize = 15 * xVoxel
            flashColor = 'magenta'
            self.nodeSelectionLayerFlash = self.viewer.add_points(
                tmpData,
                size=flashSize,
                face_color=flashColor,
                n_dimensional=False)
            self.nodeSelectionLayerFlash.name = 'Node Selection'
Exemple #13
0
def bMakeSkelFromMask(path, channelToAnalyze, maskStartStop):
		# load the stack
		myStack = bimpy.bStack(path=path, loadImages=True, loadTracing=True)

		#
		# some options
		remakeSkelFromMask = True
		saveAtEnd = True

		# SLOW: load mask and make skel from mask
		if remakeSkelFromMask:
			myStack.slabList.loadDeepVess(vascChannel=channelToAnalyze, maskStartStop=maskStartStop)

		# remove edges based on criterion
		if 1:
			#
			# remove all nCon==0
			edgeListToRemove = bimpy.bVascularTracingAics._getListFromCriterion(
						myStack.slabList,
						'edges',
						'nCon', '==', 0,
						verbose=True)

			# delete the edges
			bimpy.bVascularTracingAics._deleteList(myStack.slabList,
						'edges',
						edgeListToRemove,
						verbose=True)


			#
			# remove (nCon==1 and nSlab<20)
			edgeListToRemove = bimpy.bVascularTracingAics._getListFromCriterion(
						myStack.slabList,
						'edges',
						'nCon', '==', 1,
						verbose=True)
			#
			edgeListToRemove = bimpy.bVascularTracingAics._getListFromCriterion(
						myStack.slabList,
						'edges',
						'nSlab', '<', 20,
						fromThisList=edgeListToRemove,
						verbose=True)
			# delete edges
			bimpy.bVascularTracingAics._deleteList(myStack.slabList,
						'edges',
						edgeListToRemove,
						verbose=True)

			#
			# now we have a bunch of nodes with nEdges==0
			print('  == after deleting edges')
			nodeListToRemove = bimpy.bVascularTracingAics._getListFromCriterion(
						myStack.slabList,
						'nodes',
						'nEdges', '==', 0,
						verbose=True)
			# delete edges
			bimpy.bVascularTracingAics._deleteList(myStack.slabList,
						'nodes',
						nodeListToRemove,
						verbose=True)

			print('  == after deleting nodes with nEdges==0')
			nodeListToRemove = bimpy.bVascularTracingAics._getListFromCriterion(
						myStack.slabList,
						'nodes',
						'nEdges', '==', 0,
						verbose=True)

		# anlyze all slab diameter in a cpu pool
		# this works, see bAnalyzeDiameters.py
		'''
		if 0:
			b_mpAnalyzeSlabs.runDiameterPool(myStack, channelToAnalyze)
		'''

		if 1:
			myStack.slabList._preComputeAllMasks()

		# save, next time we load, we do not need to (make skel, analyze diameter)
		if saveAtEnd:
			myStack.saveAnnotations()
Exemple #14
0
scale = (1,1,1)

#path = '/Users/cudmore/Sites/bImpy-Data/vesselucida/20191017__0001.tif'

# 1) show fernando this nathan immuno image
path = '/Users/cudmore/box/data/bImpy-Data/vesselucida/20191017__0001.tif'
path = '/Users/cudmore/box/Sites/DeepVess/data/20191017/blur/20191017__0001.tif'

# 2) show fernando this oct image
#path = '/Users/cudmore/box/data/bImpy-Data/OCTa/PV_Crop_Reslice.tif'

#path = 'D:/Users/cudmore/data/vessellucida/20191017__0001.tif'
#path = '/Users/cudmore/box/data/bImpy-Data/vesselucida/high_mag_top_of_node/tracing_20191217.tif'
#scale = (0.5, 0.31074033574250315, 0.31074033574250315)

myStack = bimpy.bStack(path=path)

print('=== NAPARI')
print('myStack.stack.shape:', myStack.stack.shape) # [channels, slices, x, y]

#
# we are using reshape(-1,1) here because each of x/y/x are of shape (n,) and we want (n,1)
x = myStack.slabList.x.reshape((-1,1)) # to do, fix this (n,) shape converting to (n)
y = myStack.slabList.y.reshape((-1,1))
z = myStack.slabList.z.reshape((-1,1))

# swap x/y
xyzPoints = np.hstack((z, x, y))

#print('x.shape:', x.shape)
print('xyzPoints.shape', xyzPoints.shape)