<s> from __future__ import division <EOL> from warnings import warn <EOL> from collections import Iterable <EOL> import numpy as np <EOL> import PIL . Image as PILImage <EOL> from menpo . compatibility import basestring <EOL> from menpo . base import Vectorizable , MenpoDeprecationWarning <EOL> from menpo . shape import PointCloud , bounding_box <EOL> from menpo . landmark import Landmarkable <EOL> from menpo . transform import ( Translation , NonUniformScale , <EOL> AlignmentUniformScale , Affine , scale_about_centre , <EOL> rotate_ccw_about_centre , Rotation ) <EOL> from menpo . visualize . base import ImageViewer , LandmarkableViewable , Viewable <EOL> from . interpolation import scipy_interpolation , cython_interpolation <EOL> from . patches import extract_patches , set_patches <EOL> _greyscale_luminosity_coef = None <EOL> class ImageBoundaryError ( ValueError ) : <EOL> r"""<STR_LIT>""" <EOL> def __init__ ( self , requested_min , requested_max , snapped_min , <EOL> snapped_max ) : <EOL> super ( ImageBoundaryError , self ) . __init__ ( ) <EOL> self . requested_min = requested_min <EOL> self . requested_max = requested_max <EOL> self . snapped_min = snapped_min <EOL> self . snapped_max = snapped_max <EOL> def indices_for_image_of_shape ( shape ) : <EOL> r"""<STR_LIT>""" <EOL> return np . indices ( shape ) . reshape ( [ len ( shape ) , - <NUM_LIT:1> ] ) . T <EOL> def normalise_pixels_range ( pixels , error_on_unknown_type = True ) : <EOL> r"""<STR_LIT>""" <EOL> dtype = pixels . dtype <EOL> if dtype == np . uint8 : <EOL> max_range = <NUM_LIT> <EOL> elif dtype == np . uint16 : <EOL> max_range = <NUM_LIT> <EOL> else : <EOL> if error_on_unknown_type : <EOL> raise ValueError ( '<STR_LIT>' <EOL> '<STR_LIT>' . format ( dtype ) ) <EOL> else : <EOL> return pixels <EOL> return pixels * ( <NUM_LIT:1.0> / max_range ) <EOL> def denormalise_pixels_range ( pixels , out_dtype ) : <EOL> """<STR_LIT>""" <EOL> in_dtype = pixels . dtype <EOL> if in_dtype == out_dtype : <EOL> return pixels <EOL> if np . issubclass_ ( in_dtype . type , np . floating ) or in_dtype == np . float : <EOL> if np . issubclass_ ( out_dtype , np . floating ) or out_dtype == np . float : <EOL> return pixels . astype ( out_dtype ) <EOL> else : <EOL> p_min = pixels . min ( ) <EOL> p_max = pixels . max ( ) <EOL> if p_min < <NUM_LIT:0.0> or p_max > <NUM_LIT:1.0> : <EOL> raise ValueError ( '<STR_LIT>' <EOL> '<STR_LIT>' . format ( p_min , <EOL> p_max ) ) <EOL> elif in_dtype != np . bool : <EOL> raise ValueError ( '<STR_LIT>' <EOL> '<STR_LIT>' . format ( in_dtype ) ) <EOL> if out_dtype == np . uint8 : <EOL> max_range = <NUM_LIT> <EOL> elif out_dtype == np . uint16 : <EOL> max_range = <NUM_LIT> <EOL> else : <EOL> raise ValueError ( '<STR_LIT>' <EOL> '<STR_LIT>' . format ( out_dtype ) ) <EOL> return ( pixels * max_range ) . astype ( out_dtype ) <EOL> def channels_to_back ( pixels ) : <EOL> r"""<STR_LIT>""" <EOL> return np . require ( np . rollaxis ( pixels , <NUM_LIT:0> , pixels . ndim ) , dtype = pixels . dtype , <EOL> requirements = [ '<STR_LIT:C>' ] ) <EOL> def channels_to_front ( pixels ) : <EOL> r"""<STR_LIT>""" <EOL> if not isinstance ( pixels , np . ndarray ) : <EOL> pixels = np . array ( pixels ) <EOL> if pixels . ndim == <NUM_LIT:3> : <EOL> pixels = np . require ( np . rollaxis ( pixels , - <NUM_LIT:1> ) , dtype = pixels . dtype , <EOL> requirements = [ '<STR_LIT:C>' ] ) <EOL> return pixels <EOL> class Image ( Vectorizable , Landmarkable , Viewable , LandmarkableViewable ) : <EOL> r"""<STR_LIT>""" <EOL> def __init__ ( self , image_data , copy = True ) : <EOL> super ( Image , self ) . __init__ ( ) <EOL> if not copy : <EOL> if not image_data . flags . c_contiguous : <EOL> image_data = np . array ( image_data , copy = True , order = '<STR_LIT:C>' ) <EOL> warn ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> else : <EOL> image_data = np . array ( image_data , copy = True , order = '<STR_LIT:C>' ) <EOL> if image_data . ndim == <NUM_LIT:2> : <EOL> image_data = image_data . reshape ( ( <NUM_LIT:1> , ) + image_data . shape ) <EOL> if image_data . ndim < <NUM_LIT:2> : <EOL> raise ValueError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" . format ( image_data . ndim ) ) <EOL> self . pixels = image_data <EOL> @ classmethod <EOL> def init_blank ( cls , shape , n_channels = <NUM_LIT:1> , fill = <NUM_LIT:0> , dtype = np . float ) : <EOL> r"""<STR_LIT>""" <EOL> shape = tuple ( np . ceil ( shape ) . astype ( np . int ) ) <EOL> if fill == <NUM_LIT:0> : <EOL> pixels = np . zeros ( ( n_channels , ) + shape , dtype = dtype ) <EOL> else : <EOL> pixels = np . ones ( ( n_channels , ) + shape , dtype = dtype ) * fill <EOL> return cls ( pixels , copy = False ) <EOL> @ classmethod <EOL> def init_from_rolled_channels ( cls , pixels ) : <EOL> r"""<STR_LIT>""" <EOL> return cls ( np . rollaxis ( pixels , - <NUM_LIT:1> ) ) <EOL> def as_masked ( self , mask = None , copy = True ) : <EOL> r"""<STR_LIT>""" <EOL> from menpo . image import MaskedImage <EOL> img = MaskedImage ( self . pixels , mask = mask , copy = copy ) <EOL> img . landmarks = self . landmarks <EOL> if hasattr ( self , '<STR_LIT:path>' ) : <EOL> img . path = self . path <EOL> return img <EOL> @ property <EOL> def n_dims ( self ) : <EOL> r"""<STR_LIT>""" <EOL> return len ( self . shape ) <EOL> @ property <EOL> def n_pixels ( self ) : <EOL> r"""<STR_LIT>""" <EOL> return self . pixels [ <NUM_LIT:0> , ... ] . size <EOL> @ property <EOL> def n_elements ( self ) : <EOL> r"""<STR_LIT>""" <EOL> return self . pixels . size <EOL> @ property <EOL> def n_channels ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . pixels . shape [ <NUM_LIT:0> ] <EOL> @ property <EOL> def width ( self ) : <EOL> r"""<STR_LIT>""" <EOL> return self . pixels . shape [ - <NUM_LIT:1> ] <EOL> @ property <EOL> def height ( self ) : <EOL> r"""<STR_LIT>""" <EOL> return self . pixels . shape [ - <NUM_LIT:2> ] <EOL> @ property <EOL> def shape ( self ) : <EOL> r"""<STR_LIT>""" <EOL> return self . pixels . shape [ <NUM_LIT:1> : ] <EOL> def diagonal ( self ) : <EOL> r"""<STR_LIT>""" <EOL> return np . sqrt ( np . sum ( np . array ( self . shape ) ** <NUM_LIT:2> ) ) <EOL> def centre ( self ) : <EOL> r"""<STR_LIT>""" <EOL> return np . array ( self . shape , dtype = np . double ) / <NUM_LIT:2> <EOL> def _str_shape ( self ) : <EOL> if self . n_dims > <NUM_LIT:2> : <EOL> return '<STR_LIT>' . join ( str ( dim ) for dim in self . shape ) <EOL> elif self . n_dims == <NUM_LIT:2> : <EOL> return '<STR_LIT>' . format ( self . width , self . height ) <EOL> def indices ( self ) : <EOL> r"""<STR_LIT>""" <EOL> return indices_for_image_of_shape ( self . shape ) <EOL> def _as_vector ( self , keep_channels = False ) : <EOL> r"""<STR_LIT>""" <EOL> if keep_channels : <EOL> return self . pixels . reshape ( [ self . n_channels , - <NUM_LIT:1> ] ) <EOL> else : <EOL> return self . pixels . ravel ( ) <EOL> def from_vector ( self , vector , n_channels = None , copy = True ) : <EOL> r"""<STR_LIT>""" <EOL> n_channels = self . n_channels if n_channels is None else n_channels <EOL> image_data = vector . reshape ( ( n_channels , ) + self . shape ) <EOL> new_image = Image ( image_data , copy = copy ) <EOL> new_image . landmarks = self . landmarks <EOL> return new_image <EOL> def _from_vector_inplace ( self , vector , copy = True ) : <EOL> r"""<STR_LIT>""" <EOL> image_data = vector . reshape ( self . pixels . shape ) <EOL> if not copy : <EOL> if not image_data . flags . c_contiguous : <EOL> warn ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> image_data = np . array ( image_data , copy = True , order = '<STR_LIT:C>' , <EOL> dtype = image_data . dtype ) <EOL> else : <EOL> image_data = np . array ( image_data , copy = True , order = '<STR_LIT:C>' , <EOL> dtype = image_data . dtype ) <EOL> self . pixels = image_data <EOL> def extract_channels ( self , channels ) : <EOL> r"""<STR_LIT>""" <EOL> copy = self . copy ( ) <EOL> if not isinstance ( channels , list ) : <EOL> channels = [ channels ] <EOL> copy . pixels = self . pixels [ channels ] <EOL> return copy <EOL> def as_histogram ( self , keep_channels = True , bins = '<STR_LIT>' ) : <EOL> r"""<STR_LIT>""" <EOL> if isinstance ( bins , basestring ) : <EOL> if bins == '<STR_LIT>' : <EOL> bins = <NUM_LIT:0> <EOL> else : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> elif isinstance ( bins , int ) and bins < <NUM_LIT:1> : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> vec = self . as_vector ( keep_channels = keep_channels ) <EOL> if len ( vec . shape ) == <NUM_LIT:1> or vec . shape [ <NUM_LIT:0> ] == <NUM_LIT:1> : <EOL> if bins == <NUM_LIT:0> : <EOL> bins = np . unique ( vec ) <EOL> hist , bin_edges = np . histogram ( vec , bins = bins ) <EOL> else : <EOL> hist = [ ] <EOL> bin_edges = [ ] <EOL> num_bins = bins <EOL> for ch in range ( vec . shape [ <NUM_LIT:0> ] ) : <EOL> if bins == <NUM_LIT:0> : <EOL> num_bins = np . unique ( vec [ ch , : ] ) <EOL> h_tmp , c_tmp = np . histogram ( vec [ ch , : ] , bins = num_bins ) <EOL> hist . append ( h_tmp ) <EOL> bin_edges . append ( c_tmp ) <EOL> return hist , bin_edges <EOL> def _view_2d ( self , figure_id = None , new_figure = False , channels = None , <EOL> interpolation = '<STR_LIT>' , cmap_name = None , alpha = <NUM_LIT:1.> , <EOL> render_axes = False , axes_font_name = '<STR_LIT>' , <EOL> axes_font_size = <NUM_LIT:10> , axes_font_style = '<STR_LIT>' , <EOL> axes_font_weight = '<STR_LIT>' , axes_x_limits = None , <EOL> axes_y_limits = None , axes_x_ticks = None , axes_y_ticks = None , <EOL> figure_size = ( <NUM_LIT:10> , <NUM_LIT:8> ) ) : <EOL> r"""<STR_LIT>""" <EOL> return ImageViewer ( figure_id , new_figure , self . n_dims , <EOL> self . pixels , channels = channels ) . render ( <EOL> interpolation = interpolation , cmap_name = cmap_name , alpha = alpha , <EOL> render_axes = render_axes , axes_font_name = axes_font_name , <EOL> axes_font_size = axes_font_size , axes_font_style = axes_font_style , <EOL> axes_font_weight = axes_font_weight , axes_x_limits = axes_x_limits , <EOL> axes_y_limits = axes_y_limits , axes_x_ticks = axes_x_ticks , <EOL> axes_y_ticks = axes_y_ticks , figure_size = figure_size ) <EOL> def view_widget ( self , browser_style = '<STR_LIT>' , figure_size = ( <NUM_LIT:10> , <NUM_LIT:8> ) , <EOL> style = '<STR_LIT>' ) : <EOL> r"""<STR_LIT>""" <EOL> try : <EOL> from menpowidgets import visualize_images <EOL> visualize_images ( self , figure_size = figure_size , style = style , <EOL> browser_style = browser_style ) <EOL> except ImportError : <EOL> from menpo . visualize . base import MenpowidgetsMissingError <EOL> raise MenpowidgetsMissingError ( ) <EOL> def _view_landmarks_2d ( self , channels = None , group = None , <EOL> with_labels = None , without_labels = None , <EOL> figure_id = None , new_figure = False , <EOL> interpolation = '<STR_LIT>' , cmap_name = None , alpha = <NUM_LIT:1.> , <EOL> render_lines = True , line_colour = None , line_style = '<STR_LIT:->' , <EOL> line_width = <NUM_LIT:1> , render_markers = True , marker_style = '<STR_LIT:o>' , <EOL> marker_size = <NUM_LIT:5> , marker_face_colour = None , <EOL> marker_edge_colour = None , marker_edge_width = <NUM_LIT:1.> , <EOL> render_numbering = False , <EOL> numbers_horizontal_align = '<STR_LIT>' , <EOL> numbers_vertical_align = '<STR_LIT>' , <EOL> numbers_font_name = '<STR_LIT>' , numbers_font_size = <NUM_LIT:10> , <EOL> numbers_font_style = '<STR_LIT>' , <EOL> numbers_font_weight = '<STR_LIT>' , <EOL> numbers_font_colour = '<STR_LIT:k>' , render_legend = False , <EOL> legend_title = '<STR_LIT>' , legend_font_name = '<STR_LIT>' , <EOL> legend_font_style = '<STR_LIT>' , legend_font_size = <NUM_LIT:10> , <EOL> legend_font_weight = '<STR_LIT>' , <EOL> legend_marker_scale = None , <EOL> legend_location = <NUM_LIT:2> , legend_bbox_to_anchor = ( <NUM_LIT> , <NUM_LIT:1.> ) , <EOL> legend_border_axes_pad = None , legend_n_columns = <NUM_LIT:1> , <EOL> legend_horizontal_spacing = None , <EOL> legend_vertical_spacing = None , legend_border = True , <EOL> legend_border_padding = None , legend_shadow = False , <EOL> legend_rounded_corners = False , render_axes = False , <EOL> axes_font_name = '<STR_LIT>' , axes_font_size = <NUM_LIT:10> , <EOL> axes_font_style = '<STR_LIT>' , axes_font_weight = '<STR_LIT>' , <EOL> axes_x_limits = None , axes_y_limits = None , <EOL> axes_x_ticks = None , axes_y_ticks = None , <EOL> figure_size = ( <NUM_LIT:10> , <NUM_LIT:8> ) ) : <EOL> """<STR_LIT>""" <EOL> from menpo . visualize import view_image_landmarks <EOL> return view_image_landmarks ( <EOL> self , channels , False , group , with_labels , without_labels , <EOL> figure_id , new_figure , interpolation , cmap_name , alpha , <EOL> render_lines , line_colour , line_style , line_width , <EOL> render_markers , marker_style , marker_size , marker_face_colour , <EOL> marker_edge_colour , marker_edge_width , render_numbering , <EOL> numbers_horizontal_align , numbers_vertical_align , <EOL> numbers_font_name , numbers_font_size , numbers_font_style , <EOL> numbers_font_weight , numbers_font_colour , render_legend , <EOL> legend_title , legend_font_name , legend_font_style , <EOL> legend_font_size , legend_font_weight , legend_marker_scale , <EOL> legend_location , legend_bbox_to_anchor , legend_border_axes_pad , <EOL> legend_n_columns , legend_horizontal_spacing , <EOL> legend_vertical_spacing , legend_border , legend_border_padding , <EOL> legend_shadow , legend_rounded_corners , render_axes , axes_font_name , <EOL> axes_font_size , axes_font_style , axes_font_weight , axes_x_limits , <EOL> axes_y_limits , axes_x_ticks , axes_y_ticks , figure_size ) <EOL> def crop ( self , min_indices , max_indices , constrain_to_boundary = False , <EOL> return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> min_indices = np . floor ( min_indices ) <EOL> max_indices = np . ceil ( max_indices ) <EOL> if not ( min_indices . size == max_indices . size == self . n_dims ) : <EOL> raise ValueError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" . format ( self . n_dims ) ) <EOL> elif not np . all ( max_indices > min_indices ) : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> min_bounded = self . constrain_points_to_bounds ( min_indices ) <EOL> max_bounded = self . constrain_points_to_bounds ( max_indices ) <EOL> all_max_bounded = np . all ( min_bounded == min_indices ) <EOL> all_min_bounded = np . all ( max_bounded == max_indices ) <EOL> if not ( constrain_to_boundary or all_max_bounded or all_min_bounded ) : <EOL> raise ImageBoundaryError ( min_indices , max_indices , <EOL> min_bounded , max_bounded ) <EOL> new_shape = max_bounded - min_bounded <EOL> return self . warp_to_shape ( new_shape , Translation ( min_bounded ) , order = <NUM_LIT:0> , <EOL> warp_landmarks = True , <EOL> return_transform = return_transform ) <EOL> def crop_to_pointcloud ( self , pointcloud , boundary = <NUM_LIT:0> , <EOL> constrain_to_boundary = True , <EOL> return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> min_indices , max_indices = pointcloud . bounds ( boundary = boundary ) <EOL> return self . crop ( min_indices , max_indices , <EOL> constrain_to_boundary = constrain_to_boundary , <EOL> return_transform = return_transform ) <EOL> def crop_to_landmarks ( self , group = None , boundary = <NUM_LIT:0> , <EOL> constrain_to_boundary = True , <EOL> return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> pc = self . landmarks [ group ] . lms <EOL> return self . crop_to_pointcloud ( <EOL> pc , boundary = boundary , constrain_to_boundary = constrain_to_boundary , <EOL> return_transform = return_transform ) <EOL> def crop_to_pointcloud_proportion ( self , pointcloud , boundary_proportion , <EOL> minimum = True , <EOL> constrain_to_boundary = True , <EOL> return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> if minimum : <EOL> boundary = boundary_proportion * np . min ( pointcloud . range ( ) ) <EOL> else : <EOL> boundary = boundary_proportion * np . max ( pointcloud . range ( ) ) <EOL> return self . crop_to_pointcloud ( <EOL> pointcloud , boundary = boundary , <EOL> constrain_to_boundary = constrain_to_boundary , <EOL> return_transform = return_transform ) <EOL> def crop_to_landmarks_proportion ( self , boundary_proportion , <EOL> group = None , minimum = True , <EOL> constrain_to_boundary = True , <EOL> return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> pc = self . landmarks [ group ] . lms <EOL> return self . crop_to_pointcloud_proportion ( <EOL> pc , boundary_proportion , minimum = minimum , <EOL> constrain_to_boundary = constrain_to_boundary , <EOL> return_transform = return_transform ) <EOL> def _propagate_crop_to_inplace ( self , cropped ) : <EOL> self . pixels = cropped . pixels <EOL> self . landmarks = cropped . landmarks <EOL> if hasattr ( self , '<STR_LIT>' ) : <EOL> self . mask = cropped . mask <EOL> return self <EOL> def constrain_points_to_bounds ( self , points ) : <EOL> r"""<STR_LIT>""" <EOL> bounded_points = points . copy ( ) <EOL> bounded_points [ bounded_points < <NUM_LIT:0> ] = <NUM_LIT:0> <EOL> shape = np . array ( self . shape ) <EOL> over_image = ( shape - bounded_points ) < <NUM_LIT:0> <EOL> bounded_points [ over_image ] = shape [ over_image ] <EOL> return bounded_points <EOL> def extract_patches ( self , patch_centers , patch_shape = ( <NUM_LIT:16> , <NUM_LIT:16> ) , <EOL> sample_offsets = None , as_single_array = True ) : <EOL> r"""<STR_LIT>""" <EOL> if self . n_dims != <NUM_LIT:2> : <EOL> raise ValueError ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> if sample_offsets is None : <EOL> sample_offsets = np . zeros ( [ <NUM_LIT:1> , <NUM_LIT:2> ] , dtype = np . intp ) <EOL> else : <EOL> sample_offsets = np . require ( sample_offsets , dtype = np . intp ) <EOL> patch_centers = np . require ( patch_centers . points , dtype = np . float , <EOL> requirements = [ '<STR_LIT:C>' ] ) <EOL> single_array = extract_patches ( self . pixels , patch_centers , <EOL> np . asarray ( patch_shape , dtype = np . intp ) , <EOL> sample_offsets ) <EOL> if as_single_array : <EOL> return single_array <EOL> else : <EOL> return [ Image ( o , copy = False ) for p in single_array for o in p ] <EOL> def extract_patches_around_landmarks ( <EOL> self , group = None , patch_shape = ( <NUM_LIT:16> , <NUM_LIT:16> ) , <EOL> sample_offsets = None , as_single_array = True ) : <EOL> r"""<STR_LIT>""" <EOL> return self . extract_patches ( self . landmarks [ group ] . lms , <EOL> patch_shape = patch_shape , <EOL> sample_offsets = sample_offsets , <EOL> as_single_array = as_single_array ) <EOL> def set_patches ( self , patches , patch_centers , offset = None , <EOL> offset_index = None ) : <EOL> r"""<STR_LIT>""" <EOL> if self . n_dims != <NUM_LIT:2> : <EOL> raise ValueError ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> if offset is None : <EOL> offset = np . zeros ( [ <NUM_LIT:1> , <NUM_LIT:2> ] , dtype = np . intp ) <EOL> elif isinstance ( offset , tuple ) or isinstance ( offset , list ) : <EOL> offset = np . asarray ( [ offset ] ) <EOL> offset = np . require ( offset , dtype = np . intp ) <EOL> if not offset . shape == ( <NUM_LIT:1> , <NUM_LIT:2> ) : <EOL> raise ValueError ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> if offset_index is None : <EOL> offset_index = <NUM_LIT:0> <EOL> if isinstance ( patches , list ) : <EOL> patches = _convert_patches_list_to_single_array ( <EOL> patches , patch_centers . n_points ) <EOL> set_patches ( patches , self . pixels , patch_centers . points , offset , <EOL> offset_index ) <EOL> def set_patches_around_landmarks ( self , patches , group = None , <EOL> offset = None , offset_index = None ) : <EOL> r"""<STR_LIT>""" <EOL> return self . set_patches ( patches , self . landmarks [ group ] . lms , <EOL> offset = offset , offset_index = offset_index ) <EOL> def warp_to_mask ( self , template_mask , transform , warp_landmarks = True , <EOL> order = <NUM_LIT:1> , mode = '<STR_LIT>' , cval = <NUM_LIT:0.0> , batch_size = None , <EOL> return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> if self . n_dims != transform . n_dims : <EOL> raise ValueError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" . format ( self . n_dims , transform . n_dims ) ) <EOL> template_points = template_mask . true_indices ( ) <EOL> points_to_sample = transform . apply ( template_points , <EOL> batch_size = batch_size ) <EOL> sampled = self . sample ( points_to_sample , <EOL> order = order , mode = mode , cval = cval ) <EOL> sampled [ np . isnan ( sampled ) ] = <NUM_LIT:0> <EOL> warped_image = self . _build_warp_to_mask ( template_mask , sampled ) <EOL> if warp_landmarks and self . has_landmarks : <EOL> warped_image . landmarks = self . landmarks <EOL> transform . pseudoinverse ( ) . _apply_inplace ( warped_image . landmarks ) <EOL> if hasattr ( self , '<STR_LIT:path>' ) : <EOL> warped_image . path = self . path <EOL> if return_transform : <EOL> return warped_image , transform <EOL> else : <EOL> return warped_image <EOL> def _build_warp_to_mask ( self , template_mask , sampled_pixel_values ) : <EOL> r"""<STR_LIT>""" <EOL> from menpo . image import MaskedImage <EOL> warped_image = MaskedImage . init_blank ( template_mask . shape , <EOL> n_channels = self . n_channels , <EOL> mask = template_mask ) <EOL> warped_image . _from_vector_inplace ( sampled_pixel_values . ravel ( ) ) <EOL> return warped_image <EOL> def sample ( self , points_to_sample , order = <NUM_LIT:1> , mode = '<STR_LIT>' , cval = <NUM_LIT:0.0> ) : <EOL> r"""<STR_LIT>""" <EOL> if isinstance ( points_to_sample , PointCloud ) : <EOL> points_to_sample = points_to_sample . points <EOL> return scipy_interpolation ( self . pixels , points_to_sample , <EOL> order = order , mode = mode , cval = cval ) <EOL> def warp_to_shape ( self , template_shape , transform , warp_landmarks = True , <EOL> order = <NUM_LIT:1> , mode = '<STR_LIT>' , cval = <NUM_LIT:0.0> , batch_size = None , <EOL> return_transform = False ) : <EOL> """<STR_LIT>""" <EOL> template_shape = np . array ( template_shape , dtype = np . int ) <EOL> if ( isinstance ( transform , Affine ) and order in range ( <NUM_LIT:4> ) and <EOL> self . n_dims == <NUM_LIT:2> ) : <EOL> if isinstance ( transform , Translation ) and order == <NUM_LIT:0> : <EOL> t = transform . translation_component . copy ( ) <EOL> pos_t = t > <NUM_LIT:0.0> <EOL> t [ pos_t ] += <NUM_LIT:0.5> <EOL> t [ ~ pos_t ] -= <NUM_LIT:0.5> <EOL> min_ = t . astype ( np . int ) <EOL> max_ = template_shape + min_ <EOL> if np . all ( max_ <= np . array ( self . shape ) ) and np . all ( min_ >= <NUM_LIT:0> ) : <EOL> warped_pixels = self . pixels [ : , <EOL> int ( min_ [ <NUM_LIT:0> ] ) : int ( max_ [ <NUM_LIT:0> ] ) , <EOL> int ( min_ [ <NUM_LIT:1> ] ) : int ( max_ [ <NUM_LIT:1> ] ) ] . copy ( ) <EOL> return self . _build_warp_to_shape ( warped_pixels , transform , <EOL> warp_landmarks , <EOL> return_transform ) <EOL> sampled = cython_interpolation ( self . pixels , template_shape , <EOL> transform , order = order , <EOL> mode = mode , cval = cval ) <EOL> else : <EOL> template_points = indices_for_image_of_shape ( template_shape ) <EOL> points_to_sample = transform . apply ( template_points , <EOL> batch_size = batch_size ) <EOL> sampled = self . sample ( points_to_sample , <EOL> order = order , mode = mode , cval = cval ) <EOL> sampled [ np . isnan ( sampled ) ] = <NUM_LIT:0> <EOL> warped_pixels = sampled . reshape ( <EOL> ( self . n_channels , ) + tuple ( template_shape ) ) <EOL> return self . _build_warp_to_shape ( warped_pixels , transform , <EOL> warp_landmarks , return_transform ) <EOL> def _build_warp_to_shape ( self , warped_pixels , transform , warp_landmarks , <EOL> return_transform ) : <EOL> warped_image = Image ( warped_pixels , copy = False ) <EOL> if warp_landmarks and self . has_landmarks : <EOL> warped_image . landmarks = self . landmarks <EOL> transform . pseudoinverse ( ) . _apply_inplace ( warped_image . landmarks ) <EOL> if hasattr ( self , '<STR_LIT:path>' ) : <EOL> warped_image . path = self . path <EOL> if return_transform : <EOL> return warped_image , transform <EOL> else : <EOL> return warped_image <EOL> def rescale ( self , scale , round = '<STR_LIT>' , order = <NUM_LIT:1> , <EOL> return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> try : <EOL> if len ( scale ) < self . n_dims : <EOL> raise ValueError ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' . format ( <EOL> len ( scale ) , self . n_dims <EOL> ) <EOL> ) <EOL> except TypeError : <EOL> scale = [ scale ] * self . n_dims <EOL> scale = np . asarray ( scale ) <EOL> for s in scale : <EOL> if s <= <NUM_LIT:0> : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> transform = NonUniformScale ( scale ) <EOL> template_shape = round_image_shape ( transform . apply ( self . shape ) , <EOL> round ) <EOL> shape = np . array ( self . shape , dtype = np . float ) <EOL> scale_factors = ( scale * shape - <NUM_LIT:1> ) / ( shape - <NUM_LIT:1> ) <EOL> inverse_transform = NonUniformScale ( scale_factors ) . pseudoinverse ( ) <EOL> return self . warp_to_shape ( template_shape , inverse_transform , <EOL> warp_landmarks = True , order = order , <EOL> mode = '<STR_LIT>' , <EOL> return_transform = return_transform ) <EOL> def rescale_to_diagonal ( self , diagonal , round = '<STR_LIT>' , <EOL> return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> return self . rescale ( diagonal / self . diagonal ( ) , round = round , <EOL> return_transform = return_transform ) <EOL> def rescale_to_pointcloud ( self , pointcloud , group = None , <EOL> round = '<STR_LIT>' , order = <NUM_LIT:1> , <EOL> return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> pc = self . landmarks [ group ] . lms <EOL> scale = AlignmentUniformScale ( pc , pointcloud ) . as_vector ( ) . copy ( ) <EOL> return self . rescale ( scale , round = round , order = order , <EOL> return_transform = return_transform ) <EOL> def rescale_landmarks_to_diagonal_range ( self , diagonal_range , group = None , <EOL> round = '<STR_LIT>' , order = <NUM_LIT:1> , <EOL> return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> x , y = self . landmarks [ group ] . lms . range ( ) <EOL> scale = diagonal_range / np . sqrt ( x ** <NUM_LIT:2> + y ** <NUM_LIT:2> ) <EOL> return self . rescale ( scale , round = round , order = order , <EOL> return_transform = return_transform ) <EOL> def resize ( self , shape , order = <NUM_LIT:1> , return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> shape = np . asarray ( shape , dtype = np . float ) <EOL> if len ( shape ) != self . n_dims : <EOL> raise ValueError ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' . format ( <EOL> shape . shape , self . n_dims ) ) <EOL> scales = shape / self . shape <EOL> return self . rescale ( scales , round = '<STR_LIT>' , order = order , <EOL> return_transform = return_transform ) <EOL> def zoom ( self , scale , cval = <NUM_LIT:0.0> , return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> t = scale_about_centre ( self , <NUM_LIT:1.0> / scale ) <EOL> return self . warp_to_shape ( self . shape , t , cval = cval , <EOL> return_transform = return_transform ) <EOL> def rotate_ccw_about_centre ( self , theta , degrees = True , retain_shape = False , <EOL> cval = <NUM_LIT:0.0> , round = '<STR_LIT>' , order = <NUM_LIT:1> , <EOL> return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> if self . n_dims != <NUM_LIT:2> : <EOL> raise ValueError ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> if retain_shape : <EOL> trans = rotate_ccw_about_centre ( self , theta , degrees = degrees ) <EOL> shape = self . shape <EOL> else : <EOL> bbox = bounding_box ( ( <NUM_LIT:0> , <NUM_LIT:0> ) , [ self . shape [ <NUM_LIT:0> ] - <NUM_LIT:1> , self . shape [ <NUM_LIT:1> ] - <NUM_LIT:1> ] ) <EOL> trans = Translation ( - self . centre ( ) , <EOL> skip_checks = True ) . compose_before ( <EOL> Rotation . init_from_2d_ccw_angle ( theta , degrees = degrees ) ) <EOL> rotated_bbox = trans . apply ( bbox ) <EOL> t = Translation ( - rotated_bbox . bounds ( ) [ <NUM_LIT:0> ] ) <EOL> trans . compose_before_inplace ( t ) <EOL> rotated_bbox = trans . apply ( bbox ) <EOL> shape = round_image_shape ( rotated_bbox . range ( ) + <NUM_LIT:1> , round ) <EOL> return self . warp_to_shape ( <EOL> shape , trans . pseudoinverse ( ) , order = order , warp_landmarks = True , <EOL> cval = cval , return_transform = return_transform ) <EOL> def mirror ( self , axis = <NUM_LIT:1> , return_transform = False ) : <EOL> r"""<STR_LIT>""" <EOL> if axis < <NUM_LIT:0> : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> elif axis >= self . n_dims : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" . format ( axis , self . n_dims ) ) <EOL> rot_matrix = np . eye ( self . n_dims ) <EOL> rot_matrix [ axis , axis ] = - <NUM_LIT:1> <EOL> tr_matrix = np . zeros ( self . n_dims ) <EOL> tr_matrix [ axis ] = self . shape [ axis ] - <NUM_LIT:1> <EOL> trans = Rotation ( rot_matrix , skip_checks = True ) . compose_before ( <EOL> Translation ( tr_matrix , skip_checks = True ) ) <EOL> return self . warp_to_shape ( self . shape , trans . pseudoinverse ( ) , <EOL> warp_landmarks = True , <EOL> return_transform = return_transform ) <EOL> def pyramid ( self , n_levels = <NUM_LIT:3> , downscale = <NUM_LIT:2> ) : <EOL> r"""<STR_LIT>""" <EOL> image = self <EOL> yield image <EOL> for _ in range ( n_levels - <NUM_LIT:1> ) : <EOL> image = image . rescale ( <NUM_LIT:1.0> / downscale ) <EOL> yield image <EOL> def gaussian_pyramid ( self , n_levels = <NUM_LIT:3> , downscale = <NUM_LIT:2> , sigma = None ) : <EOL> r"""<STR_LIT>""" <EOL> from menpo . feature import gaussian_filter <EOL> if sigma is None : <EOL> sigma = downscale / <NUM_LIT> <EOL> image = self <EOL> yield image <EOL> for level in range ( n_levels - <NUM_LIT:1> ) : <EOL> image = gaussian_filter ( image , sigma ) . rescale ( <NUM_LIT:1.0> / downscale ) <EOL> yield image <EOL> def as_greyscale ( self , mode = '<STR_LIT>' , channel = None ) : <EOL> r"""<STR_LIT>""" <EOL> greyscale = self . copy ( ) <EOL> if mode == '<STR_LIT>' : <EOL> if self . n_dims != <NUM_LIT:2> : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" . format ( self . n_dims ) ) <EOL> elif self . n_channels != <NUM_LIT:3> : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" . format ( self . n_channels ) ) <EOL> global _greyscale_luminosity_coef <EOL> if _greyscale_luminosity_coef is None : <EOL> _greyscale_luminosity_coef = np . linalg . inv ( <EOL> np . array ( [ [ <NUM_LIT:1.0> , <NUM_LIT> , <NUM_LIT> ] , <EOL> [ <NUM_LIT:1.0> , - <NUM_LIT> , - <NUM_LIT> ] , <EOL> [ <NUM_LIT:1.0> , - <NUM_LIT> , <NUM_LIT> ] ] ) ) [ <NUM_LIT:0> , : ] <EOL> pixels = np . dot ( _greyscale_luminosity_coef , <EOL> greyscale . pixels . reshape ( <NUM_LIT:3> , - <NUM_LIT:1> ) ) <EOL> pixels = pixels . reshape ( greyscale . shape ) <EOL> elif mode == '<STR_LIT>' : <EOL> pixels = np . mean ( greyscale . pixels , axis = <NUM_LIT:0> ) <EOL> elif mode == '<STR_LIT>' : <EOL> if channel is None : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> pixels = greyscale . pixels [ channel ] <EOL> else : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" . format ( mode ) ) <EOL> greyscale . pixels = pixels [ None , ... ] . astype ( greyscale . pixels . dtype , <EOL> copy = False ) <EOL> return greyscale <EOL> def as_PILImage ( self , out_dtype = np . uint8 ) : <EOL> r"""<STR_LIT>""" <EOL> if self . n_dims != <NUM_LIT:2> or ( self . n_channels != <NUM_LIT:1> and self . n_channels != <NUM_LIT:3> ) : <EOL> raise ValueError ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' . format ( self . n_channels , <EOL> self . n_dims ) ) <EOL> if self . n_channels == <NUM_LIT:1> : <EOL> pixels = self . pixels [ <NUM_LIT:0> ] <EOL> else : <EOL> pixels = channels_to_back ( self . pixels ) <EOL> pixels = denormalise_pixels_range ( pixels , out_dtype ) <EOL> return PILImage . fromarray ( pixels ) <EOL> def as_imageio ( self , out_dtype = np . uint8 ) : <EOL> r"""<STR_LIT>""" <EOL> if self . n_dims != <NUM_LIT:2> or ( self . n_channels != <NUM_LIT:1> and self . n_channels != <NUM_LIT:3> ) : <EOL> raise ValueError ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' . format ( self . n_channels , <EOL> self . n_dims ) ) <EOL> if self . n_channels == <NUM_LIT:1> : <EOL> pixels = self . pixels [ <NUM_LIT:0> ] <EOL> else : <EOL> pixels = channels_to_back ( self . pixels ) <EOL> return denormalise_pixels_range ( pixels , out_dtype ) <EOL> def pixels_range ( self ) : <EOL> r"""<STR_LIT>""" <EOL> return self . pixels . min ( ) , self . pixels . max ( ) <EOL> def rolled_channels ( self ) : <EOL> r"""<STR_LIT>""" <EOL> return channels_to_back ( self . pixels ) <EOL> def __str__ ( self ) : <EOL> return ( '<STR_LIT>' . format ( <EOL> self . _str_shape ( ) , self . n_dims , self . n_channels , <EOL> '<STR_LIT:s>' * ( self . n_channels > <NUM_LIT:1> ) ) ) <EOL> @ property <EOL> def has_landmarks_outside_bounds ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . landmarks . has_landmarks : <EOL> for l_group in self . landmarks : <EOL> pc = self . landmarks [ l_group ] . lms . points <EOL> if np . any ( np . logical_or ( self . shape - pc < <NUM_LIT:1> , pc < <NUM_LIT:0> ) ) : <EOL> return True <EOL> return False <EOL> def constrain_landmarks_to_bounds ( self ) : <EOL> r"""<STR_LIT>""" <EOL> if self . has_landmarks_outside_bounds : <EOL> for l_group in self . landmarks : <EOL> l = self . landmarks [ l_group ] <EOL> for k in range ( l . lms . points . shape [ <NUM_LIT:1> ] ) : <EOL> tmp = l . lms . points [ : , k ] <EOL> tmp [ tmp < <NUM_LIT:0> ] = <NUM_LIT:0> <EOL> tmp [ tmp > self . shape [ k ] - <NUM_LIT:1> ] = self . shape [ k ] - <NUM_LIT:1> <EOL> l . lms . points [ : , k ] = tmp <EOL> self . landmarks [ l_group ] = l <EOL> def normalize_std_inplace ( self , mode = '<STR_LIT:all>' , ** kwargs ) : <EOL> r"""<STR_LIT>""" <EOL> warn ( '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' , MenpoDeprecationWarning ) <EOL> self . _normalize_inplace ( np . std , mode = mode ) <EOL> def normalize_std ( self , mode = '<STR_LIT:all>' , ** kwargs ) : <EOL> r"""<STR_LIT>""" <EOL> return self . _normalize ( np . std , mode = mode ) <EOL> def normalize_norm_inplace ( self , mode = '<STR_LIT:all>' , ** kwargs ) : <EOL> r"""<STR_LIT>""" <EOL> warn ( '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' , MenpoDeprecationWarning ) <EOL> def scale_func ( pixels , axis = None ) : <EOL> return np . linalg . norm ( pixels , axis = axis , ** kwargs ) <EOL> self . _normalize_inplace ( scale_func , mode = mode ) <EOL> def normalize_norm ( self , mode = '<STR_LIT:all>' , ** kwargs ) : <EOL> r"""<STR_LIT>""" <EOL> def scale_func ( pixels , axis = None ) : <EOL> return np . linalg . norm ( pixels , axis = axis , ** kwargs ) <EOL> return self . _normalize ( scale_func , mode = mode ) <EOL> def _normalize ( self , scale_func , mode = '<STR_LIT:all>' ) : <EOL> new = self . copy ( ) <EOL> new . _normalize_inplace ( scale_func , mode = mode ) <EOL> return new <EOL> def _normalize_inplace ( self , scale_func , mode = '<STR_LIT:all>' ) : <EOL> pixels = self . as_vector ( keep_channels = True ) <EOL> if mode == '<STR_LIT:all>' : <EOL> centered_pixels = pixels - np . mean ( pixels ) <EOL> scale_factor = scale_func ( centered_pixels ) <EOL> elif mode == '<STR_LIT>' : <EOL> centered_pixels = pixels - np . mean ( pixels , axis = <NUM_LIT:1> ) [ ... , None ] <EOL> scale_factor = scale_func ( centered_pixels , axis = <NUM_LIT:1> ) [ ... , None ] <EOL> else : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" . format ( mode ) ) <EOL> if np . any ( scale_factor == <NUM_LIT:0> ) : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> else : <EOL> self . _from_vector_inplace ( centered_pixels / scale_factor ) <EOL> def rescale_pixels ( self , minimum , maximum , per_channel = True ) : <EOL> r"""<STR_LIT>""" <EOL> v = self . as_vector ( keep_channels = True ) . T <EOL> if per_channel : <EOL> min_ , max_ = v . min ( axis = <NUM_LIT:0> ) , v . max ( axis = <NUM_LIT:0> ) <EOL> else : <EOL> min_ , max_ = v . min ( ) , v . max ( ) <EOL> sf = ( ( maximum - minimum ) * <NUM_LIT:1.0> ) / ( max_ - min_ ) <EOL> v_new = ( ( v - min_ ) * sf ) + minimum <EOL> return self . from_vector ( v_new . T . ravel ( ) ) <EOL> def round_image_shape ( shape , round ) : <EOL> if round not in [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> return tuple ( getattr ( np , round ) ( shape ) . astype ( np . int ) ) <EOL> def _convert_patches_list_to_single_array ( patches_list , n_center ) : <EOL> r"""<STR_LIT>""" <EOL> n_offsets = np . int ( len ( patches_list ) / n_center ) <EOL> n_channels = patches_list [ <NUM_LIT:0> ] . n_channels <EOL> height = patches_list [ <NUM_LIT:0> ] . height <EOL> width = patches_list [ <NUM_LIT:0> ] . width <EOL> patches_array = np . empty ( ( n_center , n_offsets , n_channels , height , width ) , <EOL> dtype = patches_list [ <NUM_LIT:0> ] . pixels . dtype ) <EOL> total_index = <NUM_LIT:0> <EOL> for p in range ( n_center ) : <EOL> for o in range ( n_offsets ) : <EOL> patches_array [ p , o , ... ] = patches_list [ total_index ] . pixels <EOL> total_index += <NUM_LIT:1> <EOL> return patches_array <EOL> def _create_patches_image ( patches , patch_centers , patches_indices = None , <EOL> offset_index = None , background = '<STR_LIT>' ) : <EOL> r"""<STR_LIT>""" <EOL> if isinstance ( patches , list ) : <EOL> patches = _convert_patches_list_to_single_array ( patches , <EOL> patch_centers . n_points ) <EOL> if offset_index is None : <EOL> offset_index = <NUM_LIT:0> <EOL> if patches_indices is None : <EOL> patches_indices = np . arange ( patches . shape [ <NUM_LIT:0> ] ) <EOL> elif not isinstance ( patches_indices , Iterable ) : <EOL> patches_indices = [ patches_indices ] <EOL> n_channels = patches . shape [ <NUM_LIT:2> ] <EOL> patch_shape0 = patches . shape [ <NUM_LIT:3> ] <EOL> patch_shape1 = patches . shape [ <NUM_LIT:4> ] <EOL> top , left = np . min ( patch_centers . points , <NUM_LIT:0> ) <EOL> bottom , right = np . max ( patch_centers . points , <NUM_LIT:0> ) <EOL> min_0 = np . floor ( top - patch_shape0 ) <EOL> min_1 = np . floor ( left - patch_shape1 ) <EOL> max_0 = np . ceil ( bottom + patch_shape0 ) <EOL> max_1 = np . ceil ( right + patch_shape1 ) <EOL> height = max_0 - min_0 + <NUM_LIT:1> <EOL> width = max_1 - min_1 + <NUM_LIT:1> <EOL> new_patch_centers = patch_centers . copy ( ) <EOL> new_patch_centers . points = patch_centers . points - np . array ( [ [ min_0 , min_1 ] ] ) <EOL> tmp_centers = PointCloud ( new_patch_centers . points [ patches_indices ] ) <EOL> if background == '<STR_LIT>' : <EOL> patches_image = Image . init_blank ( <EOL> ( height , width ) , n_channels , <EOL> fill = np . min ( patches [ patches_indices ] ) , <EOL> dtype = patches . dtype ) <EOL> elif background == '<STR_LIT>' : <EOL> patches_image = Image . init_blank ( <EOL> ( height , width ) , n_channels , <EOL> fill = np . max ( patches [ patches_indices ] ) , <EOL> dtype = patches . dtype ) <EOL> else : <EOL> raise ValueError ( '<STR_LIT>' '<STR_LIT>' '<STR_LIT>' '<STR_LIT>' '<STR_LIT:.>' ) <EOL> patches_image . landmarks [ '<STR_LIT>' ] = new_patch_centers <EOL> patches_image . landmarks [ '<STR_LIT>' ] = tmp_centers <EOL> patches_image . set_patches_around_landmarks ( patches [ patches_indices ] , <EOL> group = '<STR_LIT>' , <EOL> offset_index = offset_index ) <EOL> return patches_image </s>
