Exemplo n.º 1
0
def test_image_has_nan_values():
    img = Image(np.random.rand(1, 3, 3), copy=False)
    img.pixels[0, 0, 0] = np.nan
    assert img.has_nan_values()
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)
def test_image_as_vector_keep_channels():
    pixels = np.random.rand(2, 10, 20)
    image = Image(pixels)
    assert (np.all(
        image.as_vector(keep_channels=True) == pixels.reshape([2, -1])))
def test_image_str_shape_2d():
    pixels = np.ones((1, 10, 20))
    image = Image(pixels)
    assert (image._str_shape() == '20W x 10H')
def test_image_as_vector():
    pixels = np.random.rand(1, 10, 20)
    image = Image(pixels)
    assert (np.all(image.as_vector() == pixels.ravel()))
def test_image_blank_fill():
    image = Image(np.ones((1, 6, 4)) * 7)
    image_blank = Image.init_blank((6, 4), fill=7)
    assert (np.all(image_blank.pixels == image.pixels))
def test_image_centre():
    pixels = np.ones((1, 10, 20))
    image = Image(pixels)
    assert (np.all(image.centre() == np.array([5, 10])))
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))
def test_image_from_vector_inplace_copy_explicit():
    pixels = np.random.rand(2, 10, 20)
    pixels2 = np.random.rand(2, 10, 20)
    image = Image(pixels)
    image._from_vector_inplace(pixels2.ravel(), copy=True)
    assert (not is_same_array(image.pixels, pixels2))
Exemplo n.º 10
0
 def __str__(self):
     out = "Supervised Descent Method\n" \
           " - Non-Parametric '{}' Regressor\n" \
           " - {} training images.\n".format(
         name_of_callable(self._fitters[0].regressor),
         self._n_training_images)
     # small strings about number of channels, channels string and downscale
     down_str = []
     for j in range(self.n_levels):
         if j == self.n_levels - 1:
             down_str.append('(no downscale)')
         else:
             down_str.append('(downscale by {})'.format(
                 self.downscale**(self.n_levels - j - 1)))
     temp_img = Image(image_data=np.random.rand(40, 40))
     if self.pyramid_on_features:
         temp = self.features(temp_img)
         n_channels = [temp.n_channels] * self.n_levels
     else:
         n_channels = []
         for j in range(self.n_levels):
             temp = self.features[j](temp_img)
             n_channels.append(temp.n_channels)
     # string about features and channels
     if self.pyramid_on_features:
         feat_str = "- Feature is {} with ".format(
             name_of_callable(self.features))
         if n_channels[0] == 1:
             ch_str = ["channel"]
         else:
             ch_str = ["channels"]
     else:
         feat_str = []
         ch_str = []
         for j in range(self.n_levels):
             if isinstance(self.features[j], str):
                 feat_str.append("- Feature is {} with ".format(
                     self.features[j]))
             elif self.features[j] is None:
                 feat_str.append("- No features extracted. ")
             else:
                 feat_str.append("- Feature is {} with ".format(
                     self.features[j].__name__))
             if n_channels[j] == 1:
                 ch_str.append("channel")
             else:
                 ch_str.append("channels")
     if self.n_levels > 1:
         out = "{} - Gaussian pyramid with {} levels and downscale " \
               "factor of {}.\n".format(out, self.n_levels,
                                        self.downscale)
         if self.pyramid_on_features:
             out = "{}   - Pyramid was applied on feature space.\n   " \
                   "{}{} {} per image.\n".format(out, feat_str,
                                                 n_channels[0], ch_str[0])
         else:
             out = "{}   - Features were extracted at each pyramid " \
                   "level.\n".format(out)
             for i in range(self.n_levels - 1, -1, -1):
                 out = "{}   - Level {} {}: \n     {}{} {} per " \
                       "image.\n".format(
                     out, self.n_levels - i, down_str[i], feat_str[i],
                     n_channels[i], ch_str[i])
     else:
         if self.pyramid_on_features:
             feat_str = [feat_str]
         out = "{0} - No pyramid used:\n   {1}{2} {3} per image.\n".format(
             out, feat_str[0], n_channels[0], ch_str[0])
     return out
Exemplo n.º 11
0
import numpy as np
from mock import patch, PropertyMock
from nose.tools import raises

import menpo.io as mio
from menpo.image import Image

test_lg = mio.import_landmark_file(mio.data_path_to('breakingbad.pts'))
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(fake_path, test_lg, overwrite=True)
    mock_open.assert_called_once_with('wb')
    landmark_types.__getitem__.assert_called_once_with('.fake')
    export_function = landmark_types.__getitem__.return_value
    export_function.assert_called_once()


