예제 #1
0
파일: image_test.py 프로젝트: Amos-zq/menpo
def test_image_gradient_sanity():
    # Only a sanity check - does it run and generate sensible output?
    image = Image(np.zeros([120, 120, 3]))
    new_image = image.gradient()
    assert(type(new_image) == Image)
    assert(new_image.shape == image.shape)
    assert(new_image.n_channels == image.n_channels * 2)
예제 #2
0
def test_image_clip_pixels_cutom_max_uint():
    pixels = (np.random.rand(3, 10, 20) * 255).astype(np.uint8)
    # add the noise of increased values
    pixels[0, 0, 0] = 255
    image = Image(pixels, copy=False)
    image2 = image.clip_pixels(maximum=200)
    assert(image2.pixels.max() <= 200)
예제 #3
0
def test_texturedtrimesh_copy():
    points = np.ones([10, 3])
    tcoords = np.ones([10, 3])
    trilist = np.ones([10, 3])
    landmarks = PointCloud(np.ones([3, 3]), copy=False)
    landmarks_im = PointCloud(np.ones([3, 2]), copy=False)
    pixels = np.ones([10, 10, 1])
    texture = Image(pixels, copy=False)
    texture.landmarks['test_im'] = landmarks_im

    ttmesh = TexturedTriMesh(points, tcoords, texture, trilist=trilist,
                             copy=False)
    ttmesh.landmarks['test'] = landmarks
    ttmesh_copy = ttmesh.copy()

    assert (not is_same_array(ttmesh_copy.points, ttmesh.points))
    assert (not is_same_array(ttmesh_copy.trilist, ttmesh.trilist))
    assert (not is_same_array(ttmesh_copy.tcoords.points,
                              ttmesh.tcoords.points))
    assert (not is_same_array(ttmesh_copy.texture.pixels,
                              ttmesh.texture.pixels))
    assert (not is_same_array(
        ttmesh_copy.texture.landmarks['test_im'].lms.points,
        ttmesh.texture.landmarks['test_im'].lms.points))
    assert (not is_same_array(ttmesh_copy.landmarks['test'].lms.points,
                              ttmesh.landmarks['test'].lms.points))
예제 #4
0
def test_rotate_image_90_180():
    image = Image(np.array([[1., 2., 3., 4.],
                            [5., 6., 7., 8.],
                            [9., 10., 11., 12.]]))
    image.landmarks['temp'] = PointCloud(np.array([[1., 1.], [1., 2.],
                                                   [2., 1.], [2., 2.]]))
    # rotate 90 degrees
    rotated_img = image.rotate_ccw_about_centre(theta=90, order=0)
    rotated_img.landmarks['temp'] = rotated_img.landmarks['temp'].constrain_to_bounds(
        rotated_img.bounds())
    assert_allclose(rotated_img.pixels, np.array([[[4., 8., 12.],
                                                   [3., 7., 11.],
                                                   [2., 6., 10.],
                                                   [1., 5., 9.]]]))
    assert_almost_equal(rotated_img.landmarks['temp'].points,
                        np.array([[2., 1.], [1., 1.], [2., 2.], [1., 2.]]))

    # rotate 180 degrees
    rotated_img = image.rotate_ccw_about_centre(theta=180, order=0)
    rotated_img.landmarks['temp'] = rotated_img.landmarks['temp'].constrain_to_bounds(
        rotated_img.bounds())
    assert_allclose(rotated_img.pixels, np.array([[[12., 11., 10., 9.],
                                                   [8., 7., 6., 5.],
                                                   [4., 3., 2., 1.]]]))
    assert_almost_equal(rotated_img.landmarks['temp'].points,
                        np.array([[1., 2.], [1., 1.], [0., 2.], [0., 1.]]))
예제 #5
0
def test_as_greyscale_average():
    ones = np.ones([3, 120, 120])
    image = Image(ones, copy=True)
    image.pixels[0].fill(0.5)
    new_image = image.as_greyscale(mode='average')
    assert (new_image.shape == image.shape)
    assert (new_image.n_channels == 1)
    assert_allclose(new_image.pixels[0], ones[0] * 0.83333333)
예제 #6
0
파일: image_test.py 프로젝트: Amos-zq/menpo
def test_image_from_vector_inplace_no_copy_warning():
        pixels = np.random.rand(10, 20, 2)
        pixels2 = np.random.rand(10, 20, 2)
        image = Image(pixels)
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            image.from_vector_inplace(pixels2.ravel()[::-1], copy=False)
            assert len(w) == 1
예제 #7
0
파일: image_test.py 프로젝트: Amos-zq/menpo
def test_normalize_norm_image():
    pixels = np.ones((120, 120, 3))
    pixels[..., 0] = 0.5
    pixels[..., 1] = 0.2345
    image = Image(pixels)
    image.normalize_norm_inplace()
    assert_allclose(np.mean(image.pixels), 0, atol=1e-10)
    assert_allclose(np.linalg.norm(image.pixels), 1)
