Ejemplo n.º 1
0
Archivo: metrics.py Proyecto: nipy/dipy
    def initialize_iteration(self):
        r"""Prepares the metric to compute one displacement field iteration.

        Pre-computes the gradient of the input images to be used in the
        computation of the forward and backward steps.
        """
        self.gradient_moving = np.empty(
            shape=(self.moving_image.shape)+(self.dim,), dtype=floating)
        for i, grad in enumerate(gradient(self.moving_image)):
            self.gradient_moving[..., i] = grad

        # Convert static image's gradient field from voxel to physical space
        if self.moving_spacing is not None:
            self.gradient_moving /= self.moving_spacing
        if self.moving_direction is not None:
            self.reorient_vector_field(self.gradient_moving,
                                       self.moving_direction)

        self.gradient_static = np.empty(
            shape=(self.static_image.shape)+(self.dim,), dtype=floating)
        for i, grad in enumerate(gradient(self.static_image)):
            self.gradient_static[..., i] = grad

        # Convert static image's gradient field from voxel to physical space
        if self.static_spacing is not None:
            self.gradient_static /= self.static_spacing
        if self.static_direction is not None:
            self.reorient_vector_field(self.gradient_static,
                                       self.static_direction)
Ejemplo n.º 2
0
    def initialize_iteration(self):
        r"""Prepares the metric to compute one displacement field iteration.

        Pre-computes the gradient of the input images to be used in the
        computation of the forward and backward steps.
        """
        self.gradient_moving = np.empty(shape=(self.moving_image.shape) +
                                        (self.dim, ),
                                        dtype=floating)
        for i, grad in enumerate(gradient(self.moving_image)):
            self.gradient_moving[..., i] = grad

        # Convert static image's gradient field from voxel to physical space
        if self.moving_spacing is not None:
            self.gradient_moving /= self.moving_spacing
        if self.moving_direction is not None:
            self.reorient_vector_field(self.gradient_moving,
                                       self.moving_direction)

        self.gradient_static = np.empty(shape=(self.static_image.shape) +
                                        (self.dim, ),
                                        dtype=floating)
        for i, grad in enumerate(gradient(self.static_image)):
            self.gradient_static[..., i] = grad

        # Convert static image's gradient field from voxel to physical space
        if self.static_spacing is not None:
            self.gradient_static /= self.static_spacing
        if self.static_direction is not None:
            self.reorient_vector_field(self.gradient_static,
                                       self.static_direction)
Ejemplo n.º 3
0
 def initialize_iteration(self):
     r'''
     Precomputes the transfer functions (hidden random variables) and
     variances of the estimators. Also precomputes the gradient of both
     input images. Note that once the images are transformed to the opposite
     modality, the gradient of the transformed images can be used with the
     gradient of the corresponding modality in the same fasion as
     diff-demons does for mono-modality images. If the flag
     self.use_double_gradient is True these garadients are averaged.
     '''
     self.__connect_functions()
     sampling_mask = self.fixed_image_mask * self.moving_image_mask
     self.sampling_mask = sampling_mask
     fixedq, self.fixedq_levels, hist = self.quantize(
         self.fixed_image, self.q_levels)
     fixedq = np.array(fixedq, dtype=np.int32)
     self.fixedq_levels = np.array(self.fixedq_levels)
     fixedq_means, fixedq_variances = self.compute_stats(
         sampling_mask, self.moving_image, self.q_levels, fixedq)
     fixedq_means[0] = 0
     fixedq_means = np.array(fixedq_means)
     fixedq_variances = np.array(fixedq_variances)
     self.fixedq_sigma_field = fixedq_variances[fixedq]
     self.fixedq_means_field = fixedq_means[fixedq]
     self.gradient_moving = np.empty(shape=(self.moving_image.shape) +
                                     (self.dim, ),
                                     dtype=np.float64)
     i = 0
     for grad in sp.gradient(self.moving_image):
         self.gradient_moving[..., i] = grad
         i += 1
     self.gradient_fixed = np.empty(shape=(self.fixed_image.shape) +
                                    (self.dim, ),
                                    dtype=np.float64)
     i = 0
     for grad in sp.gradient(self.fixed_image):
         self.gradient_fixed[..., i] = grad
         i += 1
     movingq, self.movingq_levels, hist = self.quantize(
         self.moving_image, self.q_levels)
     movingq = np.array(movingq, dtype=np.int32)
     self.movingq_levels = np.array(self.movingq_levels)
     movingq_means, movingq_variances = self.compute_stats(
         sampling_mask, self.fixed_image, self.q_levels, movingq)
     movingq_means[0] = 0
     movingq_means = np.array(movingq_means)
     movingq_variances = np.array(movingq_variances)
     self.movingq_sigma_field = movingq_variances[movingq]
     self.movingq_means_field = movingq_means[movingq]
     if self.use_double_gradient:
         i = 0
         for grad in sp.gradient(self.fixedq_means_field):
             self.gradient_moving[..., i] += grad
             i += 1
         i = 0
         for grad in sp.gradient(self.movingq_means_field):
             self.gradient_fixed[..., i] += grad
             i += 1
Ejemplo n.º 4
0
 def initialize_iteration(self):
     r'''
     Precomputes the transfer functions (hidden random variables) and
     variances of the estimators. Also precomputes the gradient of both
     input images. Note that once the images are transformed to the opposite
     modality, the gradient of the transformed images can be used with the
     gradient of the corresponding modality in the same fasion as
     diff-demons does for mono-modality images. If the flag
     self.use_double_gradient is True these garadients are averaged.
     '''
     self.__connect_functions()
     sampling_mask = self.fixed_image_mask*self.moving_image_mask
     self.sampling_mask = sampling_mask
     fixedq, self.fixedq_levels, hist = self.quantize(self.fixed_image,
                                                   self.q_levels)
     fixedq = np.array(fixedq, dtype = np.int32)
     self.fixedq_levels = np.array(self.fixedq_levels)
     fixedq_means, fixedq_variances = self.compute_stats(sampling_mask,
                                                    self.moving_image,
                                                    self.q_levels,
                                                    fixedq)
     fixedq_means[0] = 0
     fixedq_means = np.array(fixedq_means)
     fixedq_variances = np.array(fixedq_variances)
     self.fixedq_sigma_field = fixedq_variances[fixedq]
     self.fixedq_means_field = fixedq_means[fixedq]
     self.gradient_moving = np.empty(
         shape = (self.moving_image.shape)+(self.dim,), dtype = np.float64)
     i = 0
     for grad in sp.gradient(self.moving_image):
         self.gradient_moving[..., i] = grad
         i += 1
     self.gradient_fixed = np.empty(
         shape = (self.fixed_image.shape)+(self.dim,), dtype = np.float64)
     i = 0
     for grad in sp.gradient(self.fixed_image):
         self.gradient_fixed[..., i] = grad
         i += 1
     movingq, self.movingq_levels, hist = self.quantize(self.moving_image,
                                                     self.q_levels)
     movingq = np.array(movingq, dtype = np.int32)
     self.movingq_levels = np.array(self.movingq_levels)
     movingq_means, movingq_variances = self.compute_stats(
         sampling_mask, self.fixed_image, self.q_levels, movingq)
     movingq_means[0] = 0
     movingq_means = np.array(movingq_means)
     movingq_variances = np.array(movingq_variances)
     self.movingq_sigma_field = movingq_variances[movingq]
     self.movingq_means_field = movingq_means[movingq]
     if self.use_double_gradient:
         i = 0
         for grad in sp.gradient(self.fixedq_means_field):
             self.gradient_moving[..., i] += grad
             i += 1
         i = 0
         for grad in sp.gradient(self.movingq_means_field):
             self.gradient_fixed[..., i] += grad
             i += 1
Ejemplo n.º 5
0
Archivo: metrics.py Proyecto: nipy/dipy
    def initialize_iteration(self):
        r"""Prepares the metric to compute one displacement field iteration.

        Pre-computes the cross-correlation factors for efficient computation
        of the gradient of the Cross Correlation w.r.t. the displacement field.
        It also pre-computes the image gradients in the physical space by
        re-orienting the gradients in the voxel space using the corresponding
        affine transformations.
        """

        def invalid_image_size(image):
            min_size = self.radius * 2 + 1
            return any([size < min_size for size in image.shape])

        msg = ("Each image dimension should be superior to 2 * radius + 1."
               "Decrease CCMetric radius or increase your image size")

        if invalid_image_size(self.static_image):
            raise ValueError("Static image size is too small. " + msg)
        if invalid_image_size(self.moving_image):
            raise ValueError("Moving image size is too small. " + msg)

        self.factors = self.precompute_factors(self.static_image,
                                               self.moving_image,
                                               self.radius)
        self.factors = np.array(self.factors)

        self.gradient_moving = np.empty(
            shape=(self.moving_image.shape)+(self.dim,), dtype=floating)
        for i, grad in enumerate(sp.gradient(self.moving_image)):
            self.gradient_moving[..., i] = grad

        # Convert moving image's gradient field from voxel to physical space
        if self.moving_spacing is not None:
            self.gradient_moving /= self.moving_spacing
        if self.moving_direction is not None:
            self.reorient_vector_field(self.gradient_moving,
                                       self.moving_direction)

        self.gradient_static = np.empty(
            shape=(self.static_image.shape)+(self.dim,), dtype=floating)
        for i, grad in enumerate(sp.gradient(self.static_image)):
            self.gradient_static[..., i] = grad

        # Convert moving image's gradient field from voxel to physical space
        if self.static_spacing is not None:
            self.gradient_static /= self.static_spacing
        if self.static_direction is not None:
            self.reorient_vector_field(self.gradient_static,
                                       self.static_direction)
Ejemplo n.º 6
0
    def gradient(self):
        """
        Return a numpy array containing the gradient of the sample data
        """
        # Check the number of axis
        if self.data.shape[1] > 1:  # More than 1 axis
            # Calculate the gradient and extract only the first element
            return sp.gradient(self.data)[0]
        else:  # The case with only one axis must be handled differently
            # Reshape the data
            reshaped = self.data.reshape(1, -1)[0]

            # Calculate the gradient and reshape the result
            return sp.gradient(reshaped).reshape(-1, 1)
Ejemplo n.º 7
0
    def initialize_iteration(self):
        r"""Prepares the metric to compute one displacement field iteration.

        Pre-computes the cross-correlation factors for efficient computation
        of the gradient of the Cross Correlation w.r.t. the displacement field.
        It also pre-computes the image gradients in the physical space by
        re-orienting the gradients in the voxel space using the corresponding
        affine transformations.
        """
        def invalid_image_size(image):
            min_size = self.radius * 2 + 1
            return any([size < min_size for size in image.shape])

        msg = ("Each image dimension should be superior to 2 * radius + 1."
               "Decrease CCMetric radius or increase your image size")

        if invalid_image_size(self.static_image):
            raise ValueError("Static image size is too small. " + msg)
        if invalid_image_size(self.moving_image):
            raise ValueError("Moving image size is too small. " + msg)

        self.factors = self.precompute_factors(self.static_image,
                                               self.moving_image, self.radius)
        self.factors = np.array(self.factors)

        self.gradient_moving = np.empty(shape=(self.moving_image.shape) +
                                        (self.dim, ),
                                        dtype=floating)
        for i, grad in enumerate(sp.gradient(self.moving_image)):
            self.gradient_moving[..., i] = grad

        # Convert moving image's gradient field from voxel to physical space
        if self.moving_spacing is not None:
            self.gradient_moving /= self.moving_spacing
        if self.moving_direction is not None:
            self.reorient_vector_field(self.gradient_moving,
                                       self.moving_direction)

        self.gradient_static = np.empty(shape=(self.static_image.shape) +
                                        (self.dim, ),
                                        dtype=floating)
        for i, grad in enumerate(sp.gradient(self.static_image)):
            self.gradient_static[..., i] = grad

        # Convert moving image's gradient field from voxel to physical space
        if self.static_spacing is not None:
            self.gradient_static /= self.static_spacing
        if self.static_direction is not None:
            self.reorient_vector_field(self.gradient_static,
                                       self.static_direction)
