def inspect(raw, roi):

    print("Reading raw data...")

    raw_data = raw.to_ndarray(roi=roi, fill_value=0)

    return spimagine.volshow(raw_data, stackUnits=raw.voxel_size[1:][::-1])
Beispiel #2
0
def _with_volshow(data, **kwargs):
    app = QtWidgets.QApplication(sys.argv)

    t = time.time()
    w = volshow(data, **kwargs)
    print("time to volshow: ", time.time() - t)

    QtCore.QTimer.singleShot(100, app.quit)
    app.exec_()
Beispiel #3
0
    def __create_viewer(self):

        raw_data = self.raw.to_ndarray(roi=self.roi, fill_value=0)

        if len(raw_data.shape) == 5:
            raw_data = raw_data[self.channel]
        if self.show_data:
            viewer = spimagine.volshow(
                raw_data, stackUnits=self.raw.voxel_size[1:][::-1])
            viewer.set_colormap("grays")
        else:
            viewer = spimagine.volshow(
                np.zeros(raw_data.shape),
                stackUnits=self.raw.voxel_size[1:][::-1])

        viewer.glWidget.transform._transformChanged.connect(
            lambda: self.__on_transform_changed())

        return viewer
Beispiel #4
0
def spimagine_show_volume_numpy(numpy_array, stackUnits=(1, 1, 1), \
                                interpolation="nearest", cmap="grays"):
    # Spimagine OpenCL volume renderer.
    volfig()
    spim_widget = \
            volshow(numpy_array, stackUnits=stackUnits, interpolation=interpolation)
    spim_widget.set_colormap(cmap)
    spim_widget.transform.setQuaternion(Quaternion(-0.005634209439510011,\
                                                    0.00790509382124309,\
                                                   -0.0013812284289010514,\
                                                   -0.9999519273706857))
Beispiel #5
0
def _with_volshow(data, **kwargs):
    app = QtWidgets.QApplication(sys.argv)


    t = time.time()
    w = volshow(data, **kwargs)
    print("time to volshow: ", time.time() - t)



    QtCore.QTimer.singleShot(100, app.quit)
    app.exec_()
Beispiel #6
0
 def show_frame( self, f, show_surfaces=False, show_centers=False, stackUnits=[1.,1.,1.], raise_window=True ):
     assert f>=0 and f<len(self.images)
     
     self.current_frame = f
     if self.spimagine is None:
         self.spimagine = volshow(self.images[f], stackUnits = stackUnits, raise_window=raise_window, autoscale=False)
     else:
         self.spimagine.glWidget.renderer.update_data(self.images[f])
         self.spimagine.glWidget.refresh()
     
     # remove all meshes (might eg exist from last call)
     self.hide_all_objects()
     
     for oid in range(len(self.object_names)):
         netsurf = self.netsurfs[oid][f]
         if not netsurf is None:
             if show_centers:  self.spimagine.glWidget.add_mesh( 
                     netsurf.create_center_mesh( facecolor=self.colors_diverse[0]) )
             if show_surfaces: self.spimagine.glWidget.add_mesh( 
                     netsurf.create_surface_mesh( facecolor=self.colors_diverse[0]) )
     return self.spimagine
Beispiel #7
0
    hyp = watershed(potential, label(potential < 0.1)[0], mask=potential < 0.5)
    if with_border_cells == False:
        mask_borders = lib.mask_border_objs(hyp)
        hyp[mask_borders] = 0
    nhl = lib.hyp2nhl(hyp, img[..., 1])
    nhl = np.array(nhl)
    areas = np.array([n['area'] for n in nhl])
    xmom = np.array([n['moments_img'][0, 0, 0] / n['area'] for n in nhl])
    col = plt.scatter(np.log2(areas), xmom)  #np.log2(xmom))
    # selector = view.SelectFromCollection(plt.gca(), col)
    return nhl, hyp


img_spim = img6[0, ..., 1]
w = spimagine.volshow(img_spim,
                      interpolation='nearest',
                      stackUnits=[1.0, 1.0, 1.0])


def update_selection(r):
    # img = img6[1,...,1].copy()
    # img = w.glWidget.dataModel[]
    img2 = img_spim.copy()
    mask = lib.mask_nhl(nhl[selector.ind], hyp)
    img2[mask] = img2[mask] * r
    lib.update_spim(w, 0, img2)


def update_stack(r):
    img = img_spim.copy()
    mask = lib.mask_nhl(nhl[selector.ind], hyp)
import numpy as np
import matplotlib
matplotlib.use("Qt5Agg")

from matplotlib.pyplot import cm
from spimagine import volshow
import OpenGL.GL as GL

