Exemplo n.º 1
0
def load_image(
    file_or_name: str,
    *,
    size: Optional[Union[int, Tuple[int, int]]],
    device: torch.device,
) -> torch.Tensor:
    file = os.path.abspath(os.path.expanduser(file_or_name))
    name = file_or_name

    images = demo.images()
    image: _Image
    if os.path.exists(file):
        image = LocalImage(file)
    elif name in images:
        image = images[name]
    else:
        path = pathlib.Path(file_or_name)
        could_be_name = not path.suffix and path.parent == pathlib.Path(".")
        if could_be_name:
            raise ValueError(
                add_suggestion(
                    f"Unknown demo image '{name}'.",
                    word=name,
                    possibilities=images._images.keys(),
                ))
        else:
            raise ValueError(f"The file {file} does not exist.")

    return image.read(size=size, device=device)
Exemplo n.º 2
0
    def test_guides_smoke(self, name, regions):
        image = demo.images()[name]

        assert isinstance(image.guides, data.DownloadableImageCollection)

        names, _ = zip(*iter(image.guides))
        assert set(names).issuperset(set(regions))
Exemplo n.º 3
0
    def test_smoke(self):
        images = demo.images()
        assert isinstance(images, data.DownloadableImageCollection)

        names, _ = zip(*iter(images))
        assert set(names) == {
            "bird1",
            "paint",
            "bird2",
            "mosaic",
            "castle",
            "church",
            "cliff",
        }
Exemplo n.º 4
0
    def test_file_starting_point(self, mock_execution_with):
        image = demo.images()["bird2"]
        expected = image.read()
        file = pathlib.Path(pystiche.home()) / image.file
        mock = self._mock_execution(
            mock_execution_with, option="starting_point", value=str(file)
        )

        with exits(), pytest.warns(UserWarning):
            main()

        (input_image, perceptual_loss), _ = mock.call_args

        ptu.assert_allclose(
            input_image,
            resize(expected, list(extract_image_size(perceptual_loss.content_image))),
        )
Exemplo n.º 5
0
    def test_file(self, mock_execution_with, option):
        image = demo.images()["bird2"]
        # TODO: make this independent of the default size value
        expected = image.read(size=500)
        file = pathlib.Path(pystiche.home()) / image.file
        mock = self._mock_execution(mock_execution_with, option=option, value=str(file))

        with exits():
            cli.main()

        (input_image, perceptual_loss), _ = mock.call_args

        if option == "content":
            actual = perceptual_loss.content_image
        else:  # option == "style":
            actual = perceptual_loss.style_image

        ptu.assert_allclose(actual, expected)
Exemplo n.º 6
0
    def test_demo_image(self, mock_execution_with, option):
        name = "bird2"
        mock = self._mock_execution(mock_execution_with, option=option, value=name)

        with exits():
            cli.main()

        (input_image, perceptual_loss), _ = mock.call_args

        if option == "content":
            image = perceptual_loss.content_image
        elif option == "style":
            image = perceptual_loss.style_image
        else:  # option == "starting_point"
            image = input_image

        ptu.assert_allclose(
            image, demo.images()[name].read(size=extract_image_size(image)),
        )
Exemplo n.º 7
0
from os import path

import pytest

from pystiche import demo

from .utils import (
    assert_downloads_correctly,
    assert_is_downloadable,
    rate_limited_urlopen,
    retry,
)
from tests.mocks import make_mock_target

IMAGES_AND_IDS = [
    (image, f"demo, {name}") for name, image in itertools.chain(demo.images(),)
]

IMAGE_PARAMETRIZE_KWARGS = dict(zip(("argvalues", "ids"), zip(*IMAGES_AND_IDS)))


def assert_image_is_downloadable(image, **kwargs):
    assert_is_downloadable(image.url, **kwargs)


@pytest.mark.slow
@pytest.mark.parametrize("image", **IMAGE_PARAMETRIZE_KWARGS)
def test_image_download_smoke(image):
    retry(lambda: assert_image_is_downloadable(image), times=2, wait=5.0)

########################################################################################
# We combine the ``content_loss`` and ``style_loss`` into a joined
# :class:`~pystiche.loss.PerceptualLoss`, which will serve as optimization criterion.

perceptual_loss = loss.PerceptualLoss(content_loss, style_loss).to(device)
print(perceptual_loss)


########################################################################################
# Images
# ------
#
# We now load and show the images that will be used in the NST. The images will be
# resized to ``size=500`` pixels.

images = demo.images()
images.download()
size = 500


########################################################################################
# .. note::
#
#   ``ìmages.download()`` downloads **all** demo images upfront. If you only want to
#   download the images for this example remove this line. They will be downloaded at
#   runtime instead.
#
# .. note::
#
#   If you want to work with other images you can load them with
#   :func:`~pystiche.image.read_image`: