def _readImageListSpec(self, filenamelist):
     # what to do if more than one file selected ?
     from PyMca5.PyMca import specfilewrapper as Specfile
     sf = Specfile.Specfile(filenamelist[0])
     scan = sf[0]
     labels = scan.alllabels()
     data = scan.data()
     scan = None
     sf = None
     if "column" in labels:
         offset = labels.index("column")
         ncols = int(data[offset].max() + 1)
         offset += 1
     else:
         raise IOError("Only images exported as csv supported")
     imagelist = []
     imagenames = []
     for i in range(offset, len(labels)):
         if labels[i].startswith("s("):
             continue
         tmpData = data[i]
         tmpData.shape = -1, ncols
         imagelist.append(tmpData)
         imagenames.append(labels[i])
     if not imagenames:
         self._criticalError('No valid data provided')
     return imagenames, imagelist
Пример #2
0
def convert_image(scan_no, frame_no, detector_info):

    _spec = specfilewrapper.Specfile(spec_path + 'ma2254_sixcvertical.spec')
    scan = _spec.select('{0}.1'.format(scan_no))

    UB = np.array(scan.header('G')[2].split(' ')[-9:], dtype=np.float)
    wavelength = float(scan.header('G')[1].split(' ')[-1])
    scanparams = wavelength, UB

    pointparams = get_point_params(
        scan, frame_no)  # 2D array of diffractometer angles + mon + transm

    img_loader = edf_image.edf_image_loader(spec_path +
                                            'ma2254_sixcvertical.spec')
    img = img_loader.load_frame(edf_path,
                                scan_no,
                                frame_no,
                                gz_compressed=True,
                                normalize=True,
                                monitor_names=['transm', 'mon'])

    proc_img, img_params = process_image(scanparams, pointparams, img,
                                         detector_info)
    wavelength, UB, gamma, delta, theta, mu, chi, phi = img_params
    HKL = project(wavelength, UB, gamma, delta, theta, mu, chi, phi)
    return HKL, proc_img
 def _loadExternalData(self):
     getfilter = True
     fileTypeList = ["EDF Files (*edf *ccd *tif)"]
     if HDF5:
         fileTypeList.append('HDF5 Files (*.h5 *.nxs *.hdf)')
     fileTypeList.append('ASCII Files (*)')
     fileTypeList.append("EDF Files (*)")
     message = "Open data file"
     filenamelist, ffilter = PyMcaFileDialogs.getFileList(
         parent=None,
         filetypelist=fileTypeList,
         message=message,
         getfilter=getfilter,
         single=True,
         currentfilter=None)
     if len(filenamelist) < 1:
         return
     filename = filenamelist[0]
     if ffilter.startswith('HDF5'):
         data = HDF5Widget.getDatasetDialog(
             filename,
             value=True,
             message='Select your data set by a double click')
     elif ffilter.startswith("EDF"):
         edf = EdfFile.EdfFile(filename, "rb")
         if edf.GetNumImages() > 1:
             # TODO: A dialog showing the different images
             # based on the external images browser needed
             print("WARNING: Taking first image")
         data = edf.GetData(0)
         edf = None
     elif ffilter.startswith("ASCII"):
         #data=numpy.loadtxt(filename)
         sf = specfilewrapper.Specfile(filename)
         targetScan = sf[0]
         data = numpy.array(targetScan.data().T, copy=True)
         targetScan = None
         sf = None
     return data
