Esempio n. 1
0
    def test_read(self):
        logging.info('Checking reading example data')

        data = cbf.read('../examples/in16c_010001.cbf')

        # Random points of the image
        self.assertEqual(data.data[0][0], 1)
        self.assertEqual(data.data[0][-1], -2)  # Point with extreme value
        self.assertEqual(data.data[0][-2], 1)

        self.assertEqual(data.data[-1][0], -2)  # Point with extreme value
        self.assertEqual(data.data[-1][-1], -2)  # Point with extreme value
        self.assertEqual(data.data[-1][-2], 0)

        self.assertEqual(data.data[334][262], 1680)
        self.assertEqual(data.data[125][127], -2)  # Point with extreme value
        self.assertEqual(data.data[357][271], 214)

        data = cbf.read('../examples/run2_1_00148.cbf')
        # Random points of the image
        self.assertEqual(data.data[1169][1006], 20)
        self.assertEqual(data.data[1178][1030], 0)
        self.assertEqual(data.data[1223][1015], 2068)
        self.assertEqual(data.data[754][1859], 14)
        self.assertEqual(data.data[777][1707], 16)
        self.assertEqual(data.data[1302][1323], 98)
Esempio n. 2
0
 def show_image(self, im=None, lab='q', stack=1, **kwargs):
     rc('text', usetex=False)
     if not im: im = self.im
     file = "%s_%s.cbf" % (self.basename, str(im).zfill(self.pad)
                           )  #;print(filename)
     # with open(file,'wb') as f:print(file)
     content = cbf.read(file)
     image = content.data
     if stack > 1:
         for i in range(1, stack):
             filename = "%s_%s.cbf" % (self.basename, str(im + i).zfill(
                 self.pad))  #;print(filename)
             image += cbf.read(filename).data
         if 'caxis' in list(kwargs.keys()):
             kwargs['caxis'] = list(np.array(kwargs['caxis']) *
                                    stack)  #; print(kwargs['caxis'])
     if 'q' in lab:
         labs = ['$q_x(A^{-1})$', '$q_y(A^{-1})$']
         X, Y = self.qx, -self.qy
     elif 'p' in lab:
         labs = ['', '']  #['$p_x$','$p_y$']
         X, Y = self.pX, self.pY
     elif 'x' in lab:
         labs = ['$x(mm)$', '$y(mm)$']
         px, py = self.pxy
         X, Y = self.pX * px * 1e3, self.pY * py * 1e3
     return dsp.stddisp(im=[X, Y, image],
                        labs=labs,
                        pOpt='ptX',
                        title="%s" % os.path.basename(file),
                        **kwargs)
Esempio n. 3
0
def headercbf(filename):
    if isfile(filename):
        f = cbf.read(filename)
        return f.metadata
    else:
        print("file ", filename, " does not exist!")
        return 0
Esempio n. 4
0
def loadcbf(filename):
    if isfile(filename):
        f = cbf.read(filename)
        return f.data
    else:
        print("file ", filename, " does not exist!")
        return 0
Esempio n. 5
0
    def loadCBFContent(self):
        # -----
        valid = (self.full_image_path is not None)
        # -----
        newPath = self.image_path % self.image_tracking_widget_layout.image_num_spinbox.value(
        )

        if ((self.full_image_path != newPath)
                or (self.canvas.fullImagePath != newPath)):
            self.full_image_path = newPath

            try:
                self.cbfContent = cbf.read(self.full_image_path,
                                           metadata=False)
                self.numpyArrayWithData = self.cbfContent.data
                # -----
                valid = True
            except:
                # Inform user that an error occurred
                logging.getLogger('user_level_log').error(
                    'Error loading CBF image: \'%s\'!' %
                    str(self.full_image_path))
                # Clean showed image
                self.loadBlanckImage()
                # return invalid
                valid = False

        return valid
Esempio n. 6
0
 def getHeader(self, fileName):
     """
     Header is python dict {}
     """
     content = cbf.read(fileName, metadata=True, parse_miniheader=True)
     header = content.miniheader
     return header
Esempio n. 7
0
 def getData(self, fileName):
     """
     Data is float numpy array 
     """
     content = cbf.read(fileName)
     data = np.array(content.data).astype(float)
     return data
Esempio n. 8
0
 def getDataHeader(self, fileName):
     """
     Data is float numpy array 
     Header is python dict {}
     """
     content = cbf.read(fileName, metadata=True, parse_miniheader=True)
     data = np.array(content.data).astype(float)
     header = content.miniheader
     return (data, header)
Esempio n. 9
0
 def load_cbf(self, fig):
     try:
         content = cbf.read(fig)
     except:  #UnicodeDecodeError
         self.i = self.i + self.mode
         print(colors.red + 'error reading file' + colors.black)
         self.import_exp()
         return
     numpy_array_with_data = content.data
     header_metadata = content.metadata
     # print(colors.blue,header_metadata,colors.black)
     return numpy_array_with_data