Ejemplo n.º 8
0
def estimateNewMultimodalRigidTransformation2D_ecqmmf(moving, fixed, probs, nclasses, previousBeta=None):
    epsilon=1e-9
    sh=moving.shape
    center=(np.array(sh)-1)/2.0
    X0,X1=np.mgrid[0:sh[0], 0:sh[1]]
    X0=X0-center[0]
    X1=X1-center[1]
    mask=np.ones_like(X0, dtype=np.int32)
    if((previousBeta!=None) and (np.max(np.abs(previousBeta))>epsilon)):
        R=rcommon.getRotationMatrix2D(previousBeta[0])
        X0new,X1new=(R[0,0]*X0 + R[0,1]*X1 + center[0] + 2.0*previousBeta[1],
                     R[1,0]*X0 + R[1,1]*X1 + center[1] + 2.0*previousBeta[2])
        moving=ndimage.map_coordinates(moving, [X0new, X1new], prefilter=const_prefilter_map_coordinates)
        mask[...]=(X0new<0) + (X0new>(sh[0]-1))
        mask[...]=mask + (X1new<0) + (X1new>(sh[1]-1))
        mask[...]=1-mask
    means, variances=tf.computeMaskedVolumeClassStatsProbsCYTHON(mask, moving, probs)
    means=np.array(means)
    weights=np.array([1.0/x if(x>0) else 0 for x in variances], dtype=np.float64)
    g0, g1=sp.gradient(moving)
    q=np.empty(shape=(X0.shape)+(3,), dtype=np.float64)
    q[...,0]=g1*X0-g0*X1
    q[...,1]=g0
    q[...,2]=g1
    expected=probs.dot(means)
    diff=expected-moving
    Aw, bw=tf.integrateMaskedWeightedTensorFieldProductsCYTHON(mask, q, diff, numLevels, rightQ, weights)
    beta=linalg.solve(Aw,bw)
    return beta
Ejemplo n.º 9
0
def estimateNewMultimodalRigidTransformation3D(left, right, rightQ, numLevels, previousBeta=None):
    epsilon=1e-9
    sh=left.shape
    center=(np.array(sh)-1)/2.0
    X0,X1,X2=np.mgrid[0:sh[0], 0:sh[1], 0:sh[2]]
    X0=X0-center[0]
    X1=X1-center[1]
    X2=X2-center[2]
    mask=np.ones_like(X0, dtype=np.int32)
    if((previousBeta!=None) and (np.max(np.abs(previousBeta))>epsilon)):
        R=rcommon.getRotationMatrix(previousBeta[0:3])
        X0new,X1new,X2new=(R[0,0]*X0 + R[0,1]*X1 + R[0,2]*X2 + center[0] + 2.0*previousBeta[3], 
                        R[1,0]*X0 + R[1,1]*X1 + R[1,2]*X2 + center[1] + 2.0*previousBeta[4], 
                        R[2,0]*X0 + R[2,1]*X1 + R[2,2]*X2 + center[2] + 2.0*previousBeta[5])
        left=ndimage.map_coordinates(left, [X0new, X1new, X2new], prefilter=const_prefilter_map_coordinates)
        mask[...]=(X0new<0) + (X0new>(sh[0]-1))
        mask[...]=mask + (X1new<0) + (X1new>(sh[1]-1))
        mask[...]=mask + (X2new<0) + (X2new>(sh[2]-1))
        mask[...]=1-mask
    means, variances=tf.computeMaskedVolumeClassStatsCYTHON(mask, left, numLevels, rightQ)
    means=np.array(means)
    weights=np.array([1.0/x if(x>0) else 0 for x in variances], dtype=np.float64)
    g0, g1, g2=sp.gradient(left)
    q=np.empty(shape=(X0.shape)+(6,), dtype=np.float64)
    q[...,0]=g2*X1-g1*X2
    q[...,1]=g0*X2-g2*X0
    q[...,2]=g1*X0-g0*X1
    q[...,3]=g0
    q[...,4]=g1
    q[...,5]=g2
    diff=means[rightQ]-left
    Aw, bw=tf.integrateMaskedWeightedTensorFieldProductsCYTHON(mask, q, diff, numLevels, rightQ, weights)
    beta=linalg.solve(Aw,bw)
    return beta
Ejemplo n.º 10
0
    def compute_desired_velocity(self):
        """
        To compute the geodesic distance to the doors in using \
        a fast-marching method. The opposite of the gradient of this distance
        corresponds to the desired velocity which permits to reach the closest
        door

        Returns
        -------

        door_distance : numpy array
            distance to the closest door
        desired_velocity_X : numpy array
            opposite of the gradient of the door distance, x component
        desired_velocity_Y : numpy array
            opposite of the gradient of the door distance, y component
        """
        mask_red = (self.image_red == 255) \
                  *(self.image_green == 0) \
                  *(self.image_blue == 0)
        ind_red = sp.where(mask_red)
        phi = sp.ones(self.image_red.shape)
        phi[ind_red] = 0
        phi = sp.ma.MaskedArray(phi, mask=self.mask)
        self.door_distance = skfmm.distance(phi, dx=self.pixel_size)
        tmp_dist = self.door_distance.filled(9999)
        grad = sp.gradient(tmp_dist, edge_order=2)
        grad_X = -grad[1] / self.pixel_size
        grad_Y = -grad[0] / self.pixel_size
        norm = sp.sqrt(grad_X**2 + grad_Y**2)
        norm = (norm > 0) * norm + (norm == 0) * 0.001
        self.desired_velocity_X = grad_X / norm
        self.desired_velocity_Y = grad_Y / norm
        return self.door_distance, self.desired_velocity_X, self.desired_velocity_Y
Ejemplo n.º 11
0
def estimateNewRigidTransformation3D(left, right, previousBeta=None):
    epsilon=1e-9
    sh=left.shape
    center=(np.array(sh)-1)/2.0
    X0,X1,X2=np.mgrid[0:sh[0], 0:sh[1], 0:sh[2]]
    X0=X0-center[0]
    X1=X1-center[1]
    X2=X2-center[2]
    if((previousBeta!=None) and (np.max(np.abs(previousBeta))>epsilon)):
        R=rcommon.getRotationMatrix(previousBeta[0:3])
        X0new,X1new,X2new=(R[0,0]*X0 + R[0,1]*X1 + R[0,2]*X2 + center[0] + 2.0*previousBeta[3], 
                        R[1,0]*X0 + R[1,1]*X1 + R[1,2]*X2 + center[1] + 2.0*previousBeta[4], 
                        R[2,0]*X0 + R[2,1]*X1 + R[2,2]*X2 + center[2] + 2.0*previousBeta[5])
        left=ndimage.map_coordinates(left, [X0new, X1new, X2new], prefilter=const_prefilter_map_coordinates)
    g0, g1, g2=sp.gradient(left)
    q=np.empty(shape=(X0.shape)+(6,), dtype=np.float64)
    q[...,0]=g2*X1-g1*X2
    q[...,1]=g0*X2-g2*X0
    q[...,2]=g1*X0-g0*X1
    q[...,3]=g0
    q[...,4]=g1
    q[...,5]=g2
    diff=right-left
    A,b=tf.integrateTensorFieldProductsCYTHON(q,diff)
    #A,b=tf.integrateTensorFieldProducts(q,diff)
    beta=linalg.solve(A,b)
    return beta
Ejemplo n.º 12
0
def estimateNewRotation(left,
                        right,
                        previousAngleRadians,
                        maxAngleRads=0,
                        thr=-1):
    epsilon = 1e-9
    center = (np.array(right.shape) - 1) / 2.0
    C, R = sp.meshgrid(np.array(range(right.shape[1]), dtype=np.float64),
                       np.array(range(right.shape[0]), dtype=np.float64))
    R = R - center[0]
    C = C - center[1]
    if (np.abs(previousAngleRadians) > epsilon):
        a = np.cos(previousAngleRadians)
        b = np.sin(previousAngleRadians)
        Rnew, Cnew = (a * R - b * C + center[0], b * R + a * C + center[1])
        right = ndimage.map_coordinates(
            right, [Rnew, Cnew], prefilter=const_prefilter_map_coordinates)
    [dr, dc] = sp.gradient(right)
    prod = R * dc - C * dr
    diff = left - right
    num = prod * diff
    den = prod**2
    theta = 0
    if (thr > 0):
        N = np.sqrt((R * maxAngleRads)**2 + (C * maxAngleRads)**2)
        M = (N < thr)
        theta = np.sum(num * M) / np.sum(den * M)
    else:
        theta = np.sum(num) / np.sum(den)
    return theta
Ejemplo n.º 13
0
def estimateNewRigidTransformation3D(left, right, previousBeta=None):
    epsilon = 1e-9
    sh = left.shape
    center = (np.array(sh) - 1) / 2.0
    X0, X1, X2 = np.mgrid[0:sh[0], 0:sh[1], 0:sh[2]]
    X0 = X0 - center[0]
    X1 = X1 - center[1]
    X2 = X2 - center[2]
    if ((previousBeta != None) and (np.max(np.abs(previousBeta)) > epsilon)):
        R = rcommon.getRotationMatrix(previousBeta[0:3])
        X0new, X1new, X2new = (R[0, 0] * X0 + R[0, 1] * X1 + R[0, 2] * X2 +
                               center[0] + 2.0 * previousBeta[3],
                               R[1, 0] * X0 + R[1, 1] * X1 + R[1, 2] * X2 +
                               center[1] + 2.0 * previousBeta[4],
                               R[2, 0] * X0 + R[2, 1] * X1 + R[2, 2] * X2 +
                               center[2] + 2.0 * previousBeta[5])
        left = ndimage.map_coordinates(
            left, [X0new, X1new, X2new],
            prefilter=const_prefilter_map_coordinates)
    g0, g1, g2 = sp.gradient(left)
    q = np.empty(shape=(X0.shape) + (6, ), dtype=np.float64)
    q[..., 0] = g2 * X1 - g1 * X2
    q[..., 1] = g0 * X2 - g2 * X0
    q[..., 2] = g1 * X0 - g0 * X1
    q[..., 3] = g0
    q[..., 4] = g1
    q[..., 5] = g2
    diff = right - left
    A, b = tf.integrateTensorFieldProductsCYTHON(q, diff)
    #A,b=tf.integrateTensorFieldProducts(q,diff)
    beta = linalg.solve(A, b)
    return beta
Ejemplo n.º 14
0
    def augmentTrans(self, df, deg):
        ''' joins calculated and fitted transconductances to existing dataframe
        '''
        xs = sp.array(df.filter(like='Vgs'))
        ys = df.filter(like='Ids')
        grad_cols = [i.replace('Ids', 'tcd') for i in ys.columns]
        fit_cols = [i.replace('Ids', 'tcfit') for i in ys.columns]

        grads = []
        fits = []
        for x, y in zip(sp.array(xs).T, sp.array(ys).T):
            g = sp.gradient(y, x)
            grads.append(g)

            p = sp.polyfit(x, g, deg)
            fit = sp.poly1d(p)(x)
            fits.append(fit)

        graddf = pd.DataFrame(sp.array(grads).T, columns=grad_cols)
        fitdf = pd.DataFrame(sp.array(fits).T, columns=fit_cols)

        df = df.join(graddf)
        df = df.join(fitdf)

        return df
Ejemplo n.º 15
0
def harris(I):
    """ Harris Corner Detector """
    Ix,Iy = scipy.gradient(I)
    H11 = Ix*Ix
    H12 = Ix*Iy
    H22 = Iy*Iy
    return (H11*H22 - H12**2) 
Ejemplo n.º 16
0
def skeletize_latecki(img,gaussian_filter):
    # http://www.cis.temple.edu/~latecki/Papers/icip__SSM07.pdf
    dt=numpy.float32
    if (img.ndim==3):
      img=img.mean(axis=2)
    img=img.astype(dt)
    img/=img.max()      
    gimg=scipy.ndimage.gaussian_filter(img,2)
    ximg=img.max()-img
    dimg=scipy.ndimage.distance_transform_edt(ximg)
    #
    # now let's compute f
    fimg=1-scipy.abs(scipy.convolve(cgradient(gimg),dimg))
    #
    # and now compute its gradient
    u0,v0=scipy.gradient(fimg)
    #
    # now we do diffusion

    
    ##
    # now we apply SSM map
    gvf=diffuse_gradient_vector
    
    #
    # then we do particular point detection
    mimg1=scipy.ndimage.maximum_filter(dimg,size=(3,3))
    img=(((dimg-mimg1)==0).astype(dt))
    img*=ximg
    return img
