예제 #1
0
 def test_equal_crops_as_array(self, small_cont: ImageContainer,
                               as_array: bool):
     small_cont.add_img(np.random.normal(size=(small_cont.shape + (1, ))),
                        channel_dim="foobar",
                        layer="baz")
     for crop in small_cont.generate_equal_crops(size=11,
                                                 as_array=as_array):
         if as_array:
             if isinstance(as_array, bool):
                 assert isinstance(crop, dict)
                 for key in small_cont:
                     assert key in crop
                     assert crop[key].shape == (
                         11, 11, small_cont[key].data.shape[-1])
             elif isinstance(as_array, str):
                 assert isinstance(crop, np.ndarray)
                 assert crop.shape == (11, 11,
                                       small_cont[as_array].data.shape[-1])
             else:
                 assert isinstance(crop, tuple)
                 assert len(crop) == len(as_array)
                 for key, data in zip(as_array, crop):
                     assert isinstance(data, np.ndarray)
                     assert data.shape == (11, 11,
                                           small_cont[key].data.shape[-1])
         else:
             assert isinstance(crop, ImageContainer)
             for key in (Key.img.coords, Key.img.padding, Key.img.scale,
                         Key.img.mask_circle):
                 assert key in crop.data.attrs, key
             assert crop.shape == (11, 11)
예제 #2
0
    def test_plot_axis(self, cont: ImageContainer):
        cont.add_img(np.random.RandomState(42).normal(size=(*cont.shape, 3)),
                     layer="foo")
        fig, (ax1, ax2) = plt.subplots(ncols=2, dpi=DPI, tight_layout=True)

        cont.show("image", ax=ax1)
        cont.show("foo", ax=ax2)
