Ejemplo n.º 1
0
    def setVolume(self, vol=None, path=None, sliceobj=None):

        if path is not None and vol is None:
            if '*' in path:
                vol = loader.loadimageseries(path)
            elif os.path.splitext(path)[-1] == '.npy':
                vol = loader.loadimage(path)
            else:
                vol = loader.loadtiffstack(path)
        elif vol is None:
            vol = self.vol

        if vol is None:
            return

        self.vol = vol

        if slice is not None:

            def intify(a):
                if a is not None: return int(a)

            sliceobj = [
                slice(intify(s.start), intify(s.stop), intify(s.step))
                for s in sliceobj
            ]
            slicevol = self.vol[sliceobj]
        else:
            slicevol = self.vol

        # Set whether we are emulating a 3D texture
        emulate_texture = False

        # Create the volume visuals
        if self.volume is None:
            self.volume = scene.visuals.Volume(slicevol,
                                               parent=self.view.scene,
                                               emulate_texture=emulate_texture)
            self.volume.method = 'translucent'
        else:
            self.volume.set_data(slicevol)
            self.volume._create_vertex_data(
            )  #TODO: Try using this instead of slicing array?

        # Translate the volume into the center of the view (axes are in strange order for unkown )
        scale = 3 * (2.0 / self.vol.shape[1], )
        translate = map(lambda x: -scale[0] * x / 2, reversed(vol.shape))
        self.volume.transform = scene.STTransform(translate=translate,
                                                  scale=scale)
Ejemplo n.º 2
0
    def execute(self):
        steps = self.ui.rmcSteps.value()
        scalefactor = self.ui.rmcScalefactor.value()
        modlestartsize = self.ui.rmcModlestartsize.value()

        loadingfactors = []

        for item in iterAllItems(self.ui.rmcLoadingfactors):
            loadingfactors.append(item.text())

        rip = self.ui.rmcinputpaths
        inputpaths = [rip.item(index).text() for index in xrange(rip.count())]

        tiles = len(loadingfactors)

        for path in inputpaths:
            d = {
                'hipRMCInput': {
                    'instrumentation': {
                        'inputimage': path,
                        'imagesize': loader.loadimage(path).shape[0:2],
                        'numtiles': tiles,
                        'loadingfactors': loadingfactors,
                        # 'maskimage': "data/mask.tif"
                    },  # optional
                    'computation': {
                        'runname':
                        os.path.join(self.ui.rmcoutput.text(),
                                     self.ui.rmcRunName.text()),
                        'modelstartsize': [modlestartsize, modlestartsize],
                        'numstepsfactor':
                        steps,
                        'scalefactor':
                        scalefactor
                    }
                }
            }
            h = hig.hig(**d)
            h.write("test_input.hig")
            self.rmcdaemon = RMCThread()
            self.rmcdaemon.sig_finished.connect(self.displayoutput)
            self.rmcdaemon.start()
Ejemplo n.º 3
0
    def opendirectory(self, folder, operation=None):
        """
        Overrides inherited 'opendirectory' method. Used for opening hiprmc output folders.
        """
        self.activate()
        if type(folder) is list:
            folder = folder[0]
        view_widget = inOutViewer(None, self.threadWorker,)
        self.centerwidget.addTab(view_widget, os.path.basename(folder))
        self.centerwidget.setCurrentWidget(view_widget)

        # check for input image and load into plugin if it exists
        input = glob.glob(os.path.join(folder, 'input_image.tif'))
        if input:
            view_widget.orig_image = np.transpose(loader.loadimage(input[0]))
            if len(view_widget.orig_image.shape) > 2: # gets ride of extra dimensions if there are any
                view_widget.orig_image = np.transpose(view_widget.orig_image).swapaxes(0,1)
                while len(view_widget.orig_image.shape) > 2:
                    view_widget.orig_image = view_widget.orig_image[:,:,0]
            view_widget.orig_view.setImage(view_widget.orig_image)
            view_widget.orig_view.autoRange()

            view_widget.drawROI(0, 0, view_widget.orig_image.shape[0], view_widget.orig_image.shape[1], 'r',
                         view_widget.orig_view.getImageItem().getViewBox())

        view_widget.rmc_view = rmc.rmcView(folder)
        view_widget.rmc_view.findChild(QtGui.QTabBar).hide()
        view_widget.rmc_view.setContentsMargins(0, 0, 0, 0)
        view_widget.image_holder.addWidget(view_widget.rmc_view)

        view_widget.fft_view = rmc.fftView()
        view_widget.fft_view.open_from_rmcView(view_widget.rmc_view.image_list)
        view_widget.fft_view.setContentsMargins(0, 0, 0, 0)
        view_widget.image_holder.addWidget(view_widget.fft_view)

        view_widget.image_holder.setCurrentIndex(2)