Ejemplo n.º 17
0
 def initialize_iteration(self):
     r'''
     Precomputes the gradient of the input images to be used in the
     computation of the forward and backward steps.
     '''
     self.gradient_moving = np.empty(
         shape = (self.moving_image.shape)+(self.dim,), dtype = np.float64)
     i = 0
     for grad in gradient(self.moving_image):
         self.gradient_moving[..., i] = grad
         i += 1
     i = 0
     self.gradient_fixed = np.empty(
         shape = (self.fixed_image.shape)+(self.dim,), dtype = np.float64)
     for grad in gradient(self.fixed_image):
         self.gradient_fixed[..., i] = grad
         i += 1
Ejemplo n.º 18
0
def getJacobian(x, y, f, g, x0, y0):
    """J = getJacobian(x,y,f,g,x0,y0)
    getJacobian takes a grid of derivative values and a point in phase
    space, and returns the Jacobian around that point.

    Parameters:
      x   : The x-values of f and g.
      y   : The y-values of f and g.
      f   : A matrix approximating the derivative wrt x.
      g   : A matrix approximating the derivative wrt y.
      x0  : The x-value for the point.
      y0  : The y-value for the point.

    Returns Jacobian:
    J(1,1): Derivative of f wrt x evaluated at x0, y0.
    J(1,2): Derivative of f wrt y evaluated at x0, y0.
    J(2,1): Derivative of g wrt x evaluated at x0, y0.
    J(2,2): Derivative of g wrt y evaluated at x0, y0.
    """
    dx = sp.gradient(x)[1]  # the derivative in the X direction
    dy = sp.gradient(y)[0]  # the derivative in the Y direction
    dfy, dfx = sp.gradient(f)  # the derivatives of f in the X and Y directions
    dgy, dgx = sp.gradient(g)  # the derivatives of g in the X and Y directions

    # Now we need to get the values at the fixed point. We have to interpolate
    # the data from what we have.
    points = (x.flatten(), y.flatten())
    point = (x0, y0)
    dx0 = griddata(points, dx.flatten(), point)
    dy0 = griddata(points, dy.flatten(), point)
    dfdx0 = griddata(points, dfx.flatten(), point)
    dfdy0 = griddata(points, dfy.flatten(), point)
    dgdx0 = griddata(points, dgx.flatten(), point)
    dgdy0 = griddata(points, dgy.flatten(), point)

    #X, Y = x.flatten(), y.flatten()
    #xi,yi = plt.meshgrid([x0-1, x0, x0+1], [y0-1, y0, y0+1])
    #dx0   = griddata(X, Y, dx.flatten(), xi,yi)[1][1]
    #dy0   = griddata(X, Y, dy.flatten(), xi,yi)[1][1]
    #dfdx0 = griddata(X, Y, dfx.flatten(),xi,yi)[1][1]
    #dfdy0 = griddata(X, Y, dfy.flatten(),xi,yi)[1][1]
    #dgdx0 = griddata(X, Y, dgx.flatten(),xi,yi)[1][1]
    #dgdy0 = griddata(X, Y, dgy.flatten(),xi,yi)[1][1]

    return sp.array([[dfdx0 / dx0, dfdy0 / dy0], [dgdx0 / dx0, dgdy0 / dy0]])
Ejemplo n.º 19
0
def getJacobian(x,y,f,g,x0,y0):
    """J = getJacobian(x,y,f,g,x0,y0)
    getJacobian takes a grid of derivative values and a point in phase
    space, and returns the Jacobian around that point.

    Parameters:
      x   : The x-values of f and g.
      y   : The y-values of f and g.
      f   : A matrix approximating the derivative wrt x.
      g   : A matrix approximating the derivative wrt y.
      x0  : The x-value for the point.
      y0  : The y-value for the point.

    Returns Jacobian:
    J(1,1): Derivative of f wrt x evaluated at x0, y0.
    J(1,2): Derivative of f wrt y evaluated at x0, y0.
    J(2,1): Derivative of g wrt x evaluated at x0, y0.
    J(2,2): Derivative of g wrt y evaluated at x0, y0.
    """
    dx = sp.gradient(x)[1] # the derivative in the X direction
    dy = sp.gradient(y)[0] # the derivative in the Y direction
    dfy, dfx = sp.gradient(f) # the derivatives of f in the X and Y directions
    dgy, dgx = sp.gradient(g) # the derivatives of g in the X and Y directions

    # Now we need to get the values at the fixed point. We have to interpolate
    # the data from what we have.
    points = (x.flatten(), y.flatten())
    point = (x0, y0)
    dx0   = griddata(points, dx.flatten(),  point)
    dy0   = griddata(points, dy.flatten(),  point)
    dfdx0 = griddata(points, dfx.flatten(), point)
    dfdy0 = griddata(points, dfy.flatten(), point)
    dgdx0 = griddata(points, dgx.flatten(), point)
    dgdy0 = griddata(points, dgy.flatten(), point)

    #X, Y = x.flatten(), y.flatten()
    #xi,yi = plt.meshgrid([x0-1, x0, x0+1], [y0-1, y0, y0+1])
    #dx0   = griddata(X, Y, dx.flatten(), xi,yi)[1][1]
    #dy0   = griddata(X, Y, dy.flatten(), xi,yi)[1][1]
    #dfdx0 = griddata(X, Y, dfx.flatten(),xi,yi)[1][1]
    #dfdy0 = griddata(X, Y, dfy.flatten(),xi,yi)[1][1]
    #dgdx0 = griddata(X, Y, dgx.flatten(),xi,yi)[1][1]
    #dgdy0 = griddata(X, Y, dgy.flatten(),xi,yi)[1][1]

    return sp.array([[dfdx0/dx0, dfdy0/dy0], [dgdx0/dx0, dgdy0/dy0]])
Ejemplo n.º 20
0
def estimateNewMonomodalDiffeomorphicField2D(moving, fixed, lambdaParam,
                                             maxOuterIter,
                                             previousDisplacement,
                                             previousDisplacementInverse):
    '''
    Warning: in the monomodal case, the parameter lambda must be significantly lower than in the multimodal case. Try lambdaParam=1,
    as opposed as lambdaParam=150 used in the multimodal case
    '''
    innerTolerance = 1e-4
    displacement = np.zeros(shape=(moving.shape) + (2, ), dtype=np.float64)
    gradientField = np.empty(shape=(moving.shape) + (2, ), dtype=np.float64)
    totalDisplacement = np.zeros(shape=(moving.shape) + (2, ),
                                 dtype=np.float64)
    totalDisplacementInverse = np.zeros(shape=(moving.shape) + (2, ),
                                        dtype=np.float64)
    if (previousDisplacement != None):
        totalDisplacement[...] = previousDisplacement
        totalDisplacementInverse[...] = previousDisplacementInverse
    outerIter = 0
    framesToCapture = 5
    maxOuterIter = framesToCapture * (
        (maxOuterIter + framesToCapture - 1) / framesToCapture)
    itersPerCapture = maxOuterIter / framesToCapture
    plt.figure()
    while (outerIter < maxOuterIter):
        outerIter += 1
        print 'Outer iter:', outerIter
        warped = np.array(tf.warp_image(moving, totalDisplacement, None))
        if ((outerIter == 1) or (outerIter % itersPerCapture == 0)):
            plt.subplot(1, framesToCapture + 1,
                        1 + outerIter / itersPerCapture)
            rcommon.overlayImages(warped, fixed, False)
            plt.title('Iter:' + str(outerIter - 1))
        sigmaField = np.ones_like(warped, dtype=np.float64)
        deltaField = fixed - warped
        gradientField[:, :, 0], gradientField[:, :, 1] = sp.gradient(warped)
        maxVariation = 1 + innerTolerance
        innerIter = 0
        displacement[...] = 0
        maxInnerIter = 200
        while ((maxVariation > innerTolerance) and (innerIter < maxInnerIter)):
            innerIter += 1
            maxVariation = tf.iterateDisplacementField2DCYTHON(
                deltaField, sigmaField, gradientField, lambdaParam,
                displacement, None)
        #maxDisplacement=np.max(np.abs(displacement))
        expd, invexpd = tf.vector_field_exponential(displacement, True)
        totalDisplacement, stats = tf.compose_vector_fields(
            displacement, totalDisplacement)
        #totalDisplacement=np.array(totalDisplacement)
        totalDisplacementInverse, stats = tf.compose_vector_fields(
            totalDisplacementInverse, invexpd)
        #totalDisplacementInverse=np.array(totalDisplacementInverse)
        #if(maxDisplacement<outerTolerance):
        #break
    print "Iter: ", innerIter, "Max variation:", maxVariation
    return totalDisplacement, totalDisplacementInverse
Ejemplo n.º 21
0
def harris_smooth(I,alpha=0.04,si=1):
    """ Harris Corner Detector """
    def imsmooth(I,si):
        return scipy.ndimage.gaussian_filter(I,si)
    Ix,Iy = scipy.gradient(I)
    H11 = imsmooth(Ix*Ix, si)
    H12 = imsmooth(Ix*Iy, si)
    H22 = imsmooth(Iy*Iy, si)
    return (H11*H22 - H12**2) - alpha*(H11+H22)**2
Ejemplo n.º 22
0
def harris_noble(I,si):
  """ Noble's variation of Harris Corner Detector """
  eps=1e-16
  def imsmooth(I,si):
    return scipy.ndimage.gaussian_filter(I,si)
  Ix,Iy = scipy.gradient(I) 
  H11 = imsmooth(Ix*Ix, si) 
  H12 = imsmooth(Ix*Iy, si) 
  H22 = imsmooth(Iy*Iy, si) 
  return 2 *  (H11*H22 - H12**2)/(H11+H22+eps) 
Ejemplo n.º 23
0
 def initialize_iteration(self):
     r'''
     Precomputes the gradient of the input images to be used in the
     computation of the forward and backward steps.
     '''
     self.gradient_moving = np.empty(shape=(self.moving_image.shape) +
                                     (self.dim, ),
                                     dtype=np.float64)
     i = 0
     for grad in gradient(self.moving_image):
         self.gradient_moving[..., i] = grad
         i += 1
     i = 0
     self.gradient_fixed = np.empty(shape=(self.fixed_image.shape) +
                                    (self.dim, ),
                                    dtype=np.float64)
     for grad in gradient(self.fixed_image):
         self.gradient_fixed[..., i] = grad
         i += 1
Ejemplo n.º 24
0
 def initialize_iteration(self):
     r'''
     Precomputes the cross-correlation factors
     '''
     self.factors = tf.precompute_cc_factors_3d(self.fixed_image,
                                                self.moving_image,
                                                self.radius)
     self.factors = np.array(self.factors)
     self.gradient_moving = np.empty(
         shape = (self.moving_image.shape)+(self.dim,), dtype = np.float64)
     i = 0
     for grad in sp.gradient(self.moving_image):
         self.gradient_moving[..., i] = grad
         i += 1
     self.gradient_fixed = np.empty(
         shape = (self.fixed_image.shape)+(self.dim,), dtype = np.float64)
     i = 0
     for grad in sp.gradient(self.fixed_image):
         self.gradient_fixed[..., i] = grad
         i += 1