예제 #8
0
def test_copy_landmarks_and_path_with_no_lms_path():
    img = Image.init_blank((5, 5))
    new_img = Image.init_blank((5, 5))
    copy_landmarks_and_path(img, new_img)
    assert not hasattr(img, "path")
    assert not hasattr(new_img, "path")
    assert not img.has_landmarks
    assert not new_img.has_landmarks
예제 #9
0
파일: image_test.py 프로젝트: nontas/menpo
def test_as_greyscale_luminosity():
    ones = np.ones([3, 120, 120])
    image = Image(ones, copy=True)
    image.pixels[0].fill(0.5)
    new_image = image.as_greyscale(mode="luminosity")
    assert new_image.shape == image.shape
    assert new_image.n_channels == 1
    assert_allclose(new_image.pixels[0], ones[0] * 0.850532)
예제 #10
0
def test_normalize_norm_image():
    pixels = np.ones((3, 120, 120))
    pixels[0] = 0.5
    pixels[1] = 0.2345
    image = Image(pixels)
    new_image = image.normalize_norm()
    assert_allclose(np.mean(new_image.pixels), 0, atol=1e-10)
    assert_allclose(np.linalg.norm(new_image.pixels), 1)
예제 #11
0
def test_normalize_std_image():
    pixels = np.ones((3, 120, 120))
    pixels[0] = 0.5
    pixels[1] = 0.2345
    image = Image(pixels)
    image.normalize_std_inplace()
    assert_allclose(np.mean(image.pixels), 0, atol=1e-10)
    assert_allclose(np.std(image.pixels), 1)
예제 #12
0
def test_image_copy():
    pixels = np.ones([1, 10, 10])
    landmarks = PointCloud(np.ones([3, 2]), copy=False)
    im = Image(pixels, copy=False)
    im.landmarks['test'] = landmarks
    im_copy = im.copy()

    assert (not is_same_array(im.pixels, im_copy.pixels))
    assert (not is_same_array(im_copy.landmarks['test'].points,
                              im.landmarks['test'].points))
예제 #13
0
파일: image_test.py 프로젝트: dvdm/menpo
def test_normalize_norm_image():
    pixels = np.ones((3, 120, 120))
    pixels[0] = 0.5
    pixels[1] = 0.2345
    image = Image(pixels)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        new_image = image.normalize_norm()
    assert_allclose(np.mean(new_image.pixels), 0, atol=1e-10)
    assert_allclose(np.linalg.norm(new_image.pixels), 1)
예제 #14
0
def test_normalize_std_image_per_channel():
    pixels = np.random.randn(3, 120, 120)
    pixels[1] *= 9
    pixels[0] += -3
    pixels[2] /= 140
    image = Image(pixels)
    image.normalize_std_inplace(mode='per_channel')
    assert_allclose(
        np.mean(image.as_vector(keep_channels=True), axis=1), 0, atol=1e-10)
    assert_allclose(
        np.std(image.as_vector(keep_channels=True), axis=1), 1)
예제 #15
0
def test_warp_to_mask_image():
    img = Image.init_blank((10, 10), n_channels=2)
    img.pixels[:, :, :5] = 0.5
    template_mask = BooleanImage.init_blank((10, 10))
    template_mask.pixels[:, 5:, :] = False
    t = Affine.init_identity(2)
    warped_img = img.warp_to_mask(template_mask, t)
    assert(type(warped_img) == MaskedImage)
    result = Image.init_blank((10, 10), n_channels=2).pixels
    result[:, :5, :5] = 0.5
    assert(np.all(result == warped_img.pixels))
예제 #16
0
def test_image_clip_pixels_cutom_max():
    pixels = np.random.rand(3, 10, 20)
    # add the noise of increased values
    pixels *= 2.0
    pixels[0, 0, 0] = 3.0
    pixels[0, 0, 1] = - 0.1
    image = Image(pixels, copy=False)
    assert(image.pixels.max() > 1.0)
    image2 = image.clip_pixels(maximum=0.9)
    assert(image2.pixels.max() <= 0.9)
    assert(image2.pixels.min() >= 0.0)
예제 #17
0
파일: image_test.py 프로젝트: nontas/menpo
def test_normalize_norm_image_per_channel():
    pixels = np.random.randn(3, 120, 120)
    pixels[1] *= 17
    pixels[0] += -114
    pixels[2] /= 30
    image = Image(pixels)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        new_image = image.normalize_norm(mode="per_channel")
    assert_allclose(np.mean(new_image.as_vector(keep_channels=True), axis=1), 0, atol=1e-10)
    assert_allclose(np.linalg.norm(new_image.as_vector(keep_channels=True), axis=1), 1)