예제 #3
0
    def test_spot_crops_as_array_return_obs(self, adata: AnnData,
                                            cont: ImageContainer,
                                            as_array: bool, return_obs: bool):
        cont.add_img(np.random.normal(size=(cont.shape + (4, ))),
                     channel_dim="foobar",
                     layer="baz")
        diameter = adata.uns["spatial"][Key.uns.library_id(
            adata, "spatial")]["scalefactors"]["spot_diameter_fullres"]
        radius = int(round(diameter // 2))
        size = (2 * radius + 1, 2 * radius + 1)

        for crop in cont.generate_spot_crops(adata,
                                             as_array=as_array,
                                             return_obs=return_obs,
                                             spatial_key="spatial"):
            crop, obs = crop if return_obs else (crop, None)
            if obs is not None:
                assert obs in adata.obs_names
                if not as_array:
                    assert Key.img.obs in crop.data.attrs

            if as_array is True:
                assert isinstance(crop, dict), type(crop)
                for key in cont:
                    assert key in crop
                    assert crop[key].shape == (*size, cont[key].data.shape[-1])
            elif isinstance(as_array, str):
                assert isinstance(crop, np.ndarray)
                assert crop.shape == (*size, cont[as_array].data.shape[-1])
            else:
                assert isinstance(crop, ImageContainer)
                assert crop.shape == size
예제 #4
0
    def test_image_autoincrement(self, small_cont_1c: ImageContainer):
        assert len(small_cont_1c) == 1
        for _ in range(20):
            small_cont_1c.add_img(np.empty(small_cont_1c.shape))

        assert len(small_cont_1c) == 21
        for i in range(20):
            assert f"image_{i}" in small_cont_1c
예제 #5
0
    def test_xarray_remapping_spatial_dims(self):
        cont = ImageContainer(np.empty((100, 10)))
        cont.add_img(xr.DataArray(np.empty((100, 10)), dims=["foo", "bar"]),
                     layer="baz")

        assert "baz" in cont
        assert len(cont) == 2
        assert cont["baz"].dims == ("y", "x", "channels")
예제 #6
0
 def test_add_img_invalid_yx(self, small_cont_1c: ImageContainer):
     arr = xr.DataArray(np.empty(
         (small_cont_1c.shape[0] - 1, small_cont_1c.shape[1])),
                        dims=["y", "x"])
     with pytest.raises(
             ValueError,
             match=
             r".*be aligned because they have different dimension sizes"):
         small_cont_1c.add_img(arr)
예제 #7
0
    def test_repr_html(self, size: int):
        cont = ImageContainer()
        for _ in range(size):
            cont.add_img(np.empty((10, 10)))

        validator = SimpleHTMLValidator(
            n_expected_rows=min(size, 10),
            expected_tags=set() if not size else {"p", "em", "strong"})
        validator.feed(cont._repr_html_())
        validator.validate()
예제 #8
0
파일: _utils.py 프로젝트: sophial05/squidpy
    def _download(self, fpath: PathLike, backup_url: str,
                  **kwargs: Any) -> Any:
        from squidpy.im import ImageContainer  # type: ignore[attr-defined]

        check_presence_download(Path(fpath), backup_url)

        img = ImageContainer()
        img.add_img(fpath, layer="image", **kwargs)

        return img
예제 #9
0
    def test_uncrop_preserves_shape(self, small_cont_1c: ImageContainer):
        small_cont_1c.add_img(np.random.normal(size=(small_cont_1c.shape +
                                                     (4, ))),
                              channel_dim="foobar",
                              layer="baz")
        crops = list(small_cont_1c.generate_equal_crops(size=13))

        uncrop = ImageContainer.uncrop(crops)

        np.testing.assert_array_equal(small_cont_1c.shape, uncrop.shape)
        for key in small_cont_1c:
            np.testing.assert_array_equal(uncrop[key], small_cont_1c[key])
예제 #10
0
    def test_crop_scale(self, cont_dot: ImageContainer):
        # crop with scaling
        mask = np.random.randint(low=0, high=10, size=cont_dot.shape)
        cont_dot.add_img(mask, layer="image_1", channel_dim="mask")

        crop = cont_dot.crop_center(y=50, x=20, radius=10, cval=5, scale=0.5)

        assert "image_0" in crop
        assert "image_1" in crop
        np.testing.assert_array_equal(crop.data["image_0"].shape,
                                      (21 // 2, 21 // 2, 10))
        np.testing.assert_array_equal(crop.data["image_1"].shape,
                                      (21 // 2, 21 // 2, 1))
예제 #11
0
    def test_crop_multiple_images(self, cont_dot: ImageContainer):
        mask = np.random.randint(low=0, high=10, size=cont_dot.shape)
        cont_dot.add_img(mask, layer="image_1", channel_dim="mask")

        crop = cont_dot.crop_center(
            y=50,
            x=20,
            radius=0,
            cval=5,
        )

        assert "image_0" in crop
        assert "image_1" in crop
        np.testing.assert_array_equal(crop.data["image_0"].shape, (1, 1, 10))
        np.testing.assert_array_equal(crop.data["image_1"].shape, (1, 1, 1))
예제 #12
0
    def test_plot_add_image(self, qtbot, adata: AnnData, napari_cont: ImageContainer):
        from napari.layers import Image

        viewer = napari_cont.interactive(adata)
        cnt = viewer._controller
        img = np.zeros((*napari_cont.shape, 3), dtype=np.float32)
        img[..., 0] = 1.0  # all red image

        napari_cont.add_img(img, layer="foobar")
        cnt.add_image("foobar")

        assert viewer._controller.view.layernames == {"V1_Adult_Mouse_Brain", "foobar"}
        assert isinstance(viewer._controller.view.layers["foobar"], Image)

        viewer.screenshot(dpi=DPI)
예제 #13
0
    def test_add_img_channel_dim(self, small_cont_1c: ImageContainer,
                                 channel_dim: str, n_channels: int):
        arr = np.random.normal(size=(*small_cont_1c.shape, n_channels))
        if channel_dim == "channels" and n_channels == 3:
            with pytest.raises(
                    ValueError,
                    match=
                    r".*be aligned because they have different dimension sizes"
            ):
                small_cont_1c.add_img(arr, channel_dim=channel_dim)
        else:
            small_cont_1c.add_img(arr, channel_dim=channel_dim, layer="bar")
            assert len(small_cont_1c) == 2
            assert "bar" in small_cont_1c
            assert small_cont_1c["bar"].dims == ("y", "x", channel_dim)

            np.testing.assert_array_equal(small_cont_1c["bar"], arr)
예제 #14
0
    def test_add_img(self, shape1: Tuple[int, ...], shape2: Tuple[int, ...]):
        img_orig = np.random.randint(low=0,
                                     high=255,
                                     size=shape1,
                                     dtype=np.uint8)
        cont = ImageContainer(img_orig, layer="img_orig")

        img_new = np.random.randint(low=0,
                                    high=255,
                                    size=shape2,
                                    dtype=np.uint8)
        cont.add_img(img_new, layer="img_new", channel_dim="mask")

        assert "img_orig" in cont
        assert "img_new" in cont
        np.testing.assert_array_equal(np.squeeze(cont.data["img_new"]),
                                      np.squeeze(img_new))
예제 #15
0
 def test_plot_as_mask(self, cont: ImageContainer):
     cont.add_img(np.random.RandomState(42).normal(size=(*cont.shape, 3)),
                  layer="foo")
     cont.show("foo", as_mask=True, channel=1)
예제 #16
0
 def test_add_img_number_of_channels(self, n_channels: int):
     img = ImageContainer()
     arr = np.random.rand(10, 10, n_channels)
     img.add_img(arr)
     assert img["image_0"].channels.shape == (n_channels, )