Ejemplo n.º 1
0
def calibrate_mag1_from_image_fn(center_fn, other_fn):
    """Calibrate pixel->stageposition coordinates from a set of images.

    center_fn: `str`
        Reference image at the center of the grid (with the clover in the middle)
    other_fn: `tuple` of `str`
        Set of images to cross correlate to the first reference image

    return:
        instance of Calibration class with conversion methods
    """
    img_cent, h_cent = read_image(center_fn)

    # binsize = h_cent["ImageBinsize"]
    cam_dimensions = h_cent['ImageCameraDimensions']
    bin_x, bin_y = cam_dimensions / np.array(img_cent.shape)
    assert bin_x == bin_y, 'Binsizes do not match {bin_x} != {bin_y}'
    binsize = int(bin_x)

    img_cent, scale = autoscale(img_cent, maxdim=512)

    x_cent, y_cent, _, _, _ = h_cent['StagePosition']

    xy_cent = np.array([x_cent, y_cent])
    print('Center:', center_fn)
    print('Stageposition: x={:.0f} | y={:.0f}'.format(*xy_cent))
    print()

    shifts = []
    stagepos = []

    for i, fn in enumerate(other_fn):
        img, h = read_image(fn)

        img = imgscale(img, scale)

        x_xobs, yobs, _, _, _ = h_cent['StagePosition']
        print('Image:', fn)
        print(f'Stageposition: x={xobs:.0f} | y={yobs:.0f}')

        shift, error, phasediff = phase_cross_correlation(img_cent, img, upsample_factor=10)
        print('Shift:', shift)
        print()

        stagepos.append((xobs, yobs))
        shifts.append(shift)

    # correct for binsize, store as binsize=1
    shifts = np.array(shifts) * binsize / scale
    stagepos = np.array(stagepos) - xy_cent

    c = CalibStage.from_data(shifts, stagepos, reference_position=xy_cent, camera_dimensions=cam_dimensions)
    c.plot()
    c.to_file()

    return c
def calibrate_stage_lowmag_from_image_fn(center_fn, other_fn):
    """Calibrate pixel->stageposition coordinates from a set of images.

    center_fn: `str`
        Reference image at the center of the grid (with the clover in the middle)
    other_fn: `tuple` of `str`
        Set of images to cross correlate to the first reference image

    return:
        instance of Calibration class with conversion methods
    """
    img_cent, h_cent = read_image(center_fn)

    img_cent, scale = autoscale(img_cent, maxdim=512)

    x_cent, y_cent, _, _, _ = h_cent['StagePosition']
    xy_cent = np.array([x_cent, y_cent])
    print('Center:', center_fn)
    print('Stageposition: x={:.0f} | y={:.0f}'.format(*xy_cent))
    print()

    binsize = h_cent['ImageBinsize']

    shifts = []
    stagepos = []

    for fn in other_fn:
        img, h = read_image(fn)

        img = imgscale(img, scale)

        xobs, yobs, _, _, _ = h['StagePosition']
        print('Image:', fn)
        print(f'Stageposition: x={xobs:.0f} | y={yobs:.0f}')
        print()

        shift, error, phasediff = phase_cross_correlation(img_cent,
                                                          img,
                                                          upsample_factor=10)

        stagepos.append((xobs, yobs))
        shifts.append(shift)

    # correct for binsize, store as binsize=1
    shifts = np.array(shifts) * binsize / scale
    stagepos = np.array(stagepos) - xy_cent

    c = CalibStage.from_data(shifts,
                             stagepos,
                             reference_position=xy_cent,
                             header=h_cent)
    c.plot()

    return c
    def show_image(self):
        row = self.tv.item(self.tv.focus())
        try:
            frame, number, prediction, size, stage_x, stage_y = row["values"]
        except ValueError:  # no row selected
            print("No row selected")
            return

        fn = Path(row["text"])

        root = fn.parents[1]
        name = fn.stem.rsplit("_", 1)[0]  # strip crystal number
        image_fn = root / "images" / f"{name}{fn.suffix}"

        if not fn.exists():
            print(f"No such file: {fn}")
            return

        if not image_fn.exists():
            print(f"No such file: {image_fn}")
            return

        data, data_h = read_image(fn)
        img, img_h = read_image(image_fn)

        cryst_x, cryst_y = img_h["exp_crystal_coords"][number]

        fig = plt.figure()
        ax1 = plt.subplot(
            121,
            title=
            f"Image\nframe={frame} | number={number}\nsize={size} | x,y=({stage_x}, {stage_y})",
            aspect="equal")
        ax2 = plt.subplot(
            122,
            title=f"Diffraction pattern\nprediction={prediction}",
            aspect="equal")

        # img = np.rot90(img, k=3)                            # img needs to be rotated to match display
        cryst_y, cryst_x = img.shape[0] - cryst_x, cryst_y  # rotate coordinates

        coords = img_h["exp_crystal_coords"]
        for c_x, c_y in coords:
            c_y, c_x = img.shape[0] - c_x, c_y
            ax1.plot(c_y, c_x, marker="+", color="blue", mew=2)

        ax1.imshow(img, vmax=np.percentile(img, 99.5))
        ax1.plot(cryst_y, cryst_x, marker="+", color="red", mew=2)

        ax2.imshow(data, vmax=np.percentile(data, 99.5))

        ShowMatplotlibFig(self, fig, title=fn)
