Esempio n. 1
0
def test_zero_image_size():
    with pytest.raises(ValueError):
        warp(np.zeros(0), SimilarityTransform())
    with pytest.raises(ValueError):
        warp(np.zeros((0, 10)), SimilarityTransform())
    with pytest.raises(ValueError):
        warp(np.zeros((10, 0)), SimilarityTransform())
    with pytest.raises(ValueError):
        warp(np.zeros((10, 10, 0)), SimilarityTransform())
Esempio n. 2
0
def test_warp_tform():
    x = np.zeros((5, 5), dtype=np.double)
    x[2, 2] = 1
    theta = -np.pi / 2
    tform = SimilarityTransform(scale=1, rotation=theta, translation=(0, 4))

    x90 = warp(x, tform, order=1)
    assert_array_almost_equal(x90, np.rot90(x))

    x90 = warp(x, tform.inverse, order=1)
    assert_array_almost_equal(x90, np.rot90(x))
Esempio n. 3
0
    def run(self,
            stack: ImageStack,
            verbose: bool = False,
            *args) -> TransformsList:
        """
        Iterate over the given axes of an ImageStack and learn the Similarity transform
        based off the reference_stack passed into :py:class:`Translation`'s constructor.
        Only supports 2d data.


        Parameters
        ----------
        stack : ImageStack
            Stack to calculate the transforms on.
        verbose : bool
            if True, report on transformation progress (default = False)

        Returns
        -------
        List[Tuple[Mapping[Axes, int], SimilarityTransform]] :
            A list of tuples containing axes of the Imagestack and associated
            transform to apply.
        """

        transforms = TransformsList()
        reference_image = np.squeeze(self.reference_stack.xarray)
        for a in stack.axis_labels(self.axes):
            target_image = np.squeeze(stack.sel({self.axes: a}).xarray)
            if len(target_image.shape) != 2:
                raise ValueError(
                    f"Only axes: {self.axes.value} can have a length > 1, "
                    f"please use the MaxProj filter.")

            shift, error, phasediff = register_translation(
                src_image=target_image,
                target_image=reference_image,
                upsample_factor=self.upsampling)
            if verbose:
                print(f"For {self.axes}: {a}, Shift: {shift}, Error: {error}")
            selectors = {self.axes: a}
            # reverse shift because SimilarityTransform stores in y,x format
            shift = shift[::-1]
            transforms.append(selectors, TransformType.SIMILARITY,
                              SimilarityTransform(translation=shift))

        return transforms
Esempio n. 4
0
    def _align_transform(image_ref: ndarray, image: ndarray,
                         **kwargs) -> Tuple[ndarray, SimilarityTransform]:
        """
        Calculate the transformation needed to align the image with the a reference image

        :param image_ref: a refernce image to align with
        :param image: an image to align with image_ref
        :param kwargs: keyword arguments passed to imreg_dft.imreg.similarity
        :returns: a transformation that will align the image with image_ref, and the aligned greyscale image
        """
        from imreg_dft import similarity
        from skimage.color import rgb2gray
        from ..imaging import image_as_rgb

        # imreg_dft.similarity can't handle colour images
        image_ref_gray = rgb2gray(image_as_rgb(image_ref))
        image_gray = rgb2gray(image_as_rgb(image))

        transform_params = similarity(image_ref_gray, image_gray, **kwargs)
        transform = SimilarityTransform(scale=transform_params["scale"],
                                        rotation=transform_params["angle"],
                                        translation=transform_params["tvec"])

        return transform_params["timg"], transform
Esempio n. 5
0
def rotate(image, angle, resize=False, order=1, mode='constant', cval=0.):
    """Rotate image by a certain angle around its center.

    Parameters
    ----------
    image : ndarray
        Input image.
    angle : float
        Rotation angle in degrees in counter-clockwise direction.
    resize : bool, optional
        Determine whether the shape of the output image will be automatically
        calculated, so the complete rotated image exactly fits. Default is
        False.

    Returns
    -------
    rotated : ndarray
        Rotated version of the input.

    Other parameters
    ----------------
    order : int, optional
        The order of the spline interpolation, default is 1. The order has to
        be in the range 0-5. See `skimage.transform.warp` for detail.
    mode : string, optional
        Points outside the boundaries of the input are filled according
        to the given mode ('constant', 'nearest', 'reflect' or 'wrap').
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    Examples
    --------
    >>> from skimage import data
    >>> from skimage.transform import rotate
    >>> image = data.camera()
    >>> rotate(image, 2).shape
    (512, 512)
    >>> rotate(image, 2, resize=True).shape
    (530, 530)
    >>> rotate(image, 90, resize=True).shape
    (512, 512)

    """

    rows, cols = image.shape[0], image.shape[1]

    # rotation around center
    translation = np.array((cols, rows)) / 2. - 0.5
    tform1 = SimilarityTransform(translation=-translation)
    tform2 = SimilarityTransform(rotation=np.deg2rad(angle))
    tform3 = SimilarityTransform(translation=translation)
    tform = tform1 + tform2 + tform3

    output_shape = None
    if resize:
        # determine shape of output image
        corners = np.array([[1, 1], [1, rows], [cols, rows], [cols, 1]])
        corners = tform(corners - 1)
        minc = corners[:, 0].min()
        minr = corners[:, 1].min()
        maxc = corners[:, 0].max()
        maxr = corners[:, 1].max()
        out_rows = maxr - minr + 1
        out_cols = maxc - minc + 1
        output_shape = np.ceil((out_rows, out_cols))

        # fit output image in new shape
        translation = ((cols - out_cols) / 2., (rows - out_rows) / 2.)
        tform4 = SimilarityTransform(translation=translation)
        tform = tform4 + tform

    return warp(image,
                tform,
                output_shape=output_shape,
                order=order,
                mode=mode,
                cval=cval)
Esempio n. 6
0
def test_inverse():
    tform = SimilarityTransform(scale=0.5, rotation=0.1)
    inverse_tform = SimilarityTransform(matrix=np.linalg.inv(tform.params))
    image = np.arange(10 * 10).reshape(10, 10).astype(np.double)
    assert_array_equal(warp(image, inverse_tform), warp(image, tform.inverse))
Esempio n. 7
0
def test_invalid():
    with pytest.raises(ValueError):
        warp(np.ones((4, 3, 3, 3)), SimilarityTransform())
Esempio n. 8
0
def test_warp_coords_example():
    image = astronaut().astype(np.float32)
    assert 3 == image.shape[2]
    tform = SimilarityTransform(translation=(0, -10))
    coords = warp_coords(tform, (30, 30, 3))
    map_coordinates(image[:, :, 0], coords[:2])