Ejemplo n.º 25
0
def estimateNewMonomodalDiffeomorphicField3D(moving,
                                             fixed,
                                             lambdaParam,
                                             maxOuterIter,
                                             previousDisplacement,
                                             reportProgress=False):
    '''
    Warning: in the monomodal case, the parameter lambda must be significantly lower than in the multimodal case. Try lambdaParam=1,
    as opposed as lambdaParam=150 used in the multimodal case
    '''
    innerTolerance = 1e-3
    outerTolerance = 1e-3
    displacement = np.zeros(shape=(moving.shape) + (3, ), dtype=np.float64)
    residuals = np.zeros(shape=(moving.shape), dtype=np.float64)
    gradientField = np.empty(shape=(moving.shape) + (3, ), dtype=np.float64)
    totalDisplacement = np.zeros(shape=(moving.shape) + (3, ),
                                 dtype=np.float64)
    if (previousDisplacement != None):
        totalDisplacement[...] = previousDisplacement
    outerIter = 0
    while (outerIter < maxOuterIter):
        outerIter += 1
        if (reportProgress):
            print 'Iter:', outerIter, '/', maxOuterIter
        warped = np.array(tf.warp_volume(moving, totalDisplacement))
        sigmaField = np.ones_like(warped, dtype=np.float64)
        deltaField = fixed - warped
        g0, g1, g2 = sp.gradient(warped)
        gradientField[:, :, :, 0] = g0
        gradientField[:, :, :, 1] = g1
        gradientField[:, :, :, 2] = g2
        maxVariation = 1 + innerTolerance
        innerIter = 0
        maxResidual = 0
        displacement[...] = 0
        maxInnerIter = 50
        while ((maxVariation > innerTolerance) and (innerIter < maxInnerIter)):
            innerIter += 1
            maxVariation = tf.iterateDisplacementField3DCYTHON(
                deltaField, sigmaField, gradientField, lambdaParam,
                totalDisplacement, displacement, residuals)
            opt = np.max(residuals)
            if (maxResidual < opt):
                maxResidual = opt
        maxDisplacement = np.max(np.abs(displacement))
        totalDisplacement, stats = tf.compose_vector_fields3D(
            displacement, totalDisplacement)
        if (maxDisplacement < outerTolerance):
            break
    print "Iter: ", outerIter, "Max lateral displacement:", maxDisplacement, "Max variation:", maxVariation, "Max residual:", maxResidual
    if (previousDisplacement != None):
        return totalDisplacement - previousDisplacement
    return totalDisplacement
Ejemplo n.º 26
0
def plotDiffeomorphism(GT, GTinv, GTres, titlePrefix, delta=10):
    nrows=GT.shape[0]
    ncols=GT.shape[1]
    X1,X0=np.mgrid[0:GT.shape[0], 0:GT.shape[1]]
    lattice=drawLattice2D((nrows+delta)/(delta+1), (ncols+delta)/(delta+1), delta)
    lattice=lattice[0:nrows,0:ncols]
    gtLattice=warpImage(lattice, np.array(GT))
    gtInvLattice=warpImage(lattice, np.array(GTinv))
    gtResidual=warpImage(lattice, np.array(GTres))
    plt.figure()
    plt.subplot(2, 3, 1)
    plt.imshow(gtLattice, cmap=plt.cm.gray)
    plt.title(titlePrefix+'[Deformation]')
    plt.subplot(2, 3, 2)
    plt.imshow(gtInvLattice, cmap=plt.cm.gray)
    plt.title(titlePrefix+'[Inverse]')
    plt.subplot(2, 3, 3)
    plt.imshow(gtResidual, cmap=plt.cm.gray)
    plt.title(titlePrefix+'[residual]')
    #plot jacobians and residual norm
    detJacobian=computeJacobianField(GT)
    plt.subplot(2, 3, 4)
    plt.imshow(detJacobian, cmap=plt.cm.gray)
    CS=plt.contour(X0,X1,detJacobian,levels=[0.0], colors='r')
    plt.clabel(CS, inline=1, fontsize=10)
    plt.title('det(J(d))')    
    detJacobianInverse=computeJacobianField(GTinv)
    plt.subplot(2, 3, 5)
    plt.imshow(detJacobianInverse, cmap=plt.cm.gray)
    CS=plt.contour(X0,X1,detJacobianInverse,levels=[0.0], colors='r')
    plt.clabel(CS, inline=1, fontsize=10)
    plt.title('det(J(d^-1))')    
    nrm=np.sqrt(np.sum(np.array(GTres)**2,2))
    plt.subplot(2, 3, 6)
    plt.imshow(nrm, cmap=plt.cm.gray)
    plt.title('||residual||_2')    
    g00, g01=sp.gradient(GTinv[...,0])
    g10, g11=sp.gradient(GTinv[...,1])
    #priorEnergy=g00**2+g01**2+g10**2+g11**2
    return [gtLattice, gtInvLattice, gtResidual, detJacobian]
Ejemplo n.º 27
0
 def initialize_iteration(self):
     r'''
     Precomputes the cross-correlation factors
     '''
     self.factors = tf.precompute_cc_factors_3d(self.fixed_image,
                                                self.moving_image,
                                                self.radius)
     self.factors = np.array(self.factors)
     self.gradient_moving = np.empty(shape=(self.moving_image.shape) +
                                     (self.dim, ),
                                     dtype=np.float64)
     i = 0
     for grad in sp.gradient(self.moving_image):
         self.gradient_moving[..., i] = grad
         i += 1
     self.gradient_fixed = np.empty(shape=(self.fixed_image.shape) +
                                    (self.dim, ),
                                    dtype=np.float64)
     i = 0
     for grad in sp.gradient(self.fixed_image):
         self.gradient_fixed[..., i] = grad
         i += 1
Ejemplo n.º 28
0
def gradient_M(f):
	dM = g.grid_M[1] - g.grid_M[0]
	dD = g.grid_D[1] - g.grid_D[0]
	g = scipy.gradient(f, dM, dD)	
	result = []
#	for a1 in g:
#		# add empty row, col
#		newcol = scipy.NaN * scipy.ones((1, len(g.grid_D)-1))
#		a2 = scipy.hstack([a1, newcol])
#		newrow = scipy.NaN * scipy.ones((len(g.grid_M), 1))
#		a3 = scipy.vstack([a2, newrow])
#		result.append(a3)
	return g
Ejemplo n.º 29
0
    def initialize_iteration(self):
        r"""Prepares the metric to compute one displacement field iteration.

        Pre-computes the cross-correlation factors for efficient computation
        of the gradient of the Cross Correlation w.r.t. the displacement field.
        It also pre-computes the image gradients in the physical space by
        re-orienting the gradients in the voxel space using the corresponding
        affine transformations.
        """
        self.factors = self.precompute_factors(self.static_image,
                                               self.moving_image, self.radius)
        self.factors = np.array(self.factors)

        self.gradient_moving = np.empty(shape=(self.moving_image.shape) +
                                        (self.dim, ),
                                        dtype=floating)
        for i, grad in enumerate(sp.gradient(self.moving_image)):
            self.gradient_moving[..., i] = grad

        # Convert moving image's gradient field from voxel to physical space
        if self.moving_spacing is not None:
            self.gradient_moving /= self.moving_spacing
        if self.moving_direction is not None:
            self.reorient_vector_field(self.gradient_moving,
                                       self.moving_direction)

        self.gradient_static = np.empty(shape=(self.static_image.shape) +
                                        (self.dim, ),
                                        dtype=floating)
        for i, grad in enumerate(sp.gradient(self.static_image)):
            self.gradient_static[..., i] = grad

        # Convert moving image's gradient field from voxel to physical space
        if self.static_spacing is not None:
            self.gradient_static /= self.static_spacing
        if self.static_direction is not None:
            self.reorient_vector_field(self.gradient_static,
                                       self.static_direction)
Ejemplo n.º 30
0
    def initialize_iteration(self):
        r"""Prepares the metric to compute one displacement field iteration.

        Pre-computes the cross-correlation factors for efficient computation
        of the gradient of the Cross Correlation w.r.t. the displacement field.
        It also pre-computes the image gradients in the physical space by
        re-orienting the gradients in the voxel space using the corresponding
        affine transformations.
        """
        self.factors = self.precompute_factors(self.static_image,
                                               self.moving_image,
                                               self.radius)
        self.factors = np.array(self.factors)

        self.gradient_moving = np.empty(
            shape=(self.moving_image.shape)+(self.dim,), dtype=floating)
        for i, grad in enumerate(sp.gradient(self.moving_image)):
            self.gradient_moving[..., i] = grad

        # Convert moving image's gradient field from voxel to physical space
        if self.moving_spacing is not None:
            self.gradient_moving /= self.moving_spacing
        if self.moving_direction is not None:
            self.reorient_vector_field(self.gradient_moving,
                                       self.moving_direction)

        self.gradient_static = np.empty(
            shape=(self.static_image.shape)+(self.dim,), dtype=floating)
        for i, grad in enumerate(sp.gradient(self.static_image)):
            self.gradient_static[..., i] = grad

        # Convert moving image's gradient field from voxel to physical space
        if self.static_spacing is not None:
            self.gradient_static /= self.static_spacing
        if self.static_direction is not None:
            self.reorient_vector_field(self.gradient_static,
                                       self.static_direction)
Ejemplo n.º 31
0
def estimateNewMultimodalRigidTransformation3D(left,
                                               right,
                                               rightQ,
                                               numLevels,
                                               previousBeta=None):
    epsilon = 1e-9
    sh = left.shape
    center = (np.array(sh) - 1) / 2.0
    X0, X1, X2 = np.mgrid[0:sh[0], 0:sh[1], 0:sh[2]]
    X0 = X0 - center[0]
    X1 = X1 - center[1]
    X2 = X2 - center[2]
    mask = np.ones_like(X0, dtype=np.int32)
    if ((previousBeta != None) and (np.max(np.abs(previousBeta)) > epsilon)):
        R = rcommon.getRotationMatrix(previousBeta[0:3])
        X0new, X1new, X2new = (R[0, 0] * X0 + R[0, 1] * X1 + R[0, 2] * X2 +
                               center[0] + 2.0 * previousBeta[3],
                               R[1, 0] * X0 + R[1, 1] * X1 + R[1, 2] * X2 +
                               center[1] + 2.0 * previousBeta[4],
                               R[2, 0] * X0 + R[2, 1] * X1 + R[2, 2] * X2 +
                               center[2] + 2.0 * previousBeta[5])
        left = ndimage.map_coordinates(
            left, [X0new, X1new, X2new],
            prefilter=const_prefilter_map_coordinates)
        mask[...] = (X0new < 0) + (X0new > (sh[0] - 1))
        mask[...] = mask + (X1new < 0) + (X1new > (sh[1] - 1))
        mask[...] = mask + (X2new < 0) + (X2new > (sh[2] - 1))
        mask[...] = 1 - mask
    means, variances = tf.computeMaskedVolumeClassStatsCYTHON(
        mask, left, numLevels, rightQ)
    means = np.array(means)
    weights = np.array([1.0 / x if (x > 0) else 0 for x in variances],
                       dtype=np.float64)
    g0, g1, g2 = sp.gradient(left)
    q = np.empty(shape=(X0.shape) + (6, ), dtype=np.float64)
    q[..., 0] = g2 * X1 - g1 * X2
    q[..., 1] = g0 * X2 - g2 * X0
    q[..., 2] = g1 * X0 - g0 * X1
    q[..., 3] = g0
    q[..., 4] = g1
    q[..., 5] = g2
    diff = means[rightQ] - left
    Aw, bw = tf.integrateMaskedWeightedTensorFieldProductsCYTHON(
        mask, q, diff, numLevels, rightQ, weights)
    beta = linalg.solve(Aw, bw)
    return beta
Ejemplo n.º 32
0
def estimateRigidTransformation(left, right):
    #compute the centered meshgrid
    center=(np.array(right.shape)-1)/2.0
    C,R=sp.meshgrid(np.array(range(right.shape[1]), dtype=np.float64), np.array(range(right.shape[0]), dtype=np.float64))
    R=R-center[0]
    C=C-center[1]
    #parameter estimation
    [dr, dc]=sp.gradient(right)
    epsilon=R*dc-C*dr
    c=np.array([epsilon,dr,dc]).transpose(1,2,0)
    tensorProds=c[:,:,:,None]*c[:,:,None,:]
    A=np.sum(np.sum(tensorProds, axis=0), axis=0)
    diff=left-right
    prod=c*diff[:,:,None]
    b=np.sum(np.sum(prod, axis=0), axis=0)
    beta=linalg.solve(A,b)
    return beta