예제 #18
0
파일: image_test.py 프로젝트: Amos-zq/menpo
def test_normalize_norm_image_per_channel():
    pixels = np.random.randn(120, 120, 3)
    pixels[..., 1] *= 17
    pixels[..., 0] += -114
    pixels[..., 2] /= 30
    image = Image(pixels)
    image.normalize_norm_inplace(mode='per_channel')
    assert_allclose(
        np.mean(image.as_vector(keep_channels=True), axis=0), 0, atol=1e-10)
    assert_allclose(
        np.linalg.norm(image.as_vector(keep_channels=True), axis=0), 1)
예제 #19
0
def test_normalize_norm_image_per_channel():
    pixels = np.random.randn(3, 120, 120)
    pixels[1] *= 17
    pixels[0] += -114
    pixels[2] /= 30
    image = Image(pixels)
    new_image = image.normalize_norm(mode='per_channel')
    assert_allclose(
        np.mean(new_image.as_vector(keep_channels=True), axis=1), 0,
        atol=1e-10)
    assert_allclose(
        np.linalg.norm(new_image.as_vector(keep_channels=True), axis=1), 1)
예제 #20
0
def test_mirror_vertical_image():
    image = Image(np.array([[1., 2., 3., 4.],
                            [5., 6., 7., 8.],
                            [9., 10., 11., 12.]]))
    image.landmarks['temp'] = PointCloud(np.array([[1., 0.], [1., 1.],
                                                   [2., 1.], [2., 2.]]))
    mirrored_img = image.mirror()
    assert_allclose(mirrored_img.pixels,
                    np.array([[[4., 3., 2., 1.],
                               [8., 7., 6., 5.],
                               [12., 11., 10., 9.]]]))
    assert_allclose(mirrored_img.landmarks['temp'].points,
                    np.array([[1., 3.], [1., 2.], [2., 2.], [2., 1.]]))
예제 #21
0
def test_mirror_horizontal_image():
    image = Image(np.array([[1., 2., 3., 4.],
                            [5., 6., 7., 8.],
                            [9., 10., 11., 12.]]))
    image.landmarks['temp'] = PointCloud(np.array([[1., 1.], [1., 2.],
                                                   [2., 1.], [2., 2.]]))
    mirrored_img = image.mirror(axis=0)
    assert_allclose(mirrored_img.pixels,
                    np.array([[[9., 10., 11., 12.],
                               [5., 6., 7., 8.],
                               [1., 2., 3., 4.]]]))
    assert_allclose(mirrored_img.landmarks['temp'].points,
                    np.array([[1., 1.], [1., 2.], [0., 1.], [0., 2.]]))
예제 #22
0
def test_transform_about_centre():
    pixels_16 = np.arange(16, dtype=np.float)
    image = Image(pixels_16.reshape(4, 4))
    transform = Rotation.init_from_2d_ccw_angle(180).compose_before(
        UniformScale(2, n_dims=2))
    # rotate 90 + scale degrees
    transformed_img = image.transform_about_centre(transform, order=0)
    expected_pixels = np.rot90(np.repeat(np.repeat(pixels_16, 2).reshape(4, -1),
                                         2, axis=0)[1:, 1:],
                               k=2)

    assert transformed_img.shape == (7, 7)
    assert_allclose(transformed_img.pixels[0], expected_pixels)
예제 #23
0
파일: image_test.py 프로젝트: dvdm/menpo
def test_normalize_std_image_per_channel():
    pixels = np.random.randn(3, 120, 120)
    pixels[1] *= 9
    pixels[0] += -3
    pixels[2] /= 140
    image = Image(pixels)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        new_image = image.normalize_std(mode='per_channel')
    assert_allclose(
        np.mean(new_image.as_vector(keep_channels=True), axis=1), 0,
        atol=1e-10)
    assert_allclose(
        np.std(new_image.as_vector(keep_channels=True), axis=1), 1)
예제 #24
0
def build_parts_image(image, centres, parts_shape, offsets=np.array([[0, 0]]),
                      normalize_parts=False):

    # extract patches
    parts = image.extract_patches(PointCloud(np.round(centres.points)), np.array(parts_shape), offsets)

    # build parts image
    # img.pixels: n_centres x n_offsets x n_channels x height x width
    img = Image(parts)

    if normalize_parts:
        # normalize parts if required
        img.normalize_norm_inplace(mode='per_channel')

    return img