@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_no_overwrite(mock_open, exists, landmark_types):
    exists.return_value = False
    mio.export_landmark_file(fake_path, test_lg)
    mock_open.assert_called_once_with('wb')
Exemplo n.º 12
0
    def __str__(self):
        out = "{}\n - {} training images.\n".format(self._str_title,
                                                    self.n_training_images)
        # small strings about number of channels, channels string and downscale
        down_str = []
        for j in range(self.n_levels):
            if j == self.n_levels - 1:
                down_str.append('(no downscale)')
            else:
                down_str.append('(downscale by {})'.format(
                    self.downscale**(self.n_levels - j - 1)))
        temp_img = Image(image_data=np.random.rand(50, 50))
        if self.pyramid_on_features:
            temp = compute_features(temp_img, self.feature_type[0])
            n_channels = [temp.n_channels] * self.n_levels
        else:
            n_channels = []
            for j in range(self.n_levels):
                temp = compute_features(temp_img, self.feature_type[j])
                n_channels.append(temp.n_channels)
        # string about features and channels
        if self.pyramid_on_features:
            if isinstance(self.feature_type[0], str):
                feat_str = "- Feature is {} with ".format(self.feature_type[0])
            elif self.feature_type[0] is None:
                feat_str = "- No features extracted. "
            else:
                feat_str = "- Feature is {} with ".format(
                    self.feature_type[0].__name__)
            if n_channels[0] == 1:
                ch_str = ["channel"]
            else:
                ch_str = ["channels"]
        else:
            feat_str = []
            ch_str = []
            for j in range(self.n_levels):
                if isinstance(self.feature_type[j], str):
                    feat_str.append("- Feature is {} with ".format(
                        self.feature_type[j]))
                elif self.feature_type[j] is None:
                    feat_str.append("- No features extracted. ")
                else:
                    feat_str.append("- Feature is {} with ".format(
                        self.feature_type[j].__name__))
                if n_channels[j] == 1:
                    ch_str.append("channel")
                else:
                    ch_str.append("channels")
        if self.n_levels > 1:
            if self.scaled_shape_models:
                out = "{} - Gaussian pyramid with {} levels and downscale " \
                      "factor of {}.\n   - Each level has a scaled shape " \
                      "model (reference frame).\n   - Patch size is {}W x " \
                      "{}H.\n".format(out, self.n_levels, self.downscale,
                                      self.patch_shape[1], self.patch_shape[0])

            else:
                out = "{} - Gaussian pyramid with {} levels and downscale " \
                      "factor of {}:\n   - Shape models (reference frames) " \
                      "are not scaled.\n   - Patch size is {}W x " \
                      "{}H.\n".format(out, self.n_levels, self.downscale,
                                      self.patch_shape[1], self.patch_shape[0])
            if self.pyramid_on_features:
                out = "{}   - Pyramid was applied on feature space.\n   " \
                      "{}{} {} per image.\n".format(out, feat_str,
                                                    n_channels[0], ch_str[0])
            else:
                out = "{}   - Features were extracted at each pyramid " \
                      "level.\n".format(out)
            for i in range(self.n_levels - 1, -1, -1):
                out = "{}   - Level {} {}: \n".format(out, self.n_levels - i,
                                                      down_str[i])
                if not self.pyramid_on_features:
                    out = "{}     {}{} {} per image.\n".format(
                        out, feat_str[i], n_channels[i], ch_str[i])
                out = "{0}     - {1} shape components ({2:.2f}% of " \
                      "variance)\n     - {3} {4} classifiers.\n".format(
                      out, self.shape_models[i].n_components,
                      self.shape_models[i].variance_ratio * 100,
                      self.n_classifiers_per_level[i],
                      self.classifiers[i][0].__name__)
        else:
            if self.pyramid_on_features:
                feat_str = [feat_str]
            out = "{0} - No pyramid used:\n   {1}{2} {3} per image.\n" \
                  "   - {4} shape components ({5:.2f}% of " \
                  "variance)\n   - {6} {7} classifiers.".format(
                  out, feat_str[0], n_channels[0], ch_str[0],
                  self.shape_models[0].n_components,
                  self.shape_models[0].variance_ratio * 100,
                  self.n_classifiers_per_level[0],
                  self.classifiers[0][0].__name__)
        return out