def estimateNewMonomodalDiffeomorphicField2D(moving, fixed, lambdaParam, maxOuterIter, previousDisplacement, previousDisplacementInverse):
    '''
    Warning: in the monomodal case, the parameter lambda must be significantly lower than in the multimodal case. Try lambdaParam=1,
    as opposed as lambdaParam=150 used in the multimodal case
    '''
    innerTolerance=1e-4
    displacement     =np.zeros(shape=(moving.shape)+(2,), dtype=np.float64)
    gradientField    =np.empty(shape=(moving.shape)+(2,), dtype=np.float64)
    totalDisplacement=np.zeros(shape=(moving.shape)+(2,), dtype=np.float64)
    totalDisplacementInverse=np.zeros(shape=(moving.shape)+(2,), dtype=np.float64)
    if(previousDisplacement!=None):
        totalDisplacement[...]=previousDisplacement
        totalDisplacementInverse[...]=previousDisplacementInverse
    outerIter=0
    framesToCapture=5
    maxOuterIter=framesToCapture*((maxOuterIter+framesToCapture-1)/framesToCapture)
    itersPerCapture=maxOuterIter/framesToCapture
    plt.figure()
    while(outerIter<maxOuterIter):
        outerIter+=1
        print 'Outer iter:', outerIter
        warped=np.array(tf.warp_image(moving, totalDisplacement, None))
        if((outerIter==1) or (outerIter%itersPerCapture==0)):
            plt.subplot(1,framesToCapture+1, 1+outerIter/itersPerCapture)
            rcommon.overlayImages(warped, fixed, False)
            plt.title('Iter:'+str(outerIter-1))
        sigmaField=np.ones_like(warped, dtype=np.float64)
        deltaField=fixed-warped
        gradientField[:,:,0], gradientField[:,:,1]=sp.gradient(warped)
        maxVariation=1+innerTolerance
        innerIter=0
        displacement[...]=0
        maxInnerIter=200
        while((maxVariation>innerTolerance)and(innerIter<maxInnerIter)):
            innerIter+=1
            maxVariation=tf.iterateDisplacementField2DCYTHON(deltaField, sigmaField, gradientField,  lambdaParam, displacement, None)
        #maxDisplacement=np.max(np.abs(displacement))
        expd, invexpd=tf.vector_field_exponential(displacement, True)
        totalDisplacement, stats=tf.compose_vector_fields(displacement, totalDisplacement)
        #totalDisplacement=np.array(totalDisplacement)
        totalDisplacementInverse, stats=tf.compose_vector_fields(totalDisplacementInverse, invexpd)
        #totalDisplacementInverse=np.array(totalDisplacementInverse)
        #if(maxDisplacement<outerTolerance):
            #break
    print "Iter: ",innerIter, "Max variation:",maxVariation
    return totalDisplacement, totalDisplacementInverse
Ejemplo n.º 34
0
def estimateRotationOnly(left, right, maxAngleRads=0, thr=-1):
    center=(np.array(right.shape)-1)/2.0
    C,R=sp.meshgrid(np.array(range(right.shape[1]), dtype=np.float64), np.array(range(right.shape[0]), dtype=np.float64))
    R=R-center[0]
    C=C-center[1]
    [dr, dc]=sp.gradient(right)
    prod=R*dc-C*dr
    diff=left-right
    num=prod*diff
    den=prod**2
    if(thr>0):
        N=np.sqrt((R*maxAngleRads)**2+(C*maxAngleRads)**2)
        M=(N<thr)
        theta=np.sum(num*M)/np.sum(den*M)
    else:
        theta=np.sum(num)/np.sum(den)
    return theta
Ejemplo n.º 35
0
 def compute_wall_distance(self):
     """
     To compute the geodesic distance to the walls in using \
     a fast-marching method
     """
     phi = sp.ones(self.image_red.shape)
     if (len(self.mask_id[0]) > 0):
         phi[self.mask_id] = 0
         self.wall_distance = skfmm.distance(phi, dx=self.pixel_size)
         grad = sp.gradient(self.wall_distance, edge_order=2)
         grad_X = grad[1] / self.pixel_size
         grad_Y = grad[0] / self.pixel_size
         norm = sp.sqrt(grad_X**2 + grad_Y**2)
         norm = (norm > 0) * norm + (norm == 0) * 0.001
         self.wall_grad_X = grad_X / norm
         self.wall_grad_Y = grad_Y / norm
     else:
         self.wall_distance = 1.0e99 * sp.ones(self.image_red.shape)
Ejemplo n.º 36
0
def estimateRigidTransformation(left, right):
    #compute the centered meshgrid
    center = (np.array(right.shape) - 1) / 2.0
    C, R = sp.meshgrid(np.array(range(right.shape[1]), dtype=np.float64),
                       np.array(range(right.shape[0]), dtype=np.float64))
    R = R - center[0]
    C = C - center[1]
    #parameter estimation
    [dr, dc] = sp.gradient(right)
    epsilon = R * dc - C * dr
    c = np.array([epsilon, dr, dc]).transpose(1, 2, 0)
    tensorProds = c[:, :, :, None] * c[:, :, None, :]
    A = np.sum(np.sum(tensorProds, axis=0), axis=0)
    diff = left - right
    prod = c * diff[:, :, None]
    b = np.sum(np.sum(prod, axis=0), axis=0)
    beta = linalg.solve(A, b)
    return beta
Ejemplo n.º 37
0
def estimateRotationOnly(left, right, maxAngleRads=0, thr=-1):
    center = (np.array(right.shape) - 1) / 2.0
    C, R = sp.meshgrid(np.array(range(right.shape[1]), dtype=np.float64),
                       np.array(range(right.shape[0]), dtype=np.float64))
    R = R - center[0]
    C = C - center[1]
    [dr, dc] = sp.gradient(right)
    prod = R * dc - C * dr
    diff = left - right
    num = prod * diff
    den = prod**2
    if (thr > 0):
        N = np.sqrt((R * maxAngleRads)**2 + (C * maxAngleRads)**2)
        M = (N < thr)
        theta = np.sum(num * M) / np.sum(den * M)
    else:
        theta = np.sum(num) / np.sum(den)
    return theta
def estimateNewMonomodalDiffeomorphicField3D(moving, fixed, lambdaParam, maxOuterIter, previousDisplacement, reportProgress=False):
    '''
    Warning: in the monomodal case, the parameter lambda must be significantly lower than in the multimodal case. Try lambdaParam=1,
    as opposed as lambdaParam=150 used in the multimodal case
    '''
    innerTolerance=1e-3
    outerTolerance=1e-3
    displacement     =np.zeros(shape=(moving.shape)+(3,), dtype=np.float64)
    residuals=np.zeros(shape=(moving.shape), dtype=np.float64)
    gradientField    =np.empty(shape=(moving.shape)+(3,), dtype=np.float64)
    totalDisplacement=np.zeros(shape=(moving.shape)+(3,), dtype=np.float64)
    if(previousDisplacement!=None):
        totalDisplacement[...]=previousDisplacement
    outerIter=0
    while(outerIter<maxOuterIter):
        outerIter+=1
        if(reportProgress):
            print 'Iter:',outerIter,'/',maxOuterIter
        warped=np.array(tf.warp_volume(moving, totalDisplacement))
        sigmaField=np.ones_like(warped, dtype=np.float64)
        deltaField=fixed-warped
        g0, g1, g2=sp.gradient(warped)
        gradientField[:,:,:,0]=g0
        gradientField[:,:,:,1]=g1
        gradientField[:,:,:,2]=g2
        maxVariation=1+innerTolerance
        innerIter=0
        maxResidual=0
        displacement[...]=0
        maxInnerIter=50
        while((maxVariation>innerTolerance)and(innerIter<maxInnerIter)):
            innerIter+=1
            maxVariation=tf.iterateDisplacementField3DCYTHON(deltaField, sigmaField, gradientField,  lambdaParam, totalDisplacement, displacement, residuals)
            opt=np.max(residuals)
            if(maxResidual<opt):
                maxResidual=opt
        maxDisplacement=np.max(np.abs(displacement))
        totalDisplacement, stats=tf.compose_vector_fields3D(displacement, totalDisplacement)
        if(maxDisplacement<outerTolerance):
            break
    print "Iter: ",outerIter, "Max lateral displacement:", maxDisplacement, "Max variation:",maxVariation, "Max residual:", maxResidual
    if(previousDisplacement!=None):
        return totalDisplacement-previousDisplacement
    return totalDisplacement
Ejemplo n.º 39
0
def outlier_removed_fit(m, w=None, n_iter=10, polyord=7):
    """
    Remove outliers using fited data.

    Args:
        m (:obj:`numpy array`): Phase curve.
        n_iter (:obj:'int'): Number of iteration outlier removal
        polyorder (:obj:'int'): Order of polynomial used.

    Returns:
        fit (:obj:'numpy array'): Curve with outliers removed
    """
    if w is None:
        w = sp.ones_like(m)
    W = sp.diag(sp.sqrt(w))
    m2 = sp.copy(m)
    tv = sp.linspace(-1, 1, num=len(m))
    A = sp.zeros([len(m), polyord])
    for j in range(polyord):
        A[:, j] = tv**(float(j))
    A2 = sp.dot(W, A)
    m2w = sp.dot(m2, W)
    fit = None
    for i in range(n_iter):
        xhat = sp.linalg.lstsq(A2, m2w)[0]
        fit = sp.dot(A, xhat)
        # use gradient for central finite differences which keeps order
        resid = sp.gradient(fit - m2)
        std = sp.std(resid)
        bidx = sp.where(sp.absolute(resid) > 2.0 * std)[0]
        for bi in bidx:
            A2[bi, :] = 0.0
            m2[bi] = 0.0
            m2w[bi] = 0.0
    if debug_plot:
        plt.plot(m2, label="outlier removed")
        plt.plot(m, label="original")
        plt.plot(fit, label="fit")
        plt.legend()
        plt.ylim([sp.minimum(fit) - std * 3.0, sp.maximum(fit) + std * 3.0])
        plt.show()
    return (fit)
Ejemplo n.º 40
0
def estimateNewRigidTransformation(left, right, previousBeta=None):
    epsilon=1e-9
    center=(np.array(right.shape)-1)/2.0
    C,R=sp.meshgrid(np.array(range(right.shape[1]), dtype=np.float64), np.array(range(right.shape[0]), dtype=np.float64))
    R=R-center[0]
    C=C-center[1]    
    if((previousBeta!=None) and (np.max(np.abs(previousBeta))>epsilon)):
        a=np.cos(previousBeta[0])
        b=np.sin(previousBeta[0])
        Rnew,Cnew=(a*R-b*C+2.0*previousBeta[1]+center[0], b*R+a*C+2.0*previousBeta[2]+center[1])
        right=ndimage.map_coordinates(right, [Rnew,Cnew], prefilter=const_prefilter_map_coordinates)
    [dr, dc]=sp.gradient(right)
    epsilon=R*dc-C*dr
    c=np.array([epsilon,dr,dc]).transpose(1,2,0)
    tensorProds=c[:,:,:,None]*c[:,:,None,:]
    A=np.sum(np.sum(tensorProds, axis=0), axis=0)
    diff=left-right
    prod=c*diff[:,:,None]
    b=np.sum(np.sum(prod, axis=0), axis=0)
    beta=linalg.solve(A,b)
    return beta
Ejemplo n.º 41
0
def estimateNewMultimodalRigidTransformation2D_ecqmmf(moving,
                                                      fixed,
                                                      probs,
                                                      nclasses,
                                                      previousBeta=None):
    epsilon = 1e-9
    sh = moving.shape
    center = (np.array(sh) - 1) / 2.0
    X0, X1 = np.mgrid[0:sh[0], 0:sh[1]]
    X0 = X0 - center[0]
    X1 = X1 - center[1]
    mask = np.ones_like(X0, dtype=np.int32)
    if ((previousBeta != None) and (np.max(np.abs(previousBeta)) > epsilon)):
        R = rcommon.getRotationMatrix2D(previousBeta[0])
        X0new, X1new = (R[0, 0] * X0 + R[0, 1] * X1 + center[0] +
                        2.0 * previousBeta[1], R[1, 0] * X0 + R[1, 1] * X1 +
                        center[1] + 2.0 * previousBeta[2])
        moving = ndimage.map_coordinates(
            moving, [X0new, X1new], prefilter=const_prefilter_map_coordinates)
        mask[...] = (X0new < 0) + (X0new > (sh[0] - 1))
        mask[...] = mask + (X1new < 0) + (X1new > (sh[1] - 1))
        mask[...] = 1 - mask
    means, variances = tf.computeMaskedVolumeClassStatsProbsCYTHON(
        mask, moving, probs)
    means = np.array(means)
    weights = np.array([1.0 / x if (x > 0) else 0 for x in variances],
                       dtype=np.float64)
    g0, g1 = sp.gradient(moving)
    q = np.empty(shape=(X0.shape) + (3, ), dtype=np.float64)
    q[..., 0] = g1 * X0 - g0 * X1
    q[..., 1] = g0
    q[..., 2] = g1
    expected = probs.dot(means)
    diff = expected - moving
    Aw, bw = tf.integrateMaskedWeightedTensorFieldProductsCYTHON(
        mask, q, diff, numLevels, rightQ, weights)
    beta = linalg.solve(Aw, bw)
    return beta