예제 #25
0
def my_2d_rasterizer(im, fn=None, group=None, f=None, crop=False, message=None):
    """
    Visualisation related function. It accepts a menpo image and renders
    a **single** pair of landmarks in a new image.
    The fn offers the chance to apply a custom function to the image.
    ASSUMPTION: There is no check for the case of no landmarks in the image.
    :param im: menpo image.
    :param fn: (optional) If None, then the default .view_landmarks() is
        used for visualisation, otherwise the provided function.
    :param group: (optional) Used in case fn is None.
    :param f: (optional) Matplotlib figure to use. Leave None, unless
        you know how to modify.
    :param crop: (optional) Crop the resulting visualisation to avoid the
        the excessive white boundary. By default False.
    :param message: (optional) If None, nothing is added in the image. If a
        string is passed, then this is annotated (as text) with matplotlib
        utilities, i.e. the exact same text is written in the image.
    :return: menpo rasterised image.
    """
    if fn is None:
        f = plt.figure(frameon=False)
        if group is None:
            # in this case, assume that the first group of landmarks should suffice.
            group = im.landmarks.group_labels[0]
        r = im.view_landmarks(group=group)
    else:
        fn(im)
    if message is not None:
        assert isinstance(message, str)
        st1 = 25 + 90 * crop
        t = plt.annotate(message, xy=(st1, im.shape[0] - 10),
                         size=26, fontweight='bold', color='b')
        # set background transparency
        t.set_bbox(dict(color='w', alpha=0.5, edgecolor='w'))
    # get the image from plt
    f.tight_layout(pad=0)
    # Get the pixels directly from the canvas buffer which is fast
    c_buffer, shape = f.canvas.print_to_buffer()
    # Turn buffer into numpy array and reshape to image
    pixels_buffer = np.fromstring(c_buffer,
                                  dtype=np.uint8).reshape(shape[::-1] + (-1,))
    # Prevent matplotlib from rendering
    plt.close(f)
    # Ignore the Alpha channel
    im_plt = Image.init_from_channels_at_back(pixels_buffer[..., :3])
    # ensure that they have the same dtype as the original pixels.
    dtype = im.pixels.dtype
    if dtype != np.uint8:
        if dtype == np.float32 or dtype == np.float64:
            im_plt.pixels = im_plt.pixels.astype(dtype)
            im_plt.pixels /= 255.0
        else:
            m1 = 'Not recognised type of original dtype ({}).'
            print(m1.format(dtype))
    if crop:
            # # position to crop the rasterised image (hardcoded for now).
            cri = (50, 60)
            sh1 = im_plt.shape
            im_plt = im_plt.crop((cri[0], cri[1]), (sh1[0] + cri[0], sh1[1] + cri[1]))
    return im_plt
예제 #26
0
파일: rasterize.py 프로젝트: dvdm/menpo
def _rasterize_matplotlib(image, pclouds, render_lines=True, line_style='-',
                          line_colour='b', line_width=1, render_markers=True,
                          marker_style='o', marker_size=1,
                          marker_face_colour='b', marker_edge_colour='b',
                          marker_edge_width=1):
    import matplotlib.pyplot as plt

    # Convert image shape into 100 DPI inches
    # This makes sure we maintain the original image size
    image_shape = np.array(image.shape)[::-1] / 100.0
    f = plt.figure(figsize=image_shape, frameon=False, dpi=100)

    image.view(figure_id=f.number, figure_size=image_shape)
    for k, p in enumerate(pclouds):
        p.view(figure_id=f.number, render_axes=False, figure_size=image_shape,
               render_lines=render_lines[k], line_style=line_style[k],
               line_colour=line_colour[k], line_width=line_width[k],
               render_markers=render_markers[k], marker_style=marker_style[k],
               marker_size=marker_size[k],
               marker_face_colour=marker_face_colour[k],
               marker_edge_colour=marker_edge_colour[k],
               marker_edge_width=marker_edge_width[k])

    # Make sure the layout is tight so that the image is of the original size
    f.tight_layout(pad=0)
    # Get the pixels directly from the canvas buffer which is fast
    c_buffer, shape = f.canvas.print_to_buffer()
    # Turn buffer into numpy array and reshape to image
    pixels_buffer = np.fromstring(c_buffer,
                                  dtype=np.uint8).reshape(shape[::-1] + (-1,))
    # Prevent matplotlib from rendering
    plt.close(f)
    # Ignore the Alpha channel
    return Image.init_from_channels_at_back(pixels_buffer[..., :3])
def test_crop_to_landmarks():
    img = Image.init_blank((100, 100), n_channels=1)
    img.landmarks['test'] = bounding_box([0, 0], [10, 10])

    img_cropped = img.crop_to_landmarks()
    assert_allclose(img_cropped.shape, (10, 10))
    assert 1
예제 #28
0
    def iter_image(self):
        r"""
        Returns a copy of the fitted image with a as many landmark groups as
        iteration run by fitting procedure:
            - ``iter_0``, containing the initial shape.
            - ``iter_1``, containing the the fitted shape at the first
            iteration.
            - ``...``
            - ``iter_n``, containing the final fitted shape.

        :type: :map:`Image`
        """
        image = Image(self.image.pixels)
        for j, s in enumerate(self.shapes()):
            image.landmarks['iter_'+str(j)] = s
        return image