Пример #4
0
def test():
    a = qt.QApplication(sys.argv)
    a.lastWindowClosed.connect(a.quit)
    w = ParametersTab()
    w.show()
    from PyMca5.PyMca import specfilewrapper as specfile
    from PyMca5.PyMca import Specfit
    from PyMca5 import PyMcaDataDir
    import numpy
    sf = specfile.Specfile(
        os.path.join(PyMcaDataDir.PYMCA_DATA_DIR, "XRFSpectrum.mca"))
    scan = sf.select('2.1')
    mcadata = scan.mca(1)
    y = numpy.array(mcadata)
    #x=numpy.arange(len(y))
    x = numpy.arange(len(y)) * 0.0502883 - 0.492773
    fit = Specfit.Specfit()
    fit.setdata(x=x, y=y)
    fit.importfun(
        os.path.join(os.path.dirname(Specfit.__file__), "SpecfitFunctions.py"))
    fit.settheory('Hypermet')
    fit.configure(Yscaling=1.,
                  WeightFlag=1,
                  PosFwhmFlag=1,
                  HeightAreaFlag=1,
                  FwhmPoints=16,
                  PositionFlag=1,
                  HypermetTails=1)
    fit.setbackground('Linear')
    if 1:
        mcaresult = fit.mcafit(x=x, xmin=x[300], xmax=x[1000])
        w.fillfrommca(mcaresult)
    else:
        fit.estimate()
        fit.startfit()
        w.fillfromfit(fit.paramlist, current='Fit')
        w.removeview(view='Region 1')
    a.exec_()
    def _loadImageFiles(self):
        if self.getStackDataObject() is None:
            return
        getfilter = True
        fileTypeList = [
            "PNG Files (*png)", "JPEG Files (*jpg *jpeg)", "IMAGE Files (*)",
            "DAT Files (*dat)", "CSV Files (*csv)", "EDF Files (*edf)",
            "EDF Files (*ccd)", "EDF Files (*)"
        ]
        message = "Open image file"
        filenamelist, filefilter = PyMcaFileDialogs.getFileList(
            parent=None,
            filetypelist=fileTypeList,
            message=message,
            getfilter=getfilter,
            single=False,
            currentfilter=None)
        if not filenamelist:
            return
        imagelist = []
        imagenames = []
        mask = self.getStackSelectionMask()
        if mask is None:
            r, n = self.getStackROIImagesAndNames()
            shape = r[0].shape
        else:
            shape = mask.shape
        extension = qt.safe_str(os.path.splitext(filenamelist[0])[1])
        if filefilter.startswith("EDF"):
            for filename in filenamelist:
                # read the edf file
                edf = EDFStack.EdfFileDataSource.EdfFileDataSource(filename)

                # the list of images
                keylist = edf.getSourceInfo()['KeyList']
                if len(keylist) < 1:
                    msg = qt.QMessageBox(None)
                    msg.setIcon(qt.QMessageBox.Critical)
                    msg.setText("Cannot read image from file")
                    msg.exec_()
                    return

                for key in keylist:
                    #get the data
                    dataObject = edf.getDataObject(key)
                    data = dataObject.data
                    if data.shape[0] not in shape or data.shape[1] not in shape:
                        # print("Ignoring %s (inconsistent shape)" % key)
                        continue
                    imagename = dataObject.info.get('Title', "")
                    if imagename != "":
                        imagename += " "
                    imagename += os.path.basename(filename) + " " + key
                    imagelist.append(data)
                    imagenames.append(imagename)
            if not imagelist:
                msg = qt.QMessageBox(None)
                msg.setIcon(qt.QMessageBox.Critical)
                msg.setText("Cannot read a valid image from the file")
                msg.exec_()
                return
        elif extension.lower() in [".csv", ".dat"]:
            # what to do if more than one file selected ?
            from PyMca5.PyMca import specfilewrapper as Specfile
            sf = Specfile.Specfile(filenamelist[0])
            scan = sf[0]
            labels = scan.alllabels()
            data = scan.data()
            scan = None
            sf = None
            if "column" in labels:
                offset = labels.index("column")
                ncols = int(data[offset].max() + 1)
                offset += 1
            else:
                raise IOError("Only images exported as csv supported")
            imagelist = []
            imagenames = []
            for i in range(offset, len(labels)):
                if labels[i].startswith("s("):
                    continue
                tmpData = data[i]
                tmpData.shape = -1, ncols
                imagelist.append(tmpData)
                imagenames.append(labels[i])
        else:
            # Try pure Image formats
            for filename in filenamelist:
                image = qt.QImage(filename)
                if image.isNull():
                    msg = qt.QMessageBox(self)
                    msg.setIcon(qt.QMessageBox.Critical)
                    msg.setText("Cannot read file %s as an image" % filename)
                    msg.exec_()
                    return
                imagelist.append(image)
                imagenames.append(os.path.basename(filename))

            if not imagelist:
                msg = qt.QMessageBox(None)
                msg.setIcon(qt.QMessageBox.Critical)
                msg.setText("Cannot read a valid image from the file")
                msg.exec_()
                return

            for i, image in enumerate(imagelist):
                imagelist[i] = self.qImageToRgba(image)

        image_shape = self._getStackImageShape()
        origin, delta = self._getStackOriginDelta()

        h = delta[1] * image_shape[0]
        w = delta[0] * image_shape[1]

        for bgimg, bglabel in zip(imagelist, imagenames):
            if bglabel not in self.windows:
                self.windows[
                    bglabel] = SilxExternalImagesWindow.SilxExternalImagesWindow(
                    )
                self.windows[bglabel].sigMaskImageWidget.connect(
                    self.onWidgetSignal)

            self.windows[bglabel].show()
            # add the stack image for mask operation
            self.windows[bglabel].setImages([self.getStackOriginalImage()],
                                            labels=["stack data"],
                                            origin=origin,
                                            width=w,
                                            height=h)
            self.windows[bglabel].plot.getImage("current").setAlpha(0)

            # add the external image
            self.windows[bglabel].setBackgroundImages([bgimg],
                                                      labels=[bglabel],
                                                      origins=[origin],
                                                      widths=[w],
                                                      heights=[h])
            self.windows[bglabel].plot.setGraphTitle(bglabel)

            self._showWidget(bglabel)