if __name__ == '__main__':

    data = np.einsum("ij,k", np.ones((100, ) * 2), np.linspace(0, 1, 100))
    w = volshow(data)
    w.glWidget._set_colormap_array(cm.hot(np.linspace(0, 1, 2**12))[:, :3])

    print("maximal texture size: ", GL.glGetIntegerv(GL.GL_MAX_TEXTURE_SIZE))
                        proj, DR, offset=offset,
                        mode="constant", cval=0, order=2)
        proj *= 0.98
        out += rotate
    
    # visualize the axes
    out[0,0,0] = np.max(out)    #origin
    out[-1,0,0] = np.max(out)/2 # x
    out[0,-1,0] = np.max(out)/3 # z
    # show arrows pointing at projection directions (should form cone aligned with y)
    fig = plt.figure(figsize=(10,10))
    ax = fig.add_subplot(111, projection='3d')    
    for vec in vectors:
        u,v,w = vec
        a = Arrow3D([0,u],[0,v],[0,w], mutation_scale=20, lw=1, arrowstyle="-|>")
        ax.add_artist(a)
    
    radius=1
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    ax.set_xlim(-radius*1.5, radius*1.5)
    ax.set_ylim(-radius*1.5, radius*1.5)
    ax.set_zlim(-radius*1.5, radius*1.5)
    plt.tight_layout()
    plt.show()

    # show backprojection of test volume (should be cone aligned with y)
    spimagine.volshow(out)
    import IPython
    IPython.embed()    
Beispiel #10
0
    def test_two_disjoint_lines_softmask(self):
        LABEL_RADIUS = 3
        RAW_RADIUS = 3
        # exagerated to show problem
        BLEND_SMOOTHNESS = 10

        bb = Roi(Coordinate([0, 0, 0]), ([256, 256, 256]))
        voxel_size = Coordinate([1, 1, 1])
        swc_files = ("test_line_a.swc", "test_line_b.swc")
        swc_paths = tuple(
            Path(self.path_to(file_name)) for file_name in swc_files)

        # create two lines seperated by a given distance and write them to swc files
        intercepts, slopes = self._get_line_pair(roi=bb, dist=3 * LABEL_RADIUS)
        for intercept, slope, swc_path in zip(intercepts, slopes, swc_paths):
            swc_points = self._get_points(intercept, slope, bb)
            self._write_swc(swc_path, swc_points)

        # create swc sources
        fused = ArrayKey("FUSED")
        fused_labels = ArrayKey("FUSED_LABELS")
        swc_key_names = ("SWC_A", "SWC_B")
        labels_key_names = ("LABELS_A", "LABELS_B")
        raw_key_names = ("RAW_A", "RAW_B")

        swc_keys = tuple(PointsKey(name) for name in swc_key_names)
        labels_keys = tuple(ArrayKey(name) for name in labels_key_names)
        raw_keys = tuple(ArrayKey(name) for name in raw_key_names)

        # add request
        request = BatchRequest()
        request.add(fused, bb.get_shape())
        request.add(fused_labels, bb.get_shape())
        request.add(labels_keys[0], bb.get_shape())
        request.add(labels_keys[1], bb.get_shape())
        request.add(raw_keys[0], bb.get_shape())
        request.add(raw_keys[1], bb.get_shape())
        request.add(swc_keys[0], bb.get_shape())
        request.add(swc_keys[1], bb.get_shape())

        # data source for swc a
        data_sources_a = tuple()
        data_sources_a = (data_sources_a + SwcFileSource(
            swc_paths[0], swc_keys[0], PointsSpec(roi=bb)) + RasterizeSkeleton(
                points=swc_keys[0],
                array=labels_keys[0],
                array_spec=ArraySpec(interpolatable=False,
                                     dtype=np.uint32,
                                     voxel_size=voxel_size),
                radius=LABEL_RADIUS,
            ) + RasterizeSkeleton(
                points=swc_keys[0],
                array=raw_keys[0],
                array_spec=ArraySpec(interpolatable=False,
                                     dtype=np.uint32,
                                     voxel_size=voxel_size),
                radius=RAW_RADIUS,
            ))

        # data source for swc b
        data_sources_b = tuple()
        data_sources_b = (data_sources_b + SwcFileSource(
            swc_paths[1], swc_keys[1], PointsSpec(roi=bb)) + RasterizeSkeleton(
                points=swc_keys[1],
                array=labels_keys[1],
                array_spec=ArraySpec(interpolatable=False,
                                     dtype=np.uint32,
                                     voxel_size=voxel_size),
                radius=LABEL_RADIUS,
            ) + RasterizeSkeleton(
                points=swc_keys[1],
                array=raw_keys[1],
                array_spec=ArraySpec(interpolatable=False,
                                     dtype=np.uint32,
                                     voxel_size=voxel_size),
                radius=RAW_RADIUS,
            ))
        data_sources = tuple([data_sources_a, data_sources_b
                              ]) + MergeProvider()

        pipeline = data_sources + FusionAugment(
            raw_keys[0],
            raw_keys[1],
            labels_keys[0],
            labels_keys[1],
            fused,
            fused_labels,
            blend_mode="labels_mask",
            blend_smoothness=BLEND_SMOOTHNESS,
            num_blended_objects=0,
        )

        with build(pipeline):
            batch = pipeline.request_batch(request)

        fused_data = batch[fused].data
        fused_data = np.pad(fused_data, (1, ),
                            "constant",
                            constant_values=(0, ))

        a_data = batch[raw_keys[0]].data
        a_data = np.pad(a_data, (1, ), "constant", constant_values=(0, ))

        b_data = batch[raw_keys[1]].data
        b_data = np.pad(b_data, (1, ), "constant", constant_values=(0, ))

        all_data = np.zeros((5, ) + fused_data.shape)
        all_data[0, :, :, :] = fused_data
        all_data[1, :, :, :] = a_data + b_data
        all_data[2, :, :, :] = fused_data - a_data - b_data
        all_data[3, :, :, :] = a_data
        all_data[4, :, :, :] = b_data

        # Uncomment to visualize problem
        if imported_volshow:
            volshow(all_data)
            # input("Press enter when you are done viewing the data: ")

        diff = np.linalg.norm(fused_data - a_data - b_data)
        self.assertAlmostEqual(diff, 0)