def test_rescale_to_pointcloud():
    img = Image.init_blank((100, 100), n_channels=1)
    img.landmarks['test'] = bounding_box([0, 0], [10, 10])
    pcloud = bounding_box([0, 0], [25, 25])

    img_rescaled = img.rescale_to_pointcloud(pcloud)
    assert_allclose(img_rescaled.shape, (250, 250))
예제 #30
0
def test_rotate_image_45():
    image = Image(np.array([[1., 2., 3., 4.],
                            [5., 6., 7., 8.],
                            [9., 10., 11., 12.],
                            [13., 14., 15., 16.]]))
    image.landmarks['temp'] = PointCloud(np.array([[1., 1.], [1., 2.],
                                                   [2., 1.], [2., 2.]]))
    rotated_img = image.rotate_ccw_about_centre(theta=45, order=0)
    assert_allclose(rotated_img.pixels,
                    np.array([[[0., 0., 4., 0., 0.],
                               [0., 3., 7., 8., 0.],
                               [1., 6., 7., 11., 16.],
                               [0., 5., 10., 15., 15.],
                               [0., 0., 13., 14., 0.]]]))
    assert_almost_equal(rotated_img.landmarks['temp'].points,
                        np.array([[2.121, 1.414], [1.414, 2.121],
                                  [2.828, 2.121], [2.121, 2.828]]), decimal=3)
예제 #31
0
from collections import OrderedDict
from mock import patch, MagicMock
import numpy as np
from nose.tools import raises
from scipy.sparse import csr_matrix

from menpo.image import Image
from menpo.shape import (TriMesh, TexturedTriMesh, ColouredTriMesh, PointCloud,
                         LabelledPointUndirectedGraph)
from menpo.visualize import Menpo3dMissingError
from menpo.testing import surrogate

fake_triangle = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
fake_trilist = np.array([[0, 1, 2]], dtype=np.uint32)
fake_texture = Image.init_blank([10, 10])
fake_tcoords = np.array([[0, 0], [0.5, 0.5], [1.0, 1.0]])
menpo3d_visualize_mock = MagicMock()
menpo3d_visualize_mock.side_effect = ImportError


@surrogate('menpo3d.visualize.TriMeshViewer3d')
@patch('menpo3d.visualize.TriMeshViewer3d', menpo3d_visualize_mock)
@raises(Menpo3dMissingError)
def trimesh_viewer_test():
    TriMesh(fake_triangle, trilist=fake_trilist, copy=False).view()


@surrogate('menpo3d.visualize.TexturedTriMeshViewer3d')
@patch('menpo3d.visualize.TexturedTriMeshViewer3d', menpo3d_visualize_mock)
@raises(Menpo3dMissingError)
def textured_trimesh_viewer_test():
예제 #32
0
파일: image.py 프로젝트: zhangyangang/menpo
def pillow_importer(filepath, asset=None, normalize=True, **kwargs):
    r"""
    Imports an image using PIL/pillow.

    Different image modes cause different importing strategies.

    RGB, L, I:
        Imported as either `float` or `uint8` depending on normalisation flag.
    RGBA:
        Imported as :map:`MaskedImage` if normalize is ``True`` else imported
        as a 4 channel `uint8` image.
    1:
        Imported as a :map:`BooleanImage`. Normalisation is ignored.
    F:
        Imported as a floating point image. Normalisation is ignored.

    Parameters
    ----------
    filepath : `Path`
        Absolute filepath of image
    asset : `object`, optional
        An optional asset that may help with loading. This is unused for this
        implementation.
    normalize : `bool`, optional
        If ``True``, normalize between 0.0 and 1.0 and convert to float. If
        ``False`` just pass whatever PIL imports back (according
        to types rules outlined in constructor).
    \**kwargs : `dict`, optional
        Any other keyword arguments.

    Returns
    -------
    image : :map:`Image` or subclass
        The imported image.
    """
    import PIL.Image as PILImage

    pil_image = PILImage.open(str(filepath))
    mode = pil_image.mode
    if mode == 'RGBA':
        # If normalize is False, then we return the alpha as an extra
        # channel, which can be useful if the alpha channel has semantic
        # meanings!
        if normalize:
            alpha = np.array(pil_image)[..., 3].astype(np.bool)
            image_pixels = _pil_to_numpy(pil_image, True, convert='RGB')
            image = MaskedImage(image_pixels, mask=alpha, copy=False)
        else:
            # With no normalisation we just return the pixels
            image = Image(_pil_to_numpy(pil_image, False), copy=False)
    elif mode in ['L', 'I', 'RGB']:
        # Greyscale, Integer and RGB images
        image = Image(_pil_to_numpy(pil_image, normalize), copy=False)
    elif mode == '1':
        # Can't normalize a binary image
        image = BooleanImage(_pil_to_numpy(pil_image, False), copy=False)
    elif mode == 'P':
        # Convert pallete images to RGB
        image = Image(_pil_to_numpy(pil_image, normalize, convert='RGB'))
    elif mode == 'F':  # Floating point images
        # Don't normalize as we don't know the scale
        image = Image(_pil_to_numpy(pil_image, False), copy=False)
    else:
        raise ValueError('Unexpected mode for PIL: {}'.format(mode))
    return image
