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
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))
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
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))
def _aux(im, pts_paths, pts_names, pts_formats, save_path, save_original, off1, off2, figure_size, overwrite, render_options, only_ln=False): if only_ln: # case of visualising only landmarks (black background) path_tmp = im.path im = Image.init_blank([im.shape[0], im.shape[1]], im.n_channels) im.path = path_tmp # attach landmarks for k, pts_path in enumerate(pts_paths): if os.path.isfile(pts_path + im.path.stem + pts_formats[k]): pts = mio.import_landmark_file(pts_path + im.path.stem + pts_formats[k]) im.landmarks[pts_names[k]] = pts # copy original if asked if save_original: im_orig = im.copy() # crop if pts_names[0] in im.landmarks.group_labels: centre = im.landmarks[pts_names[0]].lms.centre() min_indices = np.array([round(centre[0])-off1, round(centre[1])-off2]) max_indices = np.array([round(centre[0])+off1, round(centre[1])+off2]) # im.crop_inplace(min_indices, max_indices) im = im.crop(min_indices, max_indices, constrain_to_boundary=True) else: path_tmp = im.path im = Image.init_blank([off1*2 + 1, off2*2 + 1], im.n_channels) im.path = path_tmp # render rand = randint(1, 10000) fig = plt.figure(rand) if save_original: gs = gridspec.GridSpec(1, 2, width_ratios=[im_orig.height, im.height]) plt.subplot(gs[0]) renderer = _render(im_orig, pts_names, fig, render_options['colours'][0], render_options['sizes'][0], render_options['edgesizes'][0], figure_size) plt.subplot(gs[1]) renderer = _render(im, pts_names, fig, render_options['colours'][1], render_options['sizes'][1], render_options['edgesizes'][1], figure_size) else: renderer = _render(im, pts_names, fig, render_options['colours'][1], render_options['sizes'][1], render_options['edgesizes'][1], figure_size) renderer.save_figure(save_path + im.path.stem + '.png', format='png', pad_inches=0.0, overwrite=overwrite) plt.close(rand)
def test_copy_landmarks_and_path(): img = mio.import_builtin_asset.lenna_png() new_img = Image.init_blank(img.shape) copy_landmarks_and_path(img, new_img) assert new_img.path == img.path assert new_img.landmarks.keys() == img.landmarks.keys() assert new_img.landmarks is not img.landmarks
def test_constrain_landmarks_to_bounds(): im = Image.init_blank((10, 10)) im.landmarks['test'] = PointCloud.init_2d_grid((20, 20)) with warnings.catch_warnings(): warnings.simplefilter('ignore') im.constrain_landmarks_to_bounds() assert not im.has_landmarks_outside_bounds() assert_allclose(im.landmarks['test'].lms.bounds(), im.bounds())
def test_zoom_image(): im = Image.init_blank((100, 100), fill=0) # White square in the centre of size 10x10 im.pixels[0, 45:55, 45:55] = 1.0 # Zoom in 50% makes the white square 5 pixel bigger in theory (16x16) zim = im.zoom(1.5) assert np.count_nonzero(zim.pixels) == 256
def test_rescale_pixels(): img = Image.init_blank((10, 10), n_channels=1) img.pixels[:, 6:, 6:] = 2 img_rescaled = img.rescale_pixels(0, 255) assert np.min(img_rescaled.pixels) == 0 assert np.max(img_rescaled.pixels) == 255 assert np.all(img_rescaled.pixels[:, 6:, 6:] == 255)
def test_rescale_to_diagonal_return_transform(): img = Image.init_blank((100, 100), n_channels=1) img.landmarks['test'] = bounding_box([40, 40], [80, 80]) cropped_img, transform = img.rescale_to_diagonal(100, return_transform=True) img_back = cropped_img.warp_to_shape(img.shape, transform.pseudoinverse()) assert_allclose(img_back.shape, img.shape) assert_allclose(img_back.pixels, img.pixels) assert_allclose(img_back.landmarks['test'].points, img.landmarks['test'].points)
def test_as_greyscale_luminosity_dtype_uint8(): image = Image.init_blank((120, 120), n_channels=3, fill=255, dtype=np.uint8) image.pixels[0].fill(127) new_image = image.as_greyscale(mode='luminosity') assert (new_image.shape == image.shape) assert (new_image.n_channels == 1) assert (new_image.pixels.dtype == np.uint8) expected = np.empty_like(image.pixels[0]) expected.fill(216) assert_allclose(new_image.pixels[0], expected)
def test_rasterize_matplotlib_basic(): im = Image.init_blank([11, 11], fill=0, n_channels=1) im.landmarks['test'] = centre new_im = rasterize_landmarks_2d(im, group='test', render_lines=False, marker_style='.', marker_face_colour='r', marker_size=2, marker_edge_width=0, backend='matplotlib') assert new_im.n_channels == 3 assert new_im.shape == (11, 11) assert_allclose(new_im.pixels[:, 5, 5], [255, 0, 0])
def test_rasterize_pillow_basic(): im = Image.init_blank([11, 11], fill=0, n_channels=3) im.landmarks['test'] = centre new_im = rasterize_landmarks_2d(im, group='test', render_lines=False, marker_style='s', marker_face_colour='r', marker_size=1, marker_edge_width=0, backend='pillow') assert new_im.n_channels == 3 assert new_im.shape == (11, 11) assert_allclose(new_im.pixels[0, 3:6, 3:6], 255)
def test_rescale_pixels_per_channel(): img = Image.init_blank((10, 10), n_channels=2) img.pixels[0, 6:, 6:] = 2 img.pixels[1, 6:, 6:] = 4 img_rescaled = img.rescale_pixels(0, 100, per_channel=True) assert np.min(img_rescaled.pixels) == 0 assert np.max(img_rescaled.pixels) == 100 assert np.all(img_rescaled.pixels[0, 6:, 6:] == 100) assert np.all(img_rescaled.pixels[1, 6:, 6:] == 100)
def test_crop_to_landmarks_return_transform(): img = Image.init_blank((100, 100), n_channels=1) img.landmarks['test'] = bounding_box([40, 40], [80, 80]) cropped_img, transform = img.crop(np.array([20, 30]), np.array([90, 95]), return_transform=True) img_back = cropped_img.warp_to_shape(img.shape, transform.pseudoinverse()) assert_allclose(img_back.shape, img.shape) assert_allclose(img_back.pixels, img.pixels) assert_allclose(img_back.landmarks['test'].points, img.landmarks['test'].points)
def init_2d_grid(cls, shape, spacing=None, tcoords=None, texture=None): r""" Create a TexturedTriMesh that exists on a regular 2D grid. The first dimension is the number of rows in the grid and the second dimension of the shape is the number of columns. ``spacing`` optionally allows the definition of the distance between points (uniform over points). The spacing may be different for rows and columns. The triangulation will be right-handed and the diagonal will go from the top left to the bottom right of a square on the grid. If no texture is passed a blank (black) texture is attached with correct texture coordinates for texture mapping an image of the same size as ``shape``. Parameters ---------- shape : `tuple` of 2 `int` The size of the grid to create, this defines the number of points across each dimension in the grid. The first element is the number of rows and the second is the number of columns. spacing : `int` or `tuple` of 2 `int`, optional The spacing between points. If a single `int` is provided, this is applied uniformly across each dimension. If a `tuple` is provided, the spacing is applied non-uniformly as defined e.g. ``(2, 3)`` gives a spacing of 2 for the rows and 3 for the columns. tcoords : ``(N, 2)`` `ndarray`, optional The texture coordinates for the mesh. texture : :map:`Image`, optional The texture for the mesh. Returns ------- trimesh : :map:`TriMesh` A TriMesh arranged in a grid. """ pc = TriMesh.init_2d_grid(shape, spacing=spacing) points = pc.points trilist = pc.trilist # Ensure that the tcoords and texture are copied if tcoords is not None: tcoords = tcoords.copy() else: tcoords = grid_tcoords(shape) if texture is not None: texture = texture.copy() else: from menpo.image import Image # Default texture is all black texture = Image.init_blank(shape) return TexturedTriMesh(points, tcoords, texture, trilist=trilist, copy=False)
def test_rasterize_pillow_basic_line(): im = Image.init_blank([11, 11], fill=0, n_channels=3) im.landmarks['test'] = line new_im = rasterize_landmarks_2d(im, group='test', render_lines=True, line_width=1, line_colour='b', marker_style='s', marker_face_colour='r', marker_size=1, marker_edge_width=0, backend='pillow') assert new_im.n_channels == 3 assert_allclose(new_im.pixels[0, 1:4, 3:6], 255) assert_allclose(new_im.pixels[0, 7:-1, 3:6], 255) assert_allclose(new_im.pixels[2, 4:7, 4], 255)
def test_register_image_importer(is_file): from menpo.image import Image image = Image.init_blank((10, 10)) def foo_importer(filepath, **kwargs): return image is_file.return_value = True with patch.dict(mio.input.extensions.image_types, {}, clear=True): mio.register_image_importer('.foo', foo_importer) new_image = mio.import_image('fake.foo') assert image is new_image
def test_rasterize_matplotlib_basic_line(): import matplotlib matplotlib.use('agg') im = Image.init_blank([11, 11], fill=0, n_channels=1) im.landmarks['test'] = line new_im = rasterize_landmarks_2d(im, group='test', render_lines=True, marker_style='.', marker_face_colour='r', marker_size=2, marker_edge_width=0, backend='matplotlib') assert new_im.n_channels == 3 assert new_im.shape == (11, 11) assert_allclose(new_im.pixels[0, 3, 5], [255]) assert_allclose(new_im.pixels[0, 9, 5], [255]) assert_allclose(new_im.pixels[2, 5:8, 5], [255, 255, 255])
def test_warp_to_mask_masked_image(): mask = BooleanImage.init_blank((15, 15)) # make a truncated mask on the original image mask.pixels[0, -1, -1] = False img = MaskedImage.init_blank((15, 15), n_channels=2, mask=mask, fill=2.5) template_mask = BooleanImage.init_blank((10, 10), fill=False) template_mask.pixels[:, :5, :5] = True 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] = 2.5 result_mask = BooleanImage.init_blank((10, 10), fill=False).pixels result_mask[:, :5, :5] = True assert(warped_img.n_true_pixels() == 25) assert_allclose(result, warped_img.pixels) assert_allclose(result_mask, warped_img.mask.pixels)
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))
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 test_bounds_3d(): im = Image.init_blank((50, 30, 10)) assert_allclose(im.bounds(), ((0, 0, 0), (49, 29, 9)))
def test_rescale_to_diagonal(): img = Image.init_blank((100, 100), n_channels=1) img_rescaled = img.rescale_to_diagonal(200 * np.sqrt(2)) assert_allclose(img_rescaled.shape, (200, 200))
def test_as_rolled_channels_3channels(): im = Image.init_blank((120, 120), n_channels=3, fill=1) new_im = im.pixels_with_channels_at_back() assert new_im.dtype == np.float assert_allclose(np.ones([120, 120, 3]), new_im)
def test_crop_to_pointcloud_proportion(): img = Image.init_blank((100, 100), n_channels=1) pcloud = bounding_box([0, 0], [50, 50]) img_cropped = img.crop_to_pointcloud_proportion(pcloud, 0.1) assert_allclose(img_cropped.shape, (55, 55))
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)
def test_crop_to_pointcloud_proportion(): img = Image.init_blank((100, 100), n_channels=1) pcloud = bounding_box([0, 0], [50, 50]) img_cropped = img.crop_to_pointcloud_proportion(pcloud, 0.1) assert_allclose(img_cropped.shape, (55, 55))
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_diagonal_greyscale(): image = Image.init_blank((100, 250), n_channels=1) assert image.diagonal() == (100 ** 2 + 250 ** 2) ** 0.5
def test_diagonal_color(): image = Image.init_blank((100, 250), n_channels=3) assert image.diagonal() == (100 ** 2 + 250 ** 2) ** 0.5
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))
def test_as_rolled_channels_1channel_float32_out(): im = Image.init_blank((120, 120), n_channels=1, fill=1) new_im = im.pixels_with_channels_at_back(out_dtype=np.float32) assert new_im.dtype == np.float32 assert_allclose(np.ones([120, 120]), new_im)
def test_as_rolled_channels_1channel_uint16_out(): im = Image.init_blank((120, 120), n_channels=1, fill=1) new_im = im.pixels_with_channels_at_back(out_dtype=np.uint16) assert new_im.dtype == np.uint16 assert_allclose(np.ones([120, 120]) * 65535, new_im)
def test_crop_to_landmarks_proportion(): img = Image.init_blank((100, 100), n_channels=1) img.landmarks['test'] = bounding_box([0, 0], [10, 10]) img_cropped = img.crop_to_landmarks_proportion(0.1) assert_allclose(img_cropped.shape, (11, 11))
def test_as_greyscale_channels_no_index(): image = Image.init_blank((120, 120), n_channels=3) with raises(ValueError): image.as_greyscale(mode='channel')
def test_rescale_landmarks_to_diagonal_range(): img = Image.init_blank((100, 100), n_channels=1) img.landmarks['test'] = bounding_box([0, 0], [10, 10]) img_rescaled = img.rescale_landmarks_to_diagonal_range(20 * np.sqrt(2)) assert_allclose(img_rescaled.shape, (200, 200))
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.]])
def test_normalize_unknown_mode_raises(): image = Image.init_blank((2, 2)) with raises(ValueError): normalize(image, mode='fake')
def test_copy_landmarks_and_path_returns_target(): img = mio.import_builtin_asset.lenna_png() new_img = Image.init_blank(img.shape) new_img_ret = copy_landmarks_and_path(img, new_img) assert new_img_ret is new_img
def test_rolled_channels(): image = Image.init_blank((120, 120), n_channels=3) rolled_channels = image.pixels_with_channels_at_back() assert rolled_channels.shape == (120, 120, 3)
def _set_up(self): # work out feature length per patch patch_img = Image.init_blank(self.patch_shape, fill=0) self._feature_patch_length = self.regression_features(patch_img).n_parameters
def test_as_imageio_1channel_float32_out(): im = Image.init_blank((120, 120), n_channels=1, fill=1) new_im = im.as_imageio(out_dtype=np.float32) assert new_im.dtype == np.float32 assert_allclose(np.ones([120, 120]), new_im)
def test_as_rolled_channels_float_out_range(): im = Image.init_blank((120, 120), n_channels=1, fill=2.0) with raises(ValueError): im.pixels_with_channels_at_back(out_dtype=np.uint8)
def test_as_greyscale_channels_no_index(): image = Image.init_blank((120, 120), n_channels=3) new_image = image.as_greyscale(mode='channel') assert (new_image.shape == image.shape) assert (new_image.n_channels == 1)
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)
def test_normalize_unknown_mode_raises(): image = Image.init_blank((2, 2)) normalize(image, mode='fake')
from collections import OrderedDict from mock import patch, MagicMock import numpy as np from nose.tools import raises from menpo.image import Image from menpo.landmark import LandmarkGroup from menpo.shape import TriMesh, TexturedTriMesh, ColouredTriMesh, PointCloud 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(): TexturedTriMesh(fake_triangle, fake_tcoords,
def test_image_view_widget(): with raises(MenpowidgetsMissingError): Image.init_blank((5, 5)).view_widget()
def image_view_widget_test(): Image.init_blank((5, 5)).view_widget()
def test_rescale_to_diagonal(): img = Image.init_blank((100, 100), n_channels=1) img_rescaled = img.rescale_to_diagonal(200 * np.sqrt(2)) assert_allclose(img_rescaled.shape, (200, 200))
def foo_importer(filepath, **kwargs): return LazyList([lambda: Image.init_blank((10, 10))])
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
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_rescale_landmarks_to_diagonal_range(): img = Image.init_blank((100, 100), n_channels=1) img.landmarks['test'] = bounding_box([0, 0], [10, 10]) img_rescaled = img.rescale_landmarks_to_diagonal_range(20 * np.sqrt(2)) assert_allclose(img_rescaled.shape, (200, 200))
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
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.]])
def test_normalize_unknown_mode_raises(): image = Image.init_blank((2, 2)) with raises(ValueError): normalize(image, mode="fake")
def foo_importer(filepath, **kwargs): return LazyList([lambda: Image.init_blank((10, 10))])
def test_as_imageio_1channel_uint16_out(): im = Image.init_blank((120, 120), n_channels=1, fill=1) new_im = im.as_imageio(out_dtype=np.uint16) assert new_im.dtype == np.uint16 assert_allclose(np.ones([120, 120]) * 65535, new_im)