Ejemplo n.º 1
0
def test_diffread_on_dm3_vs_dm4_image():
    """ Test that diffread() works on DM3 images """
    im3 = diffread(TEST_DM3)
    im4 = diffread(TEST_DM4)

    assert im3.shape == (256, 256)
    assert im3.dtype == np.dtype("int8")

    assert im4.shape == (256, 256)
    assert im4.dtype == np.dtype("int8")

    assert np.allclose(im3, im4)
Ejemplo n.º 2
0
    def test_on_dm3_vs_dm4_image(self):
        """ Test that diffread() works on DM3 images """
        im3 = diffread(TEST_DM3)
        im4 = diffread(TEST_DM4)

        with self.subTest("DM3"):
            self.assertEqual(im3.shape, (2048, 2048))
            self.assertEqual(im3.dtype, np.dtype("int8"))

        with self.subTest("DM4"):
            self.assertEqual(im4.shape, (2048, 2048))
            self.assertEqual(im4.dtype, np.dtype("int8"))

        with self.subTest("DM3 vs. DM4"):
            self.assertTrue(np.allclose(im3, im4))
Ejemplo n.º 3
0
def test_diffread_on_npy():
    """ Test diffread() on *.npy files """
    arr = np.random.random(size=(128, 128))
    with tempfile.TemporaryDirectory() as tmpdir:
        np.save(Path(tmpdir) / "skued_test.npy", arr)
        arr2 = diffread(Path(tmpdir) / "skued_test.npy")
    assert np.allclose(arr, arr2)
Ejemplo n.º 4
0
    def raw_data(self, timedelay, scan=1, bgr=True, **kwargs):
        """
        Returns an array of the image at a timedelay and scan.
        
        Parameters
        ----------
        timdelay : float
            Acquisition time-delay.
        scan : int, optional
            Scan number. Default is 1.
        bgr : bool, optional
            If True (default), laser background is removed before being returned.
        
        Returns
        -------
        arr : `~numpy.ndarray`, ndim 2
        
        Raises
        ------
        IOError : Filename is not associated with an image/does not exist.
        """
        fname = Path(
            self.source
        ) / f"data.nscan.{str(int(timedelay)).zfill(2)}.pumpoff.tif"

        if not fname.exists():
            raise IOError(
                f"Expected the file {fname} to exist, but could not find it.")

        im = np.asfarray(diffread(fname))
        if bgr:
            im -= self.background
            im[im < 0] = 0

        return im
Ejemplo n.º 5
0
    def raw_data(self, timedelay, scan=1, bgr=True, **kwargs):
        """
        Returns an array of the image at a timedelay and scan.
        
        Parameters
        ----------
        timdelay : float
            Acquisition time-delay.
        scan : int, optional
            Scan number. Default is 1.
        bgr : bool, optional
            If True (default), laser background is removed before being returned.
        
        Returns
        -------
        arr : `~numpy.ndarray`, ndim 2
        
        Raises
        ------
        ValueError : if ``timedelay`` or ``scan`` are invalid / out of bounds.
        IOError : Filename is not associated with an image/does not exist.
        """
        # Template filename looks like:
        #    'data.timedelay.+1.00.nscan.04.pumpon.tif'
        sign = "" if timedelay < 0 else "+"
        str_time = sign + f"{timedelay:.2f}"
        filename = ("data.timedelay." + str_time + ".nscan." +
                    str(scan).zfill(2) + ".pumpon.tif")

        im = diffread(join(self.source, filename)).astype(np.float)
        if bgr:
            im -= self.background
            im[im < 0] = 0

        return im
Ejemplo n.º 6
0
 def nearest_laserbg(self, timestamp):
     """ Laser background taken nearest to ``timestamp`` """
     fnames = {
         abs(v) - timestamp: k
         for (k, v) in self.timestamps.items()
         if k.parent == Path("laser_background")
     }
     nearest_timestamp = min(fnames.keys())
     return diffread(self.source / fnames[nearest_timestamp])
Ejemplo n.º 7
0
 def nearest_dark(self, timestamp):
     """ Dark image taken nearest to ``timestamp`` """
     fnames = {
         abs(v) - timestamp: k
         for (k, v) in self.timestamps.items()
         if k.parent == Path("dark_image")
     }
     nearest_timestamp = min(fnames.keys())
     return diffread(self.source / fnames[nearest_timestamp])
Ejemplo n.º 8
0
    def test_on_tiff(self):
        """ Test diffread() on tiff files """
        im = np.random.randint(0, 127, size=(512, 512))
        path = Path(".\\test_tif.tif")

        # Annoying low contrast warning
        with suppress_warnings():
            imsave(str(path), im)

        from_skued = diffread(path)
        self.assertTrue(np.allclose(im, from_skued))
        os.remove(path)
Ejemplo n.º 9
0
def peakpos_evolution(file_list, mask_total, laser_bkg, FF, peakpos_all, numrefine, window_size):
    peakpos_evolution = []
    no_files  = len(file_list)
    no_peaks = np.shape(peakpos_all)[0]
    for idx, f in tqdm.tqdm(enumerate(file_list)):
        image = np.array(skued.diffread(f), dtype = np.int64)
        #checks for saturation
        #if nanmax(nanmax(Image))==65000
        #    msgbox(['Warning: Image ',num2str(k),' is saturated!'])
        #    end
        #Apply mask
        image = image*mask_total
        #Substract background and flatfield
        image = remove_bgk(image, laser_bkg, FF)
        new_peakpos_all = refine_peakpos_arb_dim(peakpos_all, image, numrefine, window_size)
        peakpos_evolution.append(new_peakpos_all)
        peakpos_all = new_peakpos_all

    peakpos_evolution = np.array(peakpos_evolution).reshape(no_files, 2*no_peaks)
    return peakpos_evolution