Ejemplo n.º 4
0
def main():
    try:
        fn = sys.argv[1]
    except:
        print("Usage: instamatic.viewer IMG.tiff")
        exit()

    img, h = read_image(fn)

    print("""Loading data: {}
        size: {} kB
       shape: {}
       range: {}-{}
       dtype: {}
""".format(fn, img.nbytes/1024, img.shape, img.min(), img.max(), img.dtype))

    max_len = max([len(s) for s in h.keys()])

    fmt = "{{:{}s}} = {{}}".format(max_len)
    for key in sorted(h.keys()):
        print(fmt.format(key, h[key]))

    plt.imshow(img, cmap="gray")
    plt.title(fn)
    plt.show()
Ejemplo n.º 5
0
def main_entry():
    import argparse
    description = """Find crystals in images."""

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('args',
                        type=str,
                        nargs='*',
                        metavar='IMG',
                        help='Images to find crystals in.')

    options = parser.parse_args()
    args = options.args

    from instamatic.formats import read_image
    import warnings
    warnings.simplefilter('ignore')

    for fn in args:
        img, h = read_image(fn)

        crystals = find_crystals_timepix(img,
                                         h['exp_magnification'],
                                         plot=True)

        for crystal in crystals:
            print(crystal)
Ejemplo n.º 6
0
def test_cbf(data, header):
    out = 'out.cbf'

    formats.write_cbf(out, data, header)

    assert os.path.exists(out)

    # Reader Not implemented:
    with pytest.raises(NotImplementedError):
        img, h = formats.read_image(out)
Ejemplo n.º 7
0
def test_hdf5(data, header):
    out = 'out.h5'

    formats.write_hdf5(out, data, header)

    assert os.path.exists(out)

    img, h = formats.read_image(out)

    assert np.allclose(img, data)
    assert header == h
Ejemplo n.º 8
0
def test_smv(data, header):
    out = 'out.smv'

    formats.write_adsc(out, data, header)

    assert os.path.exists(out)

    img, h = formats.read_image(out)

    assert np.allclose(img, data)
    assert 'value' in h  # changes type to str
    assert h['string'] == header['string']
Ejemplo n.º 9
0
def test_mrc(data, header):
    out = 'out.mrc'

    # Header not supported
    formats.write_mrc(out, data)

    assert os.path.exists(out)

    img, h = formats.read_image(out)

    assert np.allclose(img, data)
    assert isinstance(header, dict)
Ejemplo n.º 10
0
def main_entry():
    from instamatic.formats import read_image
    import warnings
    warnings.simplefilter('ignore')

    for fn in sys.argv[1:]:
        img, h = read_image(fn)

        crystals = find_crystals_timepix(img,
                                         h["exp_magnification"],
                                         plot=True)

        for crystal in crystals:
            print(crystal)
Ejemplo n.º 11
0
def main():
    import argparse
    description = """
Simple image viewer to open any image collected collected using instamatic. Supported formats include `TIFF`, `MRC`, [`HDF5`](http://www.h5py.org/), and [`SMV`](https://strucbio.biologie.uni-konstanz.de/ccp4wiki/index.php/SMV_file_format).
"""

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('args',
                        type=str,
                        nargs=1,
                        metavar='IMG',
                        help='Image to display (TIFF, HDF5, MRC, SMV).')

    options = parser.parse_args()
    args = options.args

    fn = args[0]

    img, h = read_image(fn)

    print(f"""Loading data: {fn}
        size: {img.nbytes / 1024} kB
       shape: {img.shape}
       range: {img.min()}-{img.max()}
       dtype: {img.dtype}
""")

    max_len = max(len(s) for s in h.keys())

    fmt = f'{{:{max_len}s}} = {{}}'
    for key in sorted(h.keys()):
        print(fmt.format(key, h[key]))

    plt.imshow(img, cmap='gray')
    plt.title(fn)
    plt.show()