Ejemplo n.º 4
0
    def runRMC(self):
        """
        Slot to receive signal when user requests HipRMC calculation. Writes hig file of parameter values and
        calls HipRMC as subprocess
        """


        msg.showMessage('Running RMC for centered version of {}'.format(self.path), timeout=0)

        if self.rmc_view is not None:
            self.image_holder.removeWidget(self.rmc_view)

        if self.edited_image is None:
            msg.showMessage('Error: must center image before running HipRMC',timeout = 0)
            msg.clearMessage()
            return



        params = self.configparams

        hig_info = {'hipRMCInput': {'instrumentation': {'inputimage': "{}".format(self.write_path_sample),
                                             'imagesize': [self.new_dim, self.new_dim ],
                                             'numtiles': params.child('Num tiles').value(),
                                             'loadingfactors': [params.child('Loading factor').value()]},
                         'computation': {'runname': "{}".format(params.child('Save name').value()),
                                         'modelstartsize': [params.child('Model start size').value(),
                                                            params.child('Model start size').value()],
                                         'numstepsfactor': params.child('Numsteps factor').value(),
                                         'scalefactor': params.child('Scale factor').value()}}}

        self.mask_path = params.child('Mask image').value()
        if self.mask_path and self.mask_path != "None":
            self.mask = np.transpose(loader.loadimage(self.mask_path))
            self.center(False)
            hig_info['hipRMCInput']['instrumentation']['maskimage'] = "{}".format(self.write_path_mask)

        h = hig.hig(**hig_info)
        self.hig_name = os.path.join(os.path.abspath('.'), params.child('Save name').value())

        if not self.hig_name.endswith('.hig'):
            self.hig_name += '.hig'

        # write hig file to disk
        h.write(self.hig_name)
        self.save_name = params.child('Save name').value()
        self.start_time = time.time()

        # starts filewatcher to watch for new hiprmc folder, and the HipRMC job
        # also starts worker if it is not already running
        process = threads.RunnableMethod(method = self.run_RMCthread, finished_slot = self.RMC_done,
                                         except_slot=self.hiprmc_not_found)
        self.file_watcher = NewFolderWatcher(path=os.path.abspath("."), experiment=None)

        # when filewatcher gets rmc folder, it passes it to self.start_watcher to start another watcher
        self.file_watcher.sigFinished.connect(self.start_watcher)
        watcher = threads.RunnableMethod(method=self.file_watcher.run,)
        self.worker.queue.put(watcher)
        self.worker.queue.put(process)

        if not self.worker.isRunning():
            self.worker.start()