Ejemplo n.º 10
0
    def raw_data(self, timedelay, scan=1, bgr=True, **kwargs):
        """
        Returns an array of the image at a timedelay and scan. Laser background is
        removed by default.
        
        Parameters
        ----------
        timdelay : float
            Acquisition time-delay.
        scan : int, optional
            Scan number. Default is 1.
        bgr : bool, optional
            If True (default), the laser background is removed as well.
        kwargs
            Extra keyword arguments are ignored.
        
        Returns
        -------
        arr : `~numpy.ndarray`, ndim 2
        
        Raises
        ------
        ValueError : if ``timedelay`` or ``scan`` are invalid / out of bounds.
        IOError : Filename is not associated with an image/does not exist.
        """
        # In this case, the time-delay is the pump-off timestamp
        fname = self.source / "pump_off" / f"pump_off_epoch_{timedelay:010.0f}s.tif"

        if not fname.exists():
            raise IOError(
                f"Expected the file for {timedelay}ps and scan {scan} to exist, but could not find it."
            )

        im = diffread(fname)
        if bgr:
            dark_bg = self.nearest_dark(
                timestamp=self.timestamps[fname.relative_to(self.source)])
            im -= dark_bg

        return im
Ejemplo n.º 11
0
    def load_single_picture(self):
        path = self.file_dialog.getOpenFileName(
            parent=self,
            caption="Load diffraction picture",
            filter="Images (*.tif *.tiff *.mib *.dm3 *.dm4)",
        )[0]
        if not path:
            return

        self.image_viewer = pg.ImageView(parent=self)
        self.image_viewer.setImage(diffread(path))

        layout = QtWidgets.QVBoxLayout()
        fname_label = QtWidgets.QLabel("Filename: " + path, parent=self)
        fname_label.setAlignment(QtCore.Qt.AlignCenter)
        layout.addWidget(fname_label)
        layout.addWidget(self.image_viewer)

        dialog = QtWidgets.QDialog()
        dialog.setLayout(layout)
        dialog.resize(0.75 * self.size())
        return dialog.exec_()
Ejemplo n.º 12
0
    def raw_data(self, timedelay, scan=1, **kwargs):
        """
        Returns an array of the image at a timedelay and scan. Dark background is
        always removed.
        
        Parameters
        ----------
        timdelay : float
            Acquisition time-delay.
        scan : int, optional
            Scan number. Default is 1.
        kwargs
            Extra keyword arguments are ignored.
        
        Returns
        -------
        arr : `~numpy.ndarray`, ndim 2
        
        Raises
        ------
        ValueError : if ``timedelay`` or ``scan`` are invalid / out of bounds.
        IOError : Filename is not associated with an image/does not exist.
        """
        # scan directory looks like 'scan 0132'
        # Note that a glob pattern is required because every diffraction pattern
        # has a timestamp in the filename.
        directory = join(self.source, "scan {:04d}".format(scan))
        try:
            fname = next(
                iglob(
                    join(directory,
                         "pumpon_{:+010.3f}ps_*.tif".format(timedelay))))
        except StopIteration:
            raise IOError(
                "Expected the file for {t}ps and scan {s} to exist, but could not find it."
                .format(t=timedelay, s=scan))

        return diffread(fname)
Ejemplo n.º 13
0
# This code used to be part of the documentation
# and rendered with sphinx
#
# However, the phase_cross_correlation function requires
# too much memory, and so readthedocs would kill the documentation
# build. Therefore, we render the image locally instead.

import matplotlib.pyplot as plt
import numpy as np
from skimage.registration import phase_cross_correlation

from skued import diffread, shift_image

ref = diffread("Cr_1.tif")
im = diffread("Cr_2.tif")

mask = np.ones_like(ref, dtype=np.bool)
mask[0:1250, 950:1250] = False

shift = phase_cross_correlation(im, ref, reference_mask=mask)
shifted = shift_image(im, -1 * shift)

fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(nrows=2, ncols=3, figsize=(9, 6))
ax1.imshow(ref, vmin=0, vmax=200)
ax2.imshow(im, vmin=0, vmax=200)
ax3.imshow(ref - im, cmap="RdBu_r", vmin=-100, vmax=100)
ax4.imshow(mask, vmin=0, vmax=1, cmap="binary")
ax5.imshow(shifted, vmin=0, vmax=200)
ax6.imshow(ref - shifted, cmap="RdBu_r", vmin=-100, vmax=100)

for ax in (ax1, ax2, ax3, ax4, ax5, ax6):
Ejemplo n.º 14
0
    def test_on_skimage_png(self):
        """ Test the last resort of using skimage.io for pngs """
        from_skimage = diffread(TEST_PNG)

        self.assertTupleEqual(from_skimage.shape, (256, 256))
        self.assertTrue(np.allclose(from_skimage, np.ones_like(from_skimage)))
Ejemplo n.º 15
0
def test_diffread_on_merlin_image_binary():
    """ Test diffread() on Merlin Image Binary (.mib) """
    im = diffread(TEST_MIB)
    assert im.shape == (256, 256)
    assert im.dtype == np.dtype(">u2")
Ejemplo n.º 16
0
def test_diffread_on_skimage_png():
    """ Test the last resort of using skimage.io for pngs """
    from_skimage = diffread(TEST_PNG)

    assert from_skimage.shape == (256, 256)
    assert np.allclose(from_skimage, np.ones_like(from_skimage))
Ejemplo n.º 17
0
 def test_on_merlin_image_binary(self):
     """ Test diffread() on Merlin Image Binary (.mib) """
     im = diffread(TEST_MIB)
     self.assertEqual(im.shape, (256, 256))
     self.assertEqual(im.dtype, np.dtype(">u2"))