def filter_high_gradients(data_map):
    r"""
    Filters the offset field to reduce the number of very steep gradients.
    The magnitude of the gradient is taken and all values less than or
    greater than +-99th percentile are removed and recalculated.
    """
    #
    logger.info('filtering offset map to remove steeply sloped cells')
    #
    zdir_grad, xdir_grad = sp.gradient(data_map)
    mag = sp.sqrt(zdir_grad**2 + xdir_grad**2)
    data_map += 1
    data_vector = sp.ravel(data_map)
    #
    # setting regions outside of 99th percentile to 0 for cluster removal
    val = calc_percentile(99, sp.ravel(mag))
    data_map[zdir_grad < -val] = 0
    data_map[zdir_grad > val] = 0
    data_map[xdir_grad < -val] = 0
    data_map[xdir_grad > val] = 0
    #
    logger.debug('\tremoving clusters isolated by high gradients')
    offsets = DataField(data_map)
    adj_mat = offsets.create_adjacency_matrix()
    cs_num, cs_ids = csgraph.connected_components(csgraph=adj_mat,
                                                  directed=False)
    cs_num, counts = sp.unique(cs_ids, return_counts=True)
    cs_num = cs_num[sp.argsort(counts)][-1]
    #
    data_vector[sp.where(cs_ids != cs_num)[0]] = sp.nan
    data_map = sp.reshape(data_vector, data_map.shape)
    #
    # re-interpolating for the nan regions
    logger.debug('\tpatching holes left by cluster removal')
    patch_holes(data_map)
    #
    return data_map
Ejemplo n.º 43
0
def estimateNewRotation(left, right, previousAngleRadians, maxAngleRads=0, thr=-1):
    epsilon=1e-9
    center=(np.array(right.shape)-1)/2.0
    C,R=sp.meshgrid(np.array(range(right.shape[1]), dtype=np.float64), np.array(range(right.shape[0]), dtype=np.float64))
    R=R-center[0]
    C=C-center[1]
    if(np.abs(previousAngleRadians)>epsilon):
        a=np.cos(previousAngleRadians)
        b=np.sin(previousAngleRadians)
        Rnew,Cnew=(a*R-b*C+center[0], b*R+a*C+center[1])
        right=ndimage.map_coordinates(right, [Rnew,Cnew], prefilter=const_prefilter_map_coordinates)
    [dr, dc]=sp.gradient(right)
    prod=R*dc-C*dr
    diff=left-right
    num=prod*diff
    den=prod**2
    theta=0
    if(thr>0):
        N=np.sqrt((R*maxAngleRads)**2+(C*maxAngleRads)**2)
        M=(N<thr)
        theta=np.sum(num*M)/np.sum(den*M)
    else:
        theta=np.sum(num)/np.sum(den)
    return theta
Ejemplo n.º 44
0
def estimateNewRigidTransformation(left, right, previousBeta=None):
    epsilon = 1e-9
    center = (np.array(right.shape) - 1) / 2.0
    C, R = sp.meshgrid(np.array(range(right.shape[1]), dtype=np.float64),
                       np.array(range(right.shape[0]), dtype=np.float64))
    R = R - center[0]
    C = C - center[1]
    if ((previousBeta != None) and (np.max(np.abs(previousBeta)) > epsilon)):
        a = np.cos(previousBeta[0])
        b = np.sin(previousBeta[0])
        Rnew, Cnew = (a * R - b * C + 2.0 * previousBeta[1] + center[0],
                      b * R + a * C + 2.0 * previousBeta[2] + center[1])
        right = ndimage.map_coordinates(
            right, [Rnew, Cnew], prefilter=const_prefilter_map_coordinates)
    [dr, dc] = sp.gradient(right)
    epsilon = R * dc - C * dr
    c = np.array([epsilon, dr, dc]).transpose(1, 2, 0)
    tensorProds = c[:, :, :, None] * c[:, :, None, :]
    A = np.sum(np.sum(tensorProds, axis=0), axis=0)
    diff = left - right
    prod = c * diff[:, :, None]
    b = np.sum(np.sum(prod, axis=0), axis=0)
    beta = linalg.solve(A, b)
    return beta
##  I-------------wall2----------------I
## wall3                             wall1
##  I---wall0---pL--door--pR---wall0---I
dist_wall2 = y1 - dom.Y
dist_wall1 = x3 - dom.X
dist_wall3 = dom.X - x0
dist_wall0 = (dom.X<=x1)*(dom.Y-y0) + \
             (dom.X>=x2)*(dom.Y-y0) + \
             (dom.X>x1)*(dom.X<x2)*sp.minimum( \
                sp.sqrt((dom.X-x1)**2+(dom.Y-y0)**2), \
                sp.sqrt((dom.X-x2)**2+(dom.Y-y0)**2)  \
             )
wall_distance = sp.ma.MaskedArray(sp.minimum(sp.minimum(sp.minimum( \
                    dist_wall0,dist_wall1),dist_wall2),dist_wall3), mask=mask \
                )
grad = sp.gradient(wall_distance, edge_order=2)
grad_X = grad[1] / pixel_size
grad_Y = grad[0] / pixel_size
norm = sp.sqrt(grad_X**2 + grad_Y**2)
wall_grad_X = grad_X / norm
wall_grad_Y = grad_Y / norm
dom.wall_distance = wall_distance
dom.wall_grad_X = wall_grad_X
dom.wall_grad_Y = wall_grad_Y

dom.plot()
dom.plot_wall_dist(id=2)
dom.plot_desired_velocity(id=3)

## Custom plot function
fig = plt.figure(10)
Ejemplo n.º 46
0
def readmattsdata(filename,datadir,outdir,keepspec=[0,1,2,6],angle=20.5):
    d2r=sp.pi/180.
    angr=d2r*angle
    lsp=7
    # Read in Data
    
    inst = sio.loadmat(os.path.join(datadir,filename))
    xg=inst['xg'][0,0]
    x1v = xg['xp']# added to avoid gratting lobes.
    x3v = xg['zp']
    
    [x1mat,x3mat] = sp.meshgrid(x1v,x3v);
    

    
    E = x1mat*sp.sin(angr)#x
    N = x1mat*sp.cos(angr)#y
    U = x3mat
    lxs=x3mat.size
    
    Time_Vector = sp.column_stack([inst['t'],inst['t']+15])
    ns =inst['ns']
    print('Loaded densities...');
    
    ns= sp.reshape(ns,[lxs,lsp])
    Ts =inst['Ts']
    print('Loaded temperatures...')
    
    Ts=sp.reshape(Ts,[lxs,lsp])
    vs = inst['vsx1']
    print('Loaded parallel velocities...\n');
    
    # derive velocity from ExB
    Ez,Ex=sp.gradient(-1*inst['Phi'])
    dx=sp.diff(xg['x'].flatten())[0]
    dEdx=Ex/dx
    vx1=-1*dEdx/xg['Bmag']
    # from looking at the data it seems that the velocity is off by a factor of
    # 10.
    vx1=vx1.flatten()/10.
    vs=sp.reshape(vs,[lxs,lsp])
    vs=sp.sum(ns[:,:(lsp-1)]*vs[:,:(lsp-1)],1)/ns[:,lsp-1]
    v_e= vx1*sp.sin(angr)
    v_n = vx1*sp.cos(angr)
    v_u = vs
    #change units of velocity to km/s
    Velocity = sp.reshape(sp.column_stack([v_e,v_n,v_u]),[lxs,1,3])
    # reduce the number of spcecies
#    if islogical(keepspec)
#        keepspec(end)=true;
#        keepspecnum = sum(keepspec);
#    elseif ~any(keepspec==numspec)
#        keepspec = [keepspec(:),numspec];
#        keepspecnum = length(keepspec);
#    else
#        keepspecnum = length(keepspec);
#    end
    nsout = sp.reshape(ns[:,keepspec],[lxs,1,len(keepspec)])
    Tsout = sp.reshape(Ts[:,keepspec],[lxs,1,len(keepspec)])
    
    
    
    # Put everything in to ionocontainer structure
    Cart_Coords = sp.column_stack([E.flatten(),N.flatten(),U.flatten()])*1e-3

    Param_List = sp.concatenate((sp.expand_dims(nsout,nsout.ndim),sp.expand_dims(Tsout,Tsout.ndim)),-1);
    Species = sp.array(['O+','NO+','N2+','O2+','N+', 'H+','e-'])
    Species = Species[keepspec]
    fpart=os.path.splitext(filename)[0]
    fout=os.path.join(outdir,fpart+'.h5')
    ionoout=IonoContainer(Cart_Coords,Param_List,Time_Vector,ver=0,species=Species,velocity=Velocity)
    
    ionoout.saveh5(fout)
Ejemplo n.º 47
0
def Gradient(potentiel):

    Ey, Ex = gradient(potentiel)
    Ex = -Ex
    Ey = -Ey
    return Ex, Ey
Ejemplo n.º 48
0
Archivo: metrics.py Proyecto: nipy/dipy
    def initialize_iteration(self):
        r"""Prepares the metric to compute one displacement field iteration.

        Pre-computes the transfer functions (hidden random variables) and
        variances of the estimators. Also pre-computes the gradient of both
        input images. Note that once the images are transformed to the opposite
        modality, the gradient of the transformed images can be used with the
        gradient of the corresponding modality in the same fashion as
        diff-demons does for mono-modality images. If the flag
        self.use_double_gradient is True these gradients are averaged.
        """
        sampling_mask = self.static_image_mask*self.moving_image_mask
        self.sampling_mask = sampling_mask
        staticq, self.staticq_levels, hist = self.quantize(self.static_image,
                                                           self.q_levels)
        staticq = np.array(staticq, dtype=np.int32)
        self.staticq_levels = np.array(self.staticq_levels)
        staticq_means, staticq_vars = self.compute_stats(sampling_mask,
                                                         self.moving_image,
                                                         self.q_levels,
                                                         staticq)
        staticq_means[0] = 0
        self.staticq_means = np.array(staticq_means)
        self.staticq_variances = np.array(staticq_vars)
        self.staticq_sigma_sq_field = self.staticq_variances[staticq]
        self.staticq_means_field = self.staticq_means[staticq]

        self.gradient_moving = np.empty(
            shape=(self.moving_image.shape)+(self.dim,), dtype=floating)

        for i, grad in enumerate(sp.gradient(self.moving_image)):
            self.gradient_moving[..., i] = grad

        # Convert moving image's gradient field from voxel to physical space
        if self.moving_spacing is not None:
            self.gradient_moving /= self.moving_spacing
        if self.moving_direction is not None:
            self.reorient_vector_field(self.gradient_moving,
                                       self.moving_direction)

        self.gradient_static = np.empty(
            shape=(self.static_image.shape)+(self.dim,), dtype=floating)

        for i, grad in enumerate(sp.gradient(self.static_image)):
            self.gradient_static[..., i] = grad

        # Convert moving image's gradient field from voxel to physical space
        if self.static_spacing is not None:
            self.gradient_static /= self.static_spacing
        if self.static_direction is not None:
            self.reorient_vector_field(self.gradient_static,
                                       self.static_direction)

        movingq, self.movingq_levels, hist = self.quantize(self.moving_image,
                                                           self.q_levels)
        movingq = np.array(movingq, dtype=np.int32)
        self.movingq_levels = np.array(self.movingq_levels)
        movingq_means, movingq_variances = self.compute_stats(
            sampling_mask, self.static_image, self.q_levels, movingq)
        movingq_means[0] = 0
        self.movingq_means = np.array(movingq_means)
        self.movingq_variances = np.array(movingq_variances)
        self.movingq_sigma_sq_field = self.movingq_variances[movingq]
        self.movingq_means_field = self.movingq_means[movingq]
        if self.use_double_gradient:
            for i, grad in enumerate(sp.gradient(self.staticq_means_field)):
                self.gradient_moving[..., i] += grad

            for i, grad in enumerate(sp.gradient(self.movingq_means_field)):
                self.gradient_static[..., i] += grad