Ejemplo n.º 5
0
    def __init__(self, paths, worker, parent=None):
        """
        Class that holds image to be processed by HipRMC, image after it has been centered, and HipRMC output

        Attributes
        ----------
        emitter : threads.Emitter
            Holds and emits a signal when fHipRMc done processing
        interrupt : bool
            flag - set true if rmc processing was interrupted; affects post-rmc processes
        cameraLocation : tuple
            2-tuple (x,y) of camera location on input image
        rmcView : ximcam.RmcView.rncView
            Timeline viewer which holds and displays HipRMC output
        orig_image: np.array
            Original input image
        edited_image : np.array
            Image with camera location adjusted to its center
        orig_view : pyqtgraph.ImageView
            Holds the original image
        edited_view : pyqtgraph.ImageView
            Holds the image after camera location adjustment
        image_holder : QtGui.StackedWidget
            Main widget of plugin. Holds original and edited images, as well as HipRMC output, in tabs
        scatteringParams : pyqtgraph.parametertree
            Occupies right side of main widget. Holds configparams
        configparams : pyqtgraph.Parameter
            Class held by scatteringParams which holds parameter values for HipRMC
        output, err : str
            Output and error from HipRMC subprocess call
        headings : QtGui.QTabBar
            Displays name of corresponding tab of image_holder

        Parameters
        ----------
        paths : str/list of str
            Path to input dataset
        worker: threads.Worker
            Worker which queues up jobs and runs them on a QtCore.QThreadpool
        parent : QtGui.QWidget
            parent widget
        args
            Additional arguments
        kwargs
            Additional keyword arguments
        """


        super(inOutViewer, self).__init__(parent=parent)

        self.emitter = threads.Emitter()
        self.interrupt = False
        self.cameraLocation = config.activeExperiment.center
        self.rmc_view= None
        self.edited_image = None
        self.worker = worker


        # holders for original and edited images
        self.orig_view = LogViewer()
        self.orig_view.setContentsMargins(0,0,0,0)
        self.edited_view = LogViewer()
        self.edited_view.setContentsMargins(0,0,0,0)

        if type(paths) == list:
            self.path = paths[0]
        else:
            self.path = paths

        self.image_holder = QtGui.QStackedWidget()
        self.image_holder.setContentsMargins(0,0,0,0)

        # configuring right widget
        sideWidget = QtGui.QWidget()
        sideWidgetFormat = QtGui.QVBoxLayout()
        sideWidgetFormat.setContentsMargins(0, 0, 0, 0)

        # if paths is None, inOutViewer will only hold HipRMC output and the images/parameter table are not necessary
        if paths is not None:

            self.orig_image = np.transpose(loader.loadimage(self.path))
            if len(self.orig_image.shape) > 2:
                self.orig_image = np.transpose(self.orig_image).swapaxes(0,1)
                while len(self.orig_image.shape) > 2:
                    self.orig_image = self.orig_image[:,:,0]
            self.orig_view.setImage(self.orig_image)
            self.orig_view.autoRange()
            try:
                start_size = max(self.orig_image.shape)/10
            except ValueError:
                msg.showMessage("Image must be 2-D")

            scatteringHolder = QtGui.QStackedWidget()

            image_name = self.path.split('/')[-1].split('.')[0]
            self.scatteringParams = pt.ParameterTree()
            params = [{'name': 'Num tiles', 'type': 'int', 'value': 1, 'default': 1},
                      {'name': 'Loading factor', 'type': 'float', 'value': 0.5, 'default': 0.5},
                      {'name': 'Scale factor', 'type': 'int', 'value': 32, 'default': 32},
                      {'name': 'Numsteps factor', 'type': 'int', 'value': 100, 'default': 100},
                      {'name': 'Model start size', 'type': 'int', 'value': start_size},
                      {'name': 'Save name', 'type': 'str', 'value': 'hiprmc_' + image_name},
                      {'name': 'Mask image', 'type': 'str'}]
            self.configparams = pt.Parameter.create(name='Configuration', type='group', children=params)
            self.scatteringParams.setParameters(self.configparams, showTop=False)
            scatteringHolder.addWidget(self.scatteringParams)

            # # is there a better way to check for correct dimensions?
            # if len(self.orig_image.shape) > 2:
            #     shape = (self.orig_image.shape[1], self.orig_image.shape[2])
            # else:
            #     shape = self.orig_image.shape

            self.drawROI(0, 0, self.orig_image.shape[0], self.orig_image.shape[1], 'r',
                         self.orig_view.getImageItem().getViewBox())

            scatteringHolder.setFixedHeight(300)
            sideWidgetFormat.addWidget(scatteringHolder)

        centerButton = QtGui.QPushButton("Center camera location")
        runButton = QtGui.QPushButton("Run RMC processing")
        stopButton = QtGui.QPushButton("Stop RMC")
        sideWidgetFormat.addSpacing(5)
        sideWidgetFormat.addWidget(centerButton)
        sideWidgetFormat.addSpacing(5)
        sideWidgetFormat.addWidget(runButton)
        sideWidgetFormat.addSpacing(5)
        sideWidgetFormat.addWidget(stopButton)
        sideWidgetFormat.addStretch(10)
        sideWidget.setLayout(sideWidgetFormat)

        # connect buttons to processing
        centerButton.clicked.connect(self.center)
        runButton.clicked.connect(self.runRMC)
        stopButton.clicked.connect(self.stop_threads)

        # tab headings for main widget
        self.headings = QtGui.QTabBar(self)
        self.headings.addTab('Original Image')
        self.headings.addTab('Recentered Image')
        self.headings.addTab('RMC Timeline')
        self.headings.addTab('FFT RMC Timeline')
        self.headings.setShape(QtGui.QTabBar.TriangularSouth)


        leftWidget = QtGui.QWidget()
        sidelayout = QtGui.QVBoxLayout()
        sidelayout.addWidget(self.image_holder)
        sidelayout.addWidget(self.headings)
        leftWidget.setLayout(sidelayout)

        fullPlugin = QtGui.QSplitter()
        fullPlugin.addWidget(leftWidget)
        fullPlugin.addWidget(sideWidget)

        h = QtGui.QHBoxLayout()
        h.setContentsMargins(0, 0, 0, 0)
        h.addWidget(fullPlugin)
        self.setLayout(h)

        self.image_holder.addWidget(self.orig_view)
        self.image_holder.addWidget(self.edited_view)

        self.headings.currentChanged.connect(self.currentChanged)
        self.image_holder.currentChanged.connect(self.headings.setCurrentIndex)