Ejemplo n.º 12
0
fontdict = {'fontsize': 30}
vmax_im = 500
vmax_diff = 1500
vmin_diff = 0

save = True

number = 0

if not os.path.isdir('movie'):
    os.mkdir('movie')

for i, fn in enumerate(tqdm(fns)):
    dps = glob.glob(fn.replace('images', 'data').replace('.h5', '_*.h5'))

    im, h_im = read_image(fn)

    crystal_coords = np.array(h_im['exp_crystal_coords'])

    for j, dp in enumerate(dps):
        try:
            diff, h_diff = read_image(dp)
        except BaseException:
            print('fail')
            continue

        x, y = crystal_coords[j]

        fig, (ax1, ax2) = plt.subplots(1,
                                       2,
                                       figsize=(21.5, 10),
Ejemplo n.º 13
0
def calibrate_mag1_from_image_fn(center_fn, other_fn):
    """
    Calibrate pixel->stageposition coordinates from a set of images

    center_fn: `str`
        Reference image at the center of the grid (with the clover in the middle)
    other_fn: `tuple` of `str`
        Set of images to cross correlate to the first reference image

    return:
        instance of Calibration class with conversion methods
    """
    img_cent, h_cent = read_image(center_fn)

    # binsize = h_cent["ImageBinSize"]
    cam_dimensions = h_cent["ImageCameraDimensions"]
    bin_x, bin_y = cam_dimensions / np.array(img_cent.shape)
    assert bin_x == bin_y, "Binsizes do not match {bin_x} != {bin_y}"
    binsize = int(bin_x)

    img_cent, scale = autoscale(img_cent, maxdim=512)

    x_cent, y_cent, _, _, _ = h_cent["StagePosition"]
    # x_cent=40943.0
    # y_cent=-6258.4

    xy_cent = np.array([x_cent, y_cent])
    print("Center:", center_fn)
    print("Stageposition: x={:.0f} | y={:.0f}".format(*xy_cent))
    print()

    shifts = []
    stagepos = []

    # stage = ((30943.5, -16255.5),
    # (30874.701171875, -11258.2998046875),
    # (31009.701171875, -6256.89990234375),
    # (30876.0, -1256.9000244140625),
    # (31011.0, 3744.400146484375),
    # (35943.5, -16256.900390625),
    # (35874.6015625, -11256.900390625),
    # (36011.0, -6256.89990234375),
    # (35874.6015625, -1256.9000244140625),
    # (36012.30078125, 3743.0),
    # (40943.40234375, -16252.7001953125),
    # (40943.40234375, -11256.900390625),
    # (40943.40234375, -6258.30029296875),
    # (40943.40234375, -1256.9000244140625),
    # (40943.40234375, 3744.400146484375),
    # (45943.40234375, -16255.5),
    # (45943.40234375, -11258.2998046875),
    # (45943.40234375, -6255.5),
    # (45943.40234375, -1259.7000732421875),
    # (45943.40234375, 3745.800048828125),
    # (50943.40234375, -16255.5),
    # (50943.40234375, -11258.2998046875),
    # (50943.40234375, -6256.89990234375),
    # (50943.40234375, -1256.9000244140625),
    # (50943.40234375, 3743.0))

    for i, fn in enumerate(other_fn):
        img, h = read_image(fn)

        img = imgscale(img, scale)

        x_xobs, yobs, _, _, _ = h_cent["StagePosition"]
        # xobs, yobs = stage[i]
        print("Image:", fn)
        print(f"Stageposition: x={xobs:.0f} | y={yobs:.0f}")

        shift = cross_correlate(img_cent,
                                img,
                                upsample_factor=10,
                                verbose=False)
        print("Shift:", shift)
        print()

        stagepos.append((xobs, yobs))
        shifts.append(shift)

    # correct for binsize, store as binsize=1
    shifts = np.array(shifts) * binsize / scale
    stagepos = np.array(stagepos) - xy_cent

    c = CalibStage.from_data(shifts,
                             stagepos,
                             reference_position=xy_cent,
                             camera_dimensions=cam_dimensions)
    c.plot()
    c.to_file()

    return c