예제 #33
0
def test_diagonal_greyscale():
    image = Image.init_blank((100, 250), n_channels=1)
    assert image.diagonal() == (100 ** 2 + 250 ** 2) ** 0.5
예제 #34
0
def test_diagonal_kchannel_ndim():
    image = Image.init_blank((100, 250, 50), n_channels=5)
    assert image.diagonal() == (100 ** 2 + 250 ** 2 + 50 ** 2) ** 0.5
예제 #35
0
def test_image_from_vector():
    pixels = np.random.rand(2, 10, 20)
    pixels2 = np.random.rand(2, 10, 20)
    image = Image(pixels)
    image2 = image.from_vector(pixels2.ravel())
    assert(np.all(image2.pixels == pixels2))
예제 #36
0
def test_image_from_vector_no_copy():
    pixels = np.random.rand(2, 10, 20)
    pixels2 = np.random.rand(2, 10, 20)
    image = Image(pixels)
    image2 = image.from_vector(pixels2.ravel(), copy=False)
    assert(is_same_array(image2.pixels, pixels2))
예제 #37
0
def test_create_1d_error():
    with raises(ValueError):
        Image(np.ones(1))
예제 #38
0
def test_image_from_vector_inplace_no_copy():
    pixels = np.random.rand(2, 10, 20)
    pixels2 = np.random.rand(2, 10, 20)
    image = Image(pixels)
    image._from_vector_inplace(pixels2.ravel(), copy=False)
    assert is_same_array(image.pixels, pixels2)
예제 #39
0
def test_normalize_scale_all():
    pixels = np.arange(27, dtype=float).reshape([3, 3, 3])
    dummy_scale = lambda *a, **kwargs: np.array(2.0)
    image = Image(pixels, copy=False)
    new_image = normalize(image, scale_func=dummy_scale, mode="all")
    assert_allclose(new_image.pixels, (pixels - 13.0) / 2.0)
예제 #40
0
def test_normalize_unknown_mode_raises():
    image = Image.init_blank((2, 2))
    with raises(ValueError):
        normalize(image, mode="fake")
예제 #41
0
import numpy as np
from numpy.testing import assert_allclose
from pytest import raises

import menpo.io as mio
from menpo.image import Image
from menpo.io.output.pickle import pickle_paths_as_pure
from menpo.io.utils import _norm_path

builtins_str = "__builtin__" if sys.version_info[0] == 2 else "builtins"

test_lg = mio.import_landmark_file(mio.data_path_to("lenna.ljson"),
                                   group="LJSON")
nan_lg = test_lg.copy()
nan_lg.points[0, :] = np.nan
test_img = Image(np.random.random([100, 100]))
colour_test_img = Image(np.random.random([3, 100, 100]))
fake_path = "/tmp/test.fake"


@patch("menpo.io.output.base.landmark_types")
@patch("menpo.io.output.base.Path.exists")
@patch("menpo.io.output.base.Path.open")
def test_export_filepath_overwrite_exists(mock_open, exists, landmark_types):
    exists.return_value = True
    landmark_types.__contains__.return_value = True
    mio.export_landmark_file(test_lg, fake_path, overwrite=True)
    mock_open.assert_called_with("wb")
    landmark_types.__getitem__.assert_called_with(".fake")
    export_function = landmark_types.__getitem__.return_value
    assert export_function.call_count == 1
예제 #42
0
import os
from pathlib import PosixPath, WindowsPath, Path
from mock import patch, PropertyMock, MagicMock
from nose.tools import raises

import menpo.io as mio
from menpo.io.utils import _norm_path
from menpo.image import Image
from menpo.io.output.pickle import pickle_paths_as_pure

builtins_str = '__builtin__' if sys.version_info[0] == 2 else 'builtins'

test_lg = mio.import_landmark_file(mio.data_path_to('breakingbad.pts'))
nan_lg = test_lg.copy()
nan_lg.lms.points[0, :] = np.nan
test_img = Image(np.random.random([100, 100]))
fake_path = '/tmp/test.fake'


@patch('menpo.io.output.base.landmark_types')
@patch('menpo.io.output.base.Path.exists')
@patch('menpo.io.output.base.Path.open')
def test_export_filepath_overwrite_exists(mock_open, exists, landmark_types):
    exists.return_value = True
    mio.export_landmark_file(test_lg, fake_path, overwrite=True)
    mock_open.assert_called_with('wb')
    landmark_types.__getitem__.assert_called_with('.fake')
    export_function = landmark_types.__getitem__.return_value
    assert export_function.call_count == 1