Пример #6
0
    def _loadImageFiles(self):
        if self.getStackDataObject() is None:
            return
        getfilter = True
        fileTypeList = [
            "PNG Files (*png)", "JPEG Files (*jpg *jpeg)", "IMAGE Files (*)",
            "DAT Files (*dat)", "CSV Files (*csv)", "EDF Files (*edf)",
            "EDF Files (*ccd)", "EDF Files (*)"
        ]
        message = "Open image file"
        filenamelist, filefilter = PyMcaFileDialogs.getFileList(
            parent=None,
            filetypelist=fileTypeList,
            message=message,
            getfilter=getfilter,
            single=False,
            currentfilter=None)
        if len(filenamelist) < 1:
            return
        imagelist = []
        imagenames = []
        mask = self.getStackSelectionMask()
        if mask is None:
            r, n = self.getStackROIImagesAndNames()
            shape = r[0].shape
        else:
            shape = mask.shape
        extension = qt.safe_str(os.path.splitext(filenamelist[0])[1])
        if (filefilter.split()[0] in ["EDF"]) or \
           (extension.upper() in [".EDF", ".TIF"]):
            for filename in filenamelist:
                #read the edf file
                edf = EDFStack.EdfFileDataSource.EdfFileDataSource(filename)

                #the list of images
                keylist = edf.getSourceInfo()['KeyList']
                if len(keylist) < 1:
                    msg = qt.QMessageBox(None)
                    msg.setIcon(qt.QMessageBox.Critical)
                    msg.setText("Cannot read image from file")
                    msg.exec_()
                    return

                for key in keylist:
                    #get the data
                    dataObject = edf.getDataObject(key)
                    data = dataObject.data
                    if data.shape[0] not in shape:
                        continue
                    if data.shape[1] not in shape:
                        continue
                    imagename = dataObject.info.get('Title', "")
                    if imagename != "":
                        imagename += " "
                    imagename += os.path.basename(filename) + " " + key
                    imagelist.append(data)
                    imagenames.append(imagename)
            if len(imagelist) == 0:
                msg = qt.QMessageBox(None)
                msg.setIcon(qt.QMessageBox.Critical)
                msg.setText("Cannot read a valid image from the file")
                msg.exec_()
                return
            crop = False
            self.widget = StackPluginResultsWindow.StackPluginResultsWindow(
                parent=None, usetab=False)
            self.widget.buildAndConnectImageButtonBox()
            self.widget.sigMaskImageWidgetSignal.connect(self.mySlot)
            self.widget.setStackPluginResults(imagelist,
                                              image_names=imagenames)
            self._showWidget()
            return
        elif extension.lower() in [".csv", ".dat"]:
            # what to do if more than one file selected ?
            from PyMca5.PyMca import specfilewrapper as Specfile
            sf = Specfile.Specfile(filenamelist[0])
            scan = sf[0]
            labels = scan.alllabels()
            data = scan.data()
            scan = None
            sf = None
            if "column" in labels:
                offset = labels.index("column")
                ncols = int(data[offset].max() + 1)
                offset += 1
            else:
                raise IOError("Only images exported as csv supported")
            imagelist = []
            imagenames = []
            for i in range(offset, len(labels)):
                if labels[i].startswith("s("):
                    continue
                tmpData = data[i]
                tmpData.shape = -1, ncols
                imagelist.append(tmpData)
                imagenames.append(labels[i])
            crop = False
            self.widget = StackPluginResultsWindow.StackPluginResultsWindow(
                parent=None, usetab=False)
            self.widget.buildAndConnectImageButtonBox()
            self.widget.sigMaskImageWidgetSignal.connect(self.mySlot)
            self.widget.setStackPluginResults(imagelist,
                                              image_names=imagenames)
            self._showWidget()
            return
        else:
            #Try pure Image formats
            for filename in filenamelist:
                image = qt.QImage(filename)
                if image.isNull():
                    msg = qt.QMessageBox(None)
                    msg.setIcon(qt.QMessageBox.Critical)
                    msg.setText("Cannot read file %s as an image" % filename)
                    msg.exec_()
                    return
                imagelist.append(image)
                imagenames.append(os.path.basename(filename))

            if len(imagelist) == 0:
                msg = qt.QMessageBox(None)
                msg.setIcon(qt.QMessageBox.Critical)
                msg.setText("Cannot read a valid image from the file")
                msg.exec_()
                return
            self.widget = ExternalImagesWindow.ExternalImagesWindow(
                parent=None,
                rgbwidget=None,
                selection=True,
                colormap=True,
                imageicons=True,
                standalonesave=True)
            self.widget.buildAndConnectImageButtonBox()
            self.widget.sigMaskImageWidgetSignal.connect(self.mySlot)
            self.widget.setImageData(None)
            self.widget.setQImageList(imagelist,
                                      shape[1],
                                      shape[0],
                                      clearmask=False,
                                      data=None,
                                      imagenames=imagenames)
            #data=self.__stackImageData)
            self._showWidget()
            return