Beispiel #11
0
def single_data(data, t_close_ms= 1000, **kwargs):
    w = volshow(data,raise_window = False, **kwargs)
    QtCore.QTimer.singleShot(t_close_ms,w.closeMe)

    qt_exec()
Beispiel #12
0
import numpy as np
import sys

import skimage.io as io
import matplotlib.pyplot as plt
plt.ion()
from scipy.ndimage import zoom, label
from scipy.signal import gaussian
from scipy.ndimage.morphology import binary_dilation

from tabulate import tabulate
import pandas
from skimage.morphology import watershed
from segtools import voronoi

import gputools
import spimagine

from segtools import cell_view_lib as view
from segtools import lib

ys_avgd = np.load('training/t005/ys_avgd.npy')
ys_unet_dense_0 = np.load('data_predict/ys_unet_dense_0.npy')
ys_unet_dense_0_upscaled = zoom(ys_unet_dense_0, (356 / 71, 1, 1, 1))

ys_unet_dense_0_upscaled = lib.normalize_percentile_to01(
    ys_unet_dense_0_upscaled, 0, 100)

iss = view.ImshowStack(ys_avgd, colorchan=True)
w = spimagine.volshow(ys_avgd[..., 0], interpolation="nearest")
Beispiel #13
0
import numpy as np
import matplotlib
matplotlib.use("Qt5Agg")

from matplotlib.pyplot import cm
from spimagine import volshow
import OpenGL.GL as GL


if __name__ == '__main__':

    data = np.einsum("ij,k",np.ones((100,)*2), np.linspace(0,1,100))
    w = volshow(data)
    w.glWidget._set_colormap_array(cm.hot(np.linspace(0,1,2**12))[:,:3])

    print("maximal texture size: ", GL.glGetIntegerv(GL.GL_MAX_TEXTURE_SIZE))
Beispiel #14
0
def single_data(data):
    w = volshow(data, raise_window=False)
    QtCore.QTimer.singleShot(1000, w.closeMe)
    qt_exec()
Beispiel #15
0
import numpy as np
from PyQt5 import QtCore
import logging
from spimagine import volshow, volfig, logger, qt_exec, NumpyData, DataModel


def single_data(data):
    w = volshow(data, raise_window=False)
    QtCore.QTimer.singleShot(1000, w.closeMe)
    qt_exec()


def test_volumes():
    d = np.random.uniform(0, 100, (100, ) * 3)

    for dtype in (np.float32, np.int8, np.uint16, np.int32):
        print("testing: %s" % dtype)
        single_data(d.astype(dtype))


if __name__ == '__main__':
    data = np.linspace(0, 255, 100**3).reshape((100, ) * 3).transpose(
        (1, 2, 0))

    m = DataModel(NumpyData(data.astype(np.uint8)))
    w = volshow(m)

    QtCore.QTimer.singleShot(1000, w.closeMe)
    qt_exec()