예제 #43
0
def test_normalize_0_variance_raises():
    image = Image.init_blank((2, 2))
    dummy_scale = lambda *a, **kwargs: np.array(0.0)
    with raises(ValueError):
        normalize(image, scale_func=dummy_scale)
예제 #44
0
def test_mirror_image_axis_error():
    Image(np.array([[1., 2., 3., 4.], [5., 6., 7., 8.]])).mirror(axis=2)
예제 #45
0
파일: rasterize.py 프로젝트: eosulliv/menpo
def _rasterize_pillow(
    image,
    pclouds,
    render_lines=True,
    line_style="-",
    line_colour="b",
    line_width=1,
    render_markers=True,
    marker_style="o",
    marker_size=1,
    marker_face_colour="b",
    marker_edge_colour="b",
    marker_edge_width=1,
):
    from PIL import ImageDraw

    if image.n_channels not in {1, 3}:
        raise ValueError("The Pillow rasterizer only supports grayscale or "
                         "colour images")
    if any(x != "-" for x in line_style):
        raise ValueError("The Pillow rasterizer only supports the '-' "
                         "line style.")
    if any(x not in {"o", "s"} for x in marker_style):
        raise ValueError("The Pillow rasterizer only supports the 'o' and 's' "
                         "marker styles.")
    if any(x > 1 for x in marker_edge_width):
        raise ValueError("The Pillow rasterizer only supports "
                         "marker_edge_width of 1 or 0.")

    if image.n_channels == 1:
        # Make the image RGB
        image = image.extract_channels([0, 0, 0])

    pil_im = image.as_PILImage()
    draw = ImageDraw.Draw(pil_im)

    line_colour = [_parse_colour(x) for x in line_colour]
    marker_edge_colour = [_parse_colour(x) for x in marker_edge_colour]
    marker_face_colour = [_parse_colour(x) for x in marker_face_colour]

    for k in range(len(pclouds)):
        p = pclouds[k]
        if isinstance(p, TriMesh):
            pclouds[k] = p.as_pointgraph()

        points = p.points
        if (render_lines[k] and line_width[k] > 0 and hasattr(p, "edges")
                and p.edges.size > 0):
            edges = p.edges
            lines = zip(points[edges[:, 0], :], points[edges[:, 1], :])

            for l1, l2 in lines:
                draw.line(
                    [tuple(l1[::-1]), tuple(l2[::-1])],
                    fill=line_colour[k],
                    width=line_width[k],
                )

        if render_markers[k] and marker_size[k] > 0:
            draw_func = draw.ellipse if marker_style[
                k] == "o" else draw.rectangle
            outline = marker_edge_colour[k] if marker_edge_width[
                k] == 1 else None
            for p in points:
                y, x = p
                draw_func(
                    (
                        x - marker_size[k],
                        y - marker_size[k],
                        x + marker_size[k],
                        y + marker_size[k],
                    ),
                    fill=marker_face_colour[k],
                    outline=outline,
                )

    del draw

    pixels = np.asarray(pil_im)
    if image.n_channels == 3:
        return Image.init_from_channels_at_back(pixels)
    else:
        return Image(pixels)
예제 #46
0
def test_normalize_var_all():
    pixels = np.arange(27, dtype=float).reshape([3, 3, 3])
    image = Image(pixels, copy=False)
    new_image = normalize_var(image, mode="all")
    assert_allclose(np.var(new_image.pixels), 0.01648, atol=1e-3)
예제 #47
0
def test_image_from_vector_custom_channels():
    pixels = np.random.rand(2, 10, 20)
    pixels2 = np.random.rand(3, 10, 20)
    image = Image(pixels)
    image2 = image.from_vector(pixels2.ravel(), n_channels=3)
    assert(np.all(image2.pixels == pixels2))
예제 #48
0
def test_normalize_std_all():
    pixels = np.arange(27, dtype=float).reshape([3, 3, 3])
    image = Image(pixels, copy=False)
    new_image = normalize_std(image, mode="all")
    assert_allclose(np.std(new_image.pixels), 1.0)
예제 #49
0
def test_rescale_to_diagonal():
    image = Image.init_blank((8, 6), n_channels=2)
    assert image.diagonal() == 10
    rescaled = image.rescale_to_diagonal(5)
    assert rescaled.shape == (4, 3)
    assert rescaled.n_channels == 2
예제 #50
0
def test_normalize_no_scale_all():
    pixels = np.arange(27, dtype=float).reshape([3, 3, 3])
    image = Image(pixels, copy=False)
    new_image = normalize(image, scale_func=None, mode="all")
    assert_allclose(new_image.pixels, pixels - 13.0)