Ejemplo n.º 49
0
    def initialize_iteration(self):
        r"""Prepares the metric to compute one displacement field iteration.

        Pre-computes the transfer functions (hidden random variables) and
        variances of the estimators. Also pre-computes the gradient of both
        input images. Note that once the images are transformed to the opposite
        modality, the gradient of the transformed images can be used with the
        gradient of the corresponding modality in the same fashion as
        diff-demons does for mono-modality images. If the flag
        self.use_double_gradient is True these gradients are averaged.
        """
        sampling_mask = self.static_image_mask * self.moving_image_mask
        self.sampling_mask = sampling_mask
        staticq, self.staticq_levels, hist = self.quantize(
            self.static_image, self.q_levels)
        staticq = np.array(staticq, dtype=np.int32)
        self.staticq_levels = np.array(self.staticq_levels)
        staticq_means, staticq_vars = self.compute_stats(
            sampling_mask, self.moving_image, self.q_levels, staticq)
        staticq_means[0] = 0
        self.staticq_means = np.array(staticq_means)
        self.staticq_variances = np.array(staticq_vars)
        self.staticq_sigma_sq_field = self.staticq_variances[staticq]
        self.staticq_means_field = self.staticq_means[staticq]

        self.gradient_moving = np.empty(shape=(self.moving_image.shape) +
                                        (self.dim, ),
                                        dtype=floating)

        for i, grad in enumerate(sp.gradient(self.moving_image)):
            self.gradient_moving[..., i] = grad

        # Convert moving image's gradient field from voxel to physical space
        if self.moving_spacing is not None:
            self.gradient_moving /= self.moving_spacing
        if self.moving_direction is not None:
            self.reorient_vector_field(self.gradient_moving,
                                       self.moving_direction)

        self.gradient_static = np.empty(shape=(self.static_image.shape) +
                                        (self.dim, ),
                                        dtype=floating)

        for i, grad in enumerate(sp.gradient(self.static_image)):
            self.gradient_static[..., i] = grad

        # Convert moving image's gradient field from voxel to physical space
        if self.static_spacing is not None:
            self.gradient_static /= self.static_spacing
        if self.static_direction is not None:
            self.reorient_vector_field(self.gradient_static,
                                       self.static_direction)

        movingq, self.movingq_levels, hist = self.quantize(
            self.moving_image, self.q_levels)
        movingq = np.array(movingq, dtype=np.int32)
        self.movingq_levels = np.array(self.movingq_levels)
        movingq_means, movingq_variances = self.compute_stats(
            sampling_mask, self.static_image, self.q_levels, movingq)
        movingq_means[0] = 0
        self.movingq_means = np.array(movingq_means)
        self.movingq_variances = np.array(movingq_variances)
        self.movingq_sigma_sq_field = self.movingq_variances[movingq]
        self.movingq_means_field = self.movingq_means[movingq]
        if self.use_double_gradient:
            for i, grad in enumerate(sp.gradient(self.staticq_means_field)):
                self.gradient_moving[..., i] += grad

            for i, grad in enumerate(sp.gradient(self.movingq_means_field)):
                self.gradient_static[..., i] += grad
Ejemplo n.º 50
0
def sampling(data, size, gauss):
    dx, dy = scipy.gradient(data)
    edges = np.abs(dx) + np.abs(dy)
    return equalize(edges, size, gauss=gauss)
Ejemplo n.º 51
0
def estimateNewMonomodalSyNField2D(moving, fixed, fWarp, fInv, mWarp, mInv, lambdaParam, maxOuterIter):
    '''
    Warning: in the monomodal case, the parameter lambda must be significantly lower than in the multimodal case. Try lambdaParam=1,
    as opposed as lambdaParam=150 used in the multimodal case
    '''
    innerTolerance=1e-4
    outerTolerance=1e-3
    
    if(mWarp!=None):
        totalM=mWarp
        totalMInv=mInv
    else:
        totalM=np.zeros(shape=(fixed.shape)+(2,), dtype=np.float64)
        totalMInv=np.zeros(shape=(fixed.shape)+(2,), dtype=np.float64)
    if(fWarp!=None):
        totalF=fWarp
        totalFInv=fInv
    else:
        totalF=np.zeros(shape=(moving.shape)+(2,), dtype=np.float64)
        totalFInv=np.zeros(shape=(moving.shape)+(2,), dtype=np.float64)
    outerIter=0
    framesToCapture=5
    maxOuterIter=framesToCapture*((maxOuterIter+framesToCapture-1)/framesToCapture)
    itersPerCapture=maxOuterIter/framesToCapture
    plt.figure()
    while(outerIter<maxOuterIter):
        outerIter+=1
        print 'Outer iter:', outerIter
        wmoving=np.array(tf.warp_image(moving, totalMInv))
        wfixed=np.array(tf.warp_image(fixed, totalFInv))
        if((outerIter==1) or (outerIter%itersPerCapture==0)):
            plt.subplot(1,framesToCapture+1, 1+outerIter/itersPerCapture)
            rcommon.overlayImages(wmoving, wfixed, False)
            plt.title('Iter:'+str(outerIter-1))
        #Compute forward update
        sigmaField=np.ones_like(wmoving, dtype=np.float64)
        deltaField=wfixed-wmoving
        movingGradient    =np.empty(shape=(wmoving.shape)+(2,), dtype=np.float64)
        movingGradient[:,:,0], movingGradient[:,:,1]=sp.gradient(wmoving)
        maxVariation=1+innerTolerance
        innerIter=0
        fw     =np.zeros(shape=(fixed.shape)+(2,), dtype=np.float64)
        maxInnerIter=1000
        while((maxVariation>innerTolerance)and(innerIter<maxInnerIter)):
            innerIter+=1
            maxVariation=tf.iterateDisplacementField2DCYTHON(deltaField, sigmaField, movingGradient,  lambdaParam, fw, None)
        #fw*=0.5
        totalF, stats=tf.compose_vector_fields(fw, totalF)
        totalF=np.array(totalF);
        meanDispF=np.mean(np.abs(fw))
        #Compute backward field
        sigmaField=np.ones_like(wfixed, dtype=np.float64)
        deltaField=wmoving-wfixed
        fixedGradient    =np.empty(shape=(wfixed.shape)+(2,), dtype=np.float64)
        fixedGradient[:,:,0], fixedGradient[:,:,1]=sp.gradient(wfixed)
        maxVariation=1+innerTolerance
        innerIter=0
        mw     =np.zeros(shape=(fixed.shape)+(2,), dtype=np.float64)
        maxInnerIter=1000
        while((maxVariation>innerTolerance)and(innerIter<maxInnerIter)):
            innerIter+=1
            maxVariation=tf.iterateDisplacementField2DCYTHON(deltaField, sigmaField, fixedGradient,  lambdaParam, mw, None)
        #mw*=0.5
        totalM, stats=tf.compose_vector_fields(mw, totalM)
        totalM=np.array(totalM);
        meanDispM=np.mean(np.abs(mw))
        totalFInv=np.array(tf.invert_vector_field_fixed_point(totalF, None, 20, 1e-3, None))
        totalMInv=np.array(tf.invert_vector_field_fixed_point(totalM, None, 20, 1e-3, None))
        totalF=np.array(tf.invert_vector_field_fixed_point(totalFInv, None, 20, 1e-3, None))
        totalM=np.array(tf.invert_vector_field_fixed_point(totalMInv, None, 20, 1e-3, None))
#        totalFInv=np.array(tf.invert_vector_field(totalF, 0.75, 100, 1e-6))
#        totalMInv=np.array(tf.invert_vector_field(totalM, 0.75, 100, 1e-6))
#        totalF=np.array(tf.invert_vector_field(totalFInv, 0.75, 100, 1e-6))
#        totalM=np.array(tf.invert_vector_field(totalMInv, 0.75, 100, 1e-6))
        if(meanDispM+meanDispF<2*outerTolerance):
            break
    print "Iter: ",innerIter, "Mean lateral displacement:", 0.5*(meanDispM+meanDispF), "Max variation:",maxVariation
    return totalF, totalFInv, totalM, totalMInv
Ejemplo n.º 52
0
def estimateNewMultimodalSyNField3D(moving, fixed, fWarp, fInv, mWarp, mInv, initAffine, lambdaDisplacement, quantizationLevels, maxOuterIter, reportProgress=False):
    '''
        fwWarp: forward warp, the displacement field that warps moving towards fixed
        bwWarp: backward warp, the displacement field that warps fixed towards moving
        initAffine: the affine transformation to bring moving over fixed (this part is not symmetric)
    '''
    print 'Moving shape:',moving.shape,'. Fixed shape:',fixed.shape
    innerTolerance=1e-3
    outerTolerance=1e-3
    fixedMask=(fixed>0).astype(np.int32)
    movingMask=(moving>0).astype(np.int32)
    if(fWarp!=None):
        totalF=fWarp
        totalFInv=fInv
    else:
        totalF    =np.zeros(shape=(fixed.shape)+(3,), dtype=np.float64)
        totalFInv =np.zeros(shape=(fixed.shape)+(3,), dtype=np.float64)
    if(mWarp!=None):
        totalM=mWarp
        totalMInv=mInv
    else:
        totalM   =np.zeros(shape=(moving.shape)+(3,), dtype=np.float64)
        totalMInv=np.zeros(shape=(moving.shape)+(3,), dtype=np.float64)
    finished=False
    outerIter=0
    while((not finished) and (outerIter<maxOuterIter)):
        outerIter+=1
        if(reportProgress):
            print 'Iter:',outerIter,'/',maxOuterIter
        #---E step---
        wmoving=np.array(tf.warp_volume(moving, totalMInv, initAffine))
        wmovingMask=np.array(tf.warp_discrete_volumeNN(movingMask, totalMInv, initAffine)).astype(np.int32)
        wfixed=np.array(tf.warp_volume(fixed, totalFInv))
        wfixedMask=np.array(tf.warp_discrete_volumeNN(fixedMask, totalFInv)).astype(np.int32)
        fixedQ, grayLevels, hist=tf.quantizePositiveVolumeCYTHON(wfixed, quantizationLevels)
        fixedQ=np.array(fixedQ, dtype=np.int32)
        movingQ, grayLevels, hist=tf.quantizePositiveVolumeCYTHON(wmoving, quantizationLevels)
        movingQ=np.array(movingQ, dtype=np.int32)
        trust=wfixedMask*wmovingMask
        meansMoving, variancesMoving=tf.computeMaskedVolumeClassStatsCYTHON(trust, wmoving, quantizationLevels, fixedQ)
        meansFixed, variancesFixed=tf.computeMaskedVolumeClassStatsCYTHON(trust, wfixed, quantizationLevels, movingQ)
        meansMoving[0]=0
        meansFixed[0]=0
        meansMoving=np.array(meansMoving)
        meansFixed=np.array(meansFixed)
        variancesMoving=np.array(variancesMoving)
        sigmaFieldMoving=variancesMoving[fixedQ]
        variancesFixed=np.array(variancesFixed)
        sigmaFieldFixed=variancesFixed[movingQ]
        deltaFieldMoving=meansMoving[fixedQ]-wmoving
        deltaFieldFixed=meansFixed[movingQ]-wfixed
        #--M step--
        movingGradient  =np.empty(shape=(moving.shape)+(3,), dtype=np.float64)
        movingGradient[:,:,:,0], movingGradient[:,:,:,1], movingGradient[:,:,:,2]=sp.gradient(wmoving)
        #iterate forward field
        maxVariation=1+innerTolerance
        innerIter=0
        maxInnerIter=100
        fw=np.zeros_like(totalF)
        while((maxVariation>innerTolerance)and(innerIter<maxInnerIter)):
            innerIter+=1
            maxVariation=tf.iterateDisplacementField3DCYTHON(deltaFieldMoving, sigmaFieldMoving, movingGradient,  lambdaDisplacement, totalF, fw, None)
        del movingGradient
        fw*=0.5
        totalF=np.array(tf.compose_vector_fields3D(fw, totalF))#Multiply fw by 0.5??
        nrm=np.sqrt(fw[...,0]**2+fw[...,1]**2+fw[...,2]**2)
        del fw        
        #iterate backward field
        fixedGradient   =np.empty(shape=(fixed.shape)+(3,), dtype=np.float64)
        fixedGradient[:,:,:,0], fixedGradient[:,:,:,1], fixedGradient[:,:,:,2]=sp.gradient(wfixed)
        maxVariation=1+innerTolerance
        innerIter=0
        maxInnerIter=100
        mw=np.zeros_like(totalM)
        while((maxVariation>innerTolerance)and(innerIter<maxInnerIter)):
            innerIter+=1
            maxVariation=tf.iterateDisplacementField3DCYTHON(deltaFieldFixed, sigmaFieldFixed, fixedGradient,  lambdaDisplacement, totalM, mw, None)
        del fixedGradient
        mw*=0.5
        totalM=np.array(tf.compose_vector_fields3D(mw, totalM))#Multiply bw by 0.5??
        nrm=np.sqrt(mw[...,0]**2+mw[...,1]**2+mw[...,2]**2)
        del mw        
        #invert fields
        totalFInv=np.array(tf.invert_vector_field_fixed_point3D(totalF, 20, 1e-6))
        totalMInv=np.array(tf.invert_vector_field_fixed_point3D(totalM, 20, 1e-6))
        totalF=np.array(tf.invert_vector_field_fixed_point3D(totalFInv, 20, 1e-6))
        totalM=np.array(tf.invert_vector_field_fixed_point3D(totalMInv, 20, 1e-6))
        maxDisplacement=np.mean(nrm)
        if((maxDisplacement<outerTolerance)or(outerIter>=maxOuterIter)):
            finished=True
    print "Iter: ",outerIter, "Mean displacement:", maxDisplacement, "Max variation:",maxVariation
    return totalF, totalFInv, totalM, totalMInv