Exemplo n.º 13
0
    def response_image(self, image, group=None, label=None, level=-1):
        r"""
        Generates a response image result of applying the classifiers of a
        particular pyramidal level of the CLM to an image.

        Parameters
        -----------
        image: :map:`Image`
            The image.
        group : `string`, optional
            The key of the landmark set that should be used. If ``None``,
            and if there is only one set of landmarks, this set will be used.
        label : `string`, optional
            The label of of the landmark manager that you wish to use. If no
            label is passed, the convex hull of all landmarks is used.
        level: `int`, optional
            The pyramidal level to be used.

        Returns
        -------
        image : :map:`Image`
            The response image.
        """
        # rescale image
        image = image.rescale_to_reference_shape(self.reference_shape,
                                                 group=group,
                                                 label=label)

        # apply pyramid
        if self.n_levels > 1:
            if self.pyramid_on_features:
                # compute features at highest level
                feature_image = compute_features(image, self.feature_type[0])

                # apply pyramid on feature image
                pyramid = feature_image.gaussian_pyramid(
                    n_levels=self.n_levels, downscale=self.downscale)

                # get rescaled feature images
                images = list(pyramid)
            else:
                # create pyramid on intensities image
                pyramid = image.gaussian_pyramid(n_levels=self.n_levels,
                                                 downscale=self.downscale)

                # compute features at each level
                images = [
                    compute_features(i,
                                     self.feature_type[self.n_levels - j - 1])
                    for j, i in enumerate(pyramid)
                ]
            images.reverse()
        else:
            images = [compute_features(image, self.feature_type[0])]

        # initialize responses
        image = images[level]
        image_pixels = np.reshape(image.pixels, (-1, image.n_channels))
        response_data = np.zeros((image.shape[0], image.shape[1],
                                  self.n_classifiers_per_level[level]))
        # Compute responses
        for j, clf in enumerate(self.classifiers[level]):
            response_data[:, :, j] = np.reshape(clf(image_pixels), image.shape)
        return Image(image_data=response_data)
Exemplo n.º 14
0
def test_image_no_nan_values():
    img = Image(np.random.rand(1, 3, 3), copy=False)
    assert not img.has_nan_values()
def test_image_height():
    image = Image(np.ones((3, 6, 4)))
    assert (image.height == 6)
def test_create_1d_error():
    Image(np.ones(1))
def test_image_blank():
    image = Image(np.zeros((1, 6, 4)))
    image_blank = Image.init_blank((6, 4))
    assert (np.all(image_blank.pixels == image.pixels))
def test_image_from_vector_custom_channels_no_copy():
    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, copy=False)
    assert (is_same_array(image2.pixels, pixels2))
def test_image_blank_n_channels():
    image = Image(np.zeros((7, 6, 4)))
    image_blank = Image.init_blank((6, 4), n_channels=7)
    assert (np.all(image_blank.pixels == image.pixels))
def test_image_n_elements():
    image = Image(np.ones((3, 10, 10)))
    assert (image.n_elements == 3 * 10 * 10)
def test_image_str_shape_4d():
    pixels = np.ones((1, 10, 20, 11, 12))
    image = Image(pixels)
    assert (image._str_shape() == '10 x 20 x 11 x 12')
def test_image_width():
    image = Image(np.ones((3, 6, 4)))
    assert (image.width == 4)
def test_as_greyscale_channels():
    image = Image(np.random.randn(3, 120, 120), copy=False)
    new_image = image.as_greyscale(mode='channel', channel=0)
    assert (new_image.shape == image.shape)
    assert (new_image.n_channels == 1)
    assert_allclose(new_image.pixels[0], image.pixels[0])
def test_create_image_copy_false():
    pixels = np.ones((1, 100, 100))
    image = Image(pixels, copy=False)
    assert (is_same_array(image.pixels, pixels))
def test_as_pil_image_float32_uint16_out():
    im = Image(np.ones((1, 120, 120), dtype=np.float32), copy=False)
    new_im = im.as_PILImage(out_dtype=np.uint16)
    assert_allclose(
        np.asarray(new_im.getdata()).reshape(im.pixels.shape),
        (im.pixels * 65535).astype(np.uint16))
def test_create_image_copy_true():
    pixels = np.ones((1, 100, 100))
    image = Image(pixels)
    assert (not is_same_array(image.pixels, pixels))
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], ...])
def test_create_image_copy_false_not_c_contiguous():
    pixels = np.ones((1, 100, 100), order='F')
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        Image(pixels, copy=False)
        assert (len(w) == 1)
def test_image_extract_channels_multiple():
    image = Image(np.random.rand(3, 120, 120), copy=False)
    extracted = image.extract_channels([0, 2])
    assert_equal(extracted.pixels[0], image.pixels[0])
    assert_equal(extracted.pixels[1], image.pixels[2])
Exemplo n.º 30
0
def test_image_as_masked():
    img = Image(np.random.rand(3, 3, 1), copy=False)
    m_img = img.as_masked()
    assert (type(m_img) == MaskedImage)
    assert_allclose(m_img.pixels, img.pixels)