예제 #51
0
def test_diagonal_color():
    image = Image.init_blank((100, 250), n_channels=3)
    assert image.diagonal() == (100 ** 2 + 250 ** 2) ** 0.5
예제 #52
0
def test_image_extract_channels():
    image = Image(np.random.rand(3, 120, 120), copy=False)
    extracted = image.extract_channels(0)
    assert_equal(extracted.pixels, image.pixels[[0], ...])
예제 #53
0
def test_image_extract_channels_multiple_reversed():
    image = Image(np.random.rand(3, 120, 120), copy=False)
    extracted = image.extract_channels([2, 0])
    assert_equal(extracted.pixels[0], image.pixels[2])
    assert_equal(extracted.pixels[1], image.pixels[0])
예제 #54
0
 def _set_up(self):
     # work out feature length per patch
     patch_img = Image.blank(self.patch_shape, fill=0)
     self._feature_patch_length = self.regression_features(
         patch_img).n_parameters
예제 #55
0
def test_as_pil_image_3channels():
    im = Image.init_blank((120, 120), n_channels=3)
    new_im = im.as_PILImage()
    assert_allclose(np.asarray(new_im.getdata()).reshape(im.pixels.shape),
                    (im.pixels * 255).astype(np.uint8))
예제 #56
0
def test_no_op():
    image = Image([[1.0, 2.0], [2.0, 1.0]])
    new_image = no_op(image)
    assert_allclose(image.pixels, new_image.pixels)
    assert not is_same_array(image.pixels, new_image.pixels)
예제 #57
0
def test_as_pil_image_uint8():
    im = Image(np.ones((1, 120, 120), dtype=np.uint8), copy=False)
    new_im = im.as_PILImage()
    assert_allclose(np.asarray(new_im.getdata()).reshape(im.pixels.shape),
                    im.pixels)
예제 #58
0
def test_es_values():
    image = Image([[1.0, 2.0], [2.0, 1.0]])
    es_img = es(image)
    k = 1.0 / (2 * (2 ** 0.5))
    res = np.array([[[k, -k], [k, -k]], [[k, k], [-k, -k]]])
    assert_allclose(es_img.pixels, res)
예제 #59
0
def _rasterize_pillow(image,
                      pclouds,
                      render_lines=True,
                      line_style='-',
                      line_colour='b',
                      line_width=1,
                      render_markers=True,
                      marker_style='o',
                      marker_size=1,
                      marker_face_colour='b',
                      marker_edge_colour='b',
                      marker_edge_width=1):
    from PIL import ImageDraw

    if any(x != '-' for x in line_style):
        raise ValueError("The Pillow rasterizer only supports the '-' "
                         "line style.")
    if any(x not in {'o', 's'} for x in marker_style):
        raise ValueError("The Pillow rasterizer only supports the 'o' and 's' "
                         "marker styles.")
    if any(x > 1 for x in marker_edge_width):
        raise ValueError('The Pillow rasterizer only supports '
                         'marker_edge_width of 1 or 0.')

    pil_im = image.as_PILImage()
    draw = ImageDraw.Draw(pil_im)

    line_colour = [_parse_colour(x) for x in line_colour]
    marker_edge_colour = [_parse_colour(x) for x in marker_edge_colour]
    marker_face_colour = [_parse_colour(x) for x in marker_face_colour]

    for k in range(len(pclouds)):
        p = pclouds[k]
        if isinstance(p, TriMesh):
            pclouds[k] = p.as_pointgraph()

        points = p.points
        if (render_lines[k] and line_width[k] > 0 and hasattr(p, 'edges')
                and p.edges.size > 0):
            edges = p.edges
            lines = zip(points[edges[:, 0], :], points[edges[:, 1], :])

            for l1, l2 in lines:
                draw.line([tuple(l1[::-1]), tuple(l2[::-1])],
                          fill=line_colour[k],
                          width=line_width[k])

        if render_markers[k] and marker_size[k] > 0:
            draw_func = (draw.ellipse
                         if marker_style[k] == 'o' else draw.rectangle)
            outline = (marker_edge_colour[k]
                       if marker_edge_width[k] == 1 else None)
            for p in points:
                y, x = p
                draw_func((x - marker_size[k], y - marker_size[k],
                           x + marker_size[k], y + marker_size[k]),
                          fill=marker_face_colour[k],
                          outline=outline)

    del draw

    pixels = np.asarray(pil_im)
    if image.n_channels == 3:
        return Image.init_from_channels_at_back(pixels)
    else:
        return Image(pixels)
예제 #60
0
def test_sample_image():
    im = Image.init_blank((100, 100), fill=2)
    p = PointCloud(np.array([[0, 0], [1, 0]]))

    arr = im.sample(p)
    assert_allclose(arr, [[2., 2.]])