Esempio n. 10
0
    def __init__(self, file, sym=1, pad=None):
        basename = file.split('_')
        self.im = int(basename[-1].replace('.cbf', ''))
        self.basename = '_'.join(basename[:-1])
        file_ids = [
            int(f.split('_')[-1].replace('.cbf', ''))
            for f in glob.glob(self.basename + '*.cbf')
        ]
        if pad:
            self.pad = pad
        else:
            self.pad = int(np.log10(max(file_ids))) + 1  #;print(self.pad)

        ls = np.array(
            check_output("head -n25 %s" % file,
                         shell=True).decode().split('\n'))
        px_str = ls[['Pixel_size' in l for l in ls]][0]
        D_str = ls[['Detector_distance' in l for l in ls]][0]  #;print(D_str)
        lam_str = ls[["Wavelength" in l for l in ls]][0]

        self.pxy = np.array(re.findall("\d+e-\d+", px_str), dtype=float)
        self.D = 1  #float(re.findall("\d+.\d+",D_str)[0])
        self.lam = float(re.findall("\d+.\d+", lam_str)[0])

        shape = np.array(cbf.read(file).data.shape)
        self.image = cbf.read(file).data

        if sym:
            Nx, Ny = np.array(shape / 2, dtype=int)
            self.Nx, self.Ny = Nx, Ny
            self.pX, self.pY = np.meshgrid(np.arange(-Nx, Nx + 1),
                                           np.arange(-Ny, Ny + 1))
        else:
            Nx, Ny = shape
            # self.pX,self.pY = np.meshgrid(np.arange(Nx),np.arange(Ny))
            self.pX, self.pY = np.meshgrid(np.arange(Nx),
                                           np.flipud(np.arange(Ny)))
        self.qx, self.qy = self.px2s(self.pX, self.pY)
Esempio n. 11
0
    def test_write(self):
        for i in range(1000):
            logging.info('start')

            test_file = 'test.cbf'

            # Ensure that file does not exist
            try:
                os.remove(test_file)
            except OSError:
                pass

            # 65536
            # 66600 cannot compress at all
            min_number = 0
            max_number = 66600
            max_number = 600
            max_number = 2147483647  # max value int32
            # max_number = 2147483648  # max value + 1int32 # will fail
            numpy_array = numpy.random.randint(min_number, max_number,
                                               (500, 400)).astype('int32')
            numpy_array[0][0] = max_number
            # numpy_array[0][0] = -1

            # numpy_array = numpy.empty((500, 400)).astype('int32')
            # numpy_array.fill(max_number)

            print(numpy_array[0][0])
            cbf.write(test_file, numpy_array)

            content = cbf.read(test_file)

            if not (numpy_array == content.data).all():
                print('NOT SAME')
                print((numpy_array == content.data).sum())

                print(content.data)
                print(content.metadata)
            print(content.metadata)
            print(i)
            self.assertTrue((numpy_array == content.data).all())

        # Remove test file
        os.remove(test_file)
Esempio n. 12
0
    def test_write(self):
        for i in range(1000):
            logging.info('start')

            test_file = 'test.cbf'

            # Ensure that file does not exist
            try:
                os.remove(test_file)
            except OSError:
                pass

            # 65536
            # 66600 cannot compress at all
            min_number = 0
            max_number = 66600
            max_number = 600
            max_number = 2147483647  # max value int32
            # max_number = 2147483648  # max value + 1int32 # will fail
            numpy_array = numpy.random.randint(min_number, max_number, (500, 400)).astype('int32')
            numpy_array[0][0] = max_number

            # numpy_array = numpy.empty((500, 400)).astype('int32')
            # numpy_array.fill(max_number)


            print(numpy_array[0][0])
            cbf.write(test_file, numpy_array)

            content = cbf.read(test_file)

            if not (numpy_array == content.data).all():
                print('SAME')
                print((numpy_array == content.data).sum())

                print(content.data)
                print(content.metadata)
            print(content.metadata)
            print(i)
            self.assertTrue((numpy_array == content.data).all())
Esempio n. 13
0
## There already exist packages for parsing these types of files
## But.. we can easily modify/update them if necessary!

import cbf
import os
from matplotlib import pyplot as plt

directory_in_str = str(input('Input directory file path: '))

#directory = os.fsencode(directory_in_str)

directory = directory_in_str 
   
for file in os.listdir(directory):
     filename = os.fsdecode(file)
     if filename.endswith(".cbf"): 
         print('--> Reading in file: ',os.path.join(directory, filename))
         cbf_file = os.path.join(directory, filename) 
         content = cbf.read(str(cbf_file))
         numpy_array_with_data = content.data
         header_metadata = content.metadata

# Plot image with matplot lib
         plt.imshow(numpy_array_with_data, cmap='gray', vmax=1)
         plt.show()
         continue
     else:
         continue


Esempio n. 14
0
 def get_image(self, path):
     if path.endswith(".cbf"):
         return cbf.read(path).data
     else:
         return super().get_image(path)