Ejemplo n.º 53
0
def parse(fname, level, step, window):

    if not os.path.isfile(fname):
        print 'Error: could not open %s' % fname
        sys.exit('Stopping')

    oname = fname + '.wig'

    fp = open(oname, 'wt')
    fp.write('track type=wiggle_0\n')

    fedges = open(fname + '.edges.bed', 'w')

    # mat file parsing parsing
    from MAT import AffyFileParser
    bar = AffyFileParser.CBARFileWriter()
    print fname
    bar.SetFileName(fname)
    if not bar.Read():
        raise Exception('Unable to properly read %s' % fname)

    seq = AffyFileParser.CGDACSequenceResultItem()
    data = AffyFileParser.BarSequenceResultData()

    seq_range = range(bar.GetNumberSequences() - 1)
    for s in seq_range:
        bar.GetResults(s, seq)
        name = seq.GetName()
        if name in ['XIST', 'chloroplast', 'NC_000964.1']:
            continue

        read_counts = sp.zeros(sizes[name] // binsize + 1)

        for i in range(0, seq.GetNumberDataPoints() - 1, step):
            seq.GetData(i, 0, data)
            x = data.iValue
            seq.GetData(i, 1, data)
            y = data.fValue
            out = '%s\t%s\t%s\t%s\n' % (name, x - 1, x, y)
            fp.write(out)

            read_counts[x // binsize] += y

        d = sp.gradient(read_counts)
        d2 = sp.gradient(d)
        d = sp.array([0] + list(d[:-1]))
        d2 = sp.array([0, 0] + list(d2[:-2]))

        #smoothed = smooth(read_counts, window_len=3)
        #read_counts[(read_counts > -.5) & (read_counts < .5)] = 0
        smoothed = blur_image(read_counts, window_size)
        #smooth_d = sp.gradient(smoothed)
        #smooth_d2 = sp.gradient(smooth_d)

        pos_to_neg = sp.diff(sp.sign(smoothed)) < 0
        #decreasing = (sp.diff(smoothed) < 0)

        #for x_d in ((smoothed > 1) & (smooth_d < 1)).nonzero()[0]:
        #for x_d in sp.nonzero(pos_to_neg & decreasing)[0]:
        for x_d in sp.nonzero(pos_to_neg)[0]:
            fedges.write('\t'.join(
                map(str, [name, (x_d + 1) * binsize, (x_d + 2) * binsize])) +
                         '\n')

    print '...saved bar data to: %s' % oname
Ejemplo n.º 54
0
def computeJacobianField(displacement):
    g00,g01=sp.gradient(displacement[...,0])
    g10,g11=sp.gradient(displacement[...,1])
    return (1+g00)*(1+g11)-g10*g01
Ejemplo n.º 55
0
def plotgradlines(inputlist,fitiono,alt,times,paramlist=['Ne','Te','Ti']):
    """
    Plots the values along a specific alittude. 
    """
    inputiono = makeionocombined(inputlist)
    Iono1 = GeoData(readIono,[inputiono])
    fitiono = IonoContainer.readh5(fitiono)
    fitGeo = GeoData(readIono,[fitiono])
    
    paramlist = ['Ne','Te','Ti']
    (x,y,z) = inputiono.Cart_Coords.transpose()
    r = sp.sqrt(x**2+y**2)*sp.sign(y)
    incoords = sp.column_stack((r,z,sp.ones_like(z)))
    ru,zu =[ sp.unique(r),sp.unique(z)]
    Rmat,Zmat = sp.meshgrid(ru,zu)
    zinput = sp.argmin(sp.absolute(zu-alt))
    
    (xf,yf,zf) = fitiono.Cart_Coords.transpose()
    rf = sp.sqrt(xf**2+yf**2)*sp.sign(yf)
    outcoords = sp.column_stack((rf,zf,sp.ones_like(zf)))
    rfu,zfu =[ sp.unique(rf),sp.unique(zf)]
    Rfmat,Zfmat = sp.meshgrid(rfu,zfu)
    zoutput = sp.argmin(sp.absolute(zfu-alt))
    
    fitGeo.interpolate(incoords,Iono1.coordnames,method='linear',fill_value=sp.nan,twodinterp = True,oldcoords=outcoords)

    uz = sp.unique(z)
    ur = sp.unique(r)
    (rmat,zmat) = sp.meshgrid(ur,uz)
    
    inputdata = {}
    for iparm in paramlist:
        if iparm =='Nepow':
            iparm='Ne'
        curdata = Iono1.data[iparm][:,times[0]]
        
        inputdata[iparm] = sp.reshape(curdata,Rmat.shape)[zinput]

    outputdata = {}
    for iparm in paramlist:
        curdata = fitGeo.data[iparm][:, times[1]]
        outputdata[iparm] = sp.reshape(curdata,Rmat.shape)[zinput]
    
    fig, axvec = plt.subplots(len(paramlist),1,sharey=False,figsize=(12,5*len(paramlist)))
    
    for ipn,iparam in enumerate(paramlist):
        ax = axvec[ipn]
        ax2 = ax.twinx()
        p1, = ax.plot(ru,inputdata[iparam],'b-',label='In',linewidth=3)
        p2, = ax.plot(ru,outputdata[iparam],'b--',label='Out',linewidth=3)
        ax.set_title(iparam)
        ax.set_xlabel('X Plane in km')
        gi = sp.gradient(inputdata[iparam])/sp.gradient(ru)
        go = sp.gradient(outputdata[iparam])/sp.gradient(ru)
        p3, = ax2.plot(ru,gi,'g-',label='Grad In',linewidth=3)
        p4, = ax2.plot(ru,go,'g--',label='Grad Out',linewidth=3)
        ax.yaxis.label.set_color(p1.get_color())
        ax2.yaxis.label.set_color(p3.get_color())
        lines = [p1,p2,p3,p4]
        ax.legend(lines,[l.get_label() for l in lines])
    
    plt.tight_layout()    
    return(fig)
Ejemplo n.º 56
0
def estimateNewECQMMFMultimodalDeformationField2D(fixed, moving, nclasses, lambdaMeasureField, lambdaDisplacement, mu, maxOuterIter, maxInnerIter, tolerance, previousDisplacement=None):
    sh=fixed.shape
    X0,X1=np.mgrid[0:sh[0], 0:sh[1]]
    displacement     =np.empty(shape=(fixed.shape)+(2,), dtype=np.float64)
    gradientField    =np.empty(shape=(fixed.shape)+(2,), dtype=np.float64)
    totalDisplacement=np.zeros(shape=(fixed.shape)+(2,), dtype=np.float64)
    gradientField    =np.empty(shape=(fixed.shape)+(2,), dtype=np.float64)
    residuals        =np.zeros_like(fixed)
    warped=None
    if(previousDisplacement!=None):
        totalDisplacement[...]=previousDisplacement
        warped=ndimage.map_coordinates(moving, [X0+totalDisplacement[...,0], X1+totalDisplacement[...,1]], prefilter=True)
    else:
        warped=moving
    #run soft segmentation on the fixed image
    meansFixed, variancesFixed=ecqmmf.initialize_constant_models(fixed, nclasses)
    meansFixed=np.array(meansFixed)
    variancesFixed=np.array(variancesFixed)
    segFixed, meansFixed, variancesFixed, probsFixed=ecqmmf.ecqmmf(fixed, nclasses, lambdaMeasureField, mu, maxOuterIter, maxInnerIter, tolerance)
    meansFixed=np.array(meansFixed)
    probsFixed=np.array(probsFixed)
    #run soft segmentation on the warped image
    meansWarped, variancesWarped=ecqmmf.initialize_constant_models(warped, nclasses)
    meansWarped=np.array(meansWarped)
    variancesWarped=np.array(variancesWarped)
    segWarped, meansWarped, variancesWarped, probsWarped=ecqmmf.ecqmmf(warped, nclasses, lambdaMeasureField, mu, maxOuterIter, maxInnerIter, tolerance)
    meansWarped=np.array(meansWarped)
    probsWarped=np.array(probsWarped)
    #inicialize the joint models (solve assignment problem)
    ecqmmf_reg.initialize_coupled_constant_models(probsFixed, probsWarped, meansWarped)
    #start optimization
    outerIter=0
    negLogLikelihood=np.zeros_like(probsFixed)
    while(outerIter<maxOuterIter):
        outerIter+=1
        print "Outer:", outerIter
        if(outerIter>1):#avoid warping twice at the first iteration
            warped=ndimage.map_coordinates(moving, [X0+totalDisplacement[...,0], X1+totalDisplacement[...,1]], prefilter=True)
        movingMask=(moving>0)*1.0
        warpedMask=ndimage.map_coordinates(movingMask, [X0+totalDisplacement[...,0], X1+totalDisplacement[...,1]], order=0, prefilter=False)
        warpedMask=warpedMask.astype(np.int32)
        #--- optimize the measure field and the intensity models ---
        ecqmmf_reg.compute_registration_neg_log_likelihood_constant_models(fixed, warped, meansFixed, meansWarped, negLogLikelihood)
        #ecqmmf.initialize_normalized_likelihood(negLogLikelihood, probsWarped)
        ecqmmf.initialize_maximum_likelihood(negLogLikelihood, probsWarped);
        innerIter=0
        mse=0
        while(innerIter<maxInnerIter):
            innerIter+=1
            print "\tInner:",innerIter
            ecqmmf.optimize_marginals(negLogLikelihood, probsWarped, lambdaMeasureField, mu, maxInnerIter, tolerance)
            mseFixed=ecqmmf.update_constant_models(fixed, probsWarped, meansFixed, variancesFixed)
            mseWarped=ecqmmf.update_constant_models(warped, probsWarped, meansWarped, variancesWarped)
            mse=np.max([mseFixed, mseWarped])
            if(mse<tolerance):
                break
        #---given the intensity models and the measure field, compute the displacement
        deltaField=meansWarped[None, None, :]-warped[:,:,None]
        gradientField[:,:,0], gradientField[:,:,1]=sp.gradient(warped)
        maxDisplacement=ecqmmf_reg.optimize_ECQMMF_displacement_field_2D(deltaField, gradientField, probsWarped, lambdaDisplacement, displacement, residuals, maxInnerIter, tolerance)
        totalDisplacement+=displacement
        if(maxDisplacement<tolerance):
            break
    plt.figure()
    plt.subplot(2,2,1)
    plt.imshow(fixed, cmap=plt.cm.gray)
    plt.title("fixed")
    plt.subplot(2,2,2)
    plt.imshow(warped, cmap=plt.cm.gray)
    plt.title("moving")
    plt.subplot(2,2,3)
    plt.imshow(probsFixed.dot(meansFixed), cmap=plt.cm.gray)
    plt.title("E[fixed]")
    plt.subplot(2,2,4)
    plt.imshow(probsWarped.dot(meansWarped), cmap=plt.cm.gray)
    plt.title("E[moving]")
    return totalDisplacement
Ejemplo n.º 57
0
def angleofgradient(x,*args, **kwargs):
   g0=scipy.gradient(x,*args,**kwargs)
   return numpy.angle(g0[0]+g0[1]*1J)