Exemple #1
0
    def update_mask(self, mask, positive_mask=True):
        """

        Parameters
        ----------

        mask: NIPY Image
           A masking function which may be encoded as masked:=1 or
           masked:=0. The coordinate mapping must be identical to the
           original input Image (IE, the support of this function must
           be the support of the original Image).
        positive_mask: {True,False}
           by default, the masking function will be taken as masked:=0
        """
        # XYZ: CURRENTLY OBLITERATES OLD MASK! IS THIS DESIRABLE?
        mdata = np.asarray(mask)
        # convert mdata to boolean type negative-mask
        if positive_mask:
            if mdata.dtype.char is not 'B':
                mdata = mdata.astype('B')
            mdata = np.logical_not(mdata)

        # now, if necessary resample the mask ...
        if len(self.__resamp_kws):
            m_resamp = ni_api.Image(mdata.astype('d'), mask.coordmap)
            m_resamp = vu.resample_to_world_grid(
                m_resamp, cval=1, **self.__resamp_kws
                )
            # ... and set mdata to wherever the mask goes towards 1
            mdata = (np.asarray(m_resamp) > 0.5)


        print 'new unmasked pts:', mdata.size - mdata.sum()
        self.image_arr = np.ma.masked_array(np.ma.getdata(self.image_arr),
                                            mask=mdata)
Exemple #2
0
    def __init__(self, image, bbox=None, mask=False,
                 grid_spacing=None, spatial_axes=None,
                 **interp_kws):
        """
        Creates a new ResampledVolumeSlicer
        
        Parameters
        ----------
        image : a NIPY Image
          The image to slice
        bbox : iterable (optional)
          The {x,y,z} limits of the enrounding volume box. If None, then
          slices planes in the natural box of the image. This argument
          is useful for overlaying an image onto another image's volume box
        mask : bool or ndarray (optional)
          A binary mask, with same shape as image, with unmasked points
          marked as True (opposite of MaskedArray convention)
        grid_spacing : sequence (optional)
          New grid spacing for the sliced planes. If None, then the
          natural voxel spacing is used.
        spatial_axes : sequence (optional)
          Normally the image will not be resampled as long as there is a
          one-to-one correspondence from array axes to spatial axes. However,
          a desired correspondence can be specified here. List in 'x, y, z'
          order.
        interp_kws : dict
          Keyword args for the interpolating machinery.. eg:
          * order -- spline order
          * mode --  Points outside the boundaries of the input are filled
                     according to the given mode ('constant', 'nearest',
                     'reflect' or 'wrap'). Default is 'constant'.
          * cval -- fill value if mode is 'constant'
            
        """

        # XYZ: NEED TO BREAK API HERE FOR MASKED ARRAY
        xyz_image = ni_api.Image(
            image._data,
            image.coordmap.reordered_range(xipy_ras)
            )

        native_spacing = vu.voxel_size(xyz_image.affine)
        zoom_grid = grid_spacing is not None and \
                    (np.array(grid_spacing) != native_spacing).any()
        
        # if no special instructions and image is somewhat aligned,
        # don't bother with rotations
        aligned = vu.is_spatially_aligned(image.coordmap) and not zoom_grid
        self.__resamp_kws = dict()
        if aligned:
            # if aligned, double check that it is also aligned with
            # spatial_axes (if present)
            axes = vu.find_spatial_correspondence(image.coordmap)
            if spatial_axes and axes != spatial_axes:
                # XYZ: IF ARRAY IS ALIGNED IN SOME ORIENTATION, COULD
                # RE-ALIGN WITH "spatial_axes" WITH A SIMPLE TRANSFORM
                aligned = False
                interp_kws['order'] = 0
            else:
                world_image = xyz_image
        if not aligned:
            print 'resampling entire Image volume'
            self.__resamp_kws.update(interp_kws)
            self.__resamp_kws.update(
                dict(grid_spacing=grid_spacing, axis_permutation=spatial_axes)
                )
            world_image = vu.resample_to_world_grid(
                image, **self.__resamp_kws
                )

        

        self.coordmap = world_image.coordmap
        self.image_arr = np.asanyarray(world_image)
        self.grid_spacing = vu.voxel_size(world_image.affine)

        # take down the final bounding box; this will define the
        # field of the overlay plot
        self.bbox = vu.world_limits(world_image)
        

        # now find the logical axis to array axis mapping
        self._ax_lookup = vu.spatial_axes_lookup(self.coordmap)
    
        w_shape = world_image.shape
        # these planes are shaped as if the image_arr were
        # sliced along a given axis
        self.null_planes = [np.ma.masked_all((w_shape[0], w_shape[1]),'B'),
                            np.ma.masked_all((w_shape[0], w_shape[2]),'B'),
                            np.ma.masked_all((w_shape[1], w_shape[2]),'B')]

        # finally, update mask if necessary
        mask = np.ma.getmask(image._data)
        if mask is not np.ma.nomask:
            mask = ni_api.Image(mask, image.coordmap)
            self.update_mask(mask, positive_mask=False)