Skip to content

Add support for y-dimensional shear to the AffineTransform - #6752

Merged
lagru merged 9 commits into
scikit-image:mainfrom
i-aki-y:add-shear_y
Apr 7, 2023
Merged

lagru merged 9 commits into
scikit-image:mainfrom
i-aki-y:add-shear_y

Conversation

@i-aki-y

@i-aki-y i-aki-y commented Feb 15, 2023 •

Copy link
Copy Markdown
Contributor

Description

Closes #1779, closes #3548

(This PR is based on the other PR #6717; sorry, I am not sure how to compare different PRs on GitHub. This shows the two PR's diffs. If needed, I will rebase if the previous PR #6717 could be approved).

In this PR, I added support for a list-like shear argument to the AffineTransform.
The current implementation supports only the x-dimensional shear parameter, and the y-dimensional shear is a missing feature (#1779, #3548, #1975).
With this PR, the constructor supports scaler and list-like values as a shear argument.

AffineTransform(shear=(shear_x, shear_y))
AffineTransform(shear=shear)

If the shear is a scaler, it is interpreted as a tuple of an x-dimensional only to maintain backward compatibility.

AffineTransform(shear=shear) == AffineTransform(shear=(shear, 0))

Including the shear_y argument, the equation of the transformation is modified in the following ways:

X = a0*x + a1*y + a2
    = sx*x*(cos(rotation) + tan(shear_y) sin(rotation)) -
    sy*y*(tan(shear_x) * sin(rotation) + sin(rotation)) + a2

Y = b0*x + b1*y + b2
    = sx*x*(sin(rotation) - tan(shear_y) cos(rotation)) -
    sy*y*(tan(shear_x) * sin(rotation) - cos(rotation)) + b2

Some results will be:

import matplotlib.pyplot as plt
import skimage.data
from skimage.transform import warp, AffineTransform

img = skimage.data.astronaut()
M_shx = AffineTransform(scale=0.5, shear=-np.pi / 4)
M_shy = AffineTransform(scale=0.5, shear=(0, -np.pi / 4))
M_shxy = AffineTransform(scale=0.5, shear=(-np.pi / 6, -np.pi / 6))
img1 = warp(img, M_shx.inverse, cval=1.0)
img2 = warp(img, M_shy.inverse, cval=1.0)
img3 = warp(img, M_shxy.inverse, cval=1.0)
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
axes[0].set_title("shear:(-45, 0) deg")
axes[0].imshow(img1)
axes[1].set_title("shear:(0, -45) deg")
axes[1].imshow(img2)
axes[2].set_title("shear:(-30, -30) deg")
axes[2].imshow(img3)
[ax.grid() for ax in axes]
fig.savefig("./affine_shear_xy.jpg", bbox_inches="tight")

affine_shear_xy

Important Note

With this slight modification, I found that the properties self.scale, self.rotation, self.shear, self.translation become meaning less. I want to conclude we should make these properties deprecated in the future.

This example shows what I want to say:

from numpy.testing import assert_allclose
from skimage.transform import AffineTransform

scale1 = (1.2, 0.8)
shear1 = (0.5, 1.2)
rotation1 = 0.6283185307179586
trans1 = AffineTransform(scale=scale1, shear=shear1, rotation=rotation1)

scale2 = (1.78928906317501, 0.69722642221784) 
shear2 = (0.7, 1.0)
rotation2 = 0.42831853071795867
trans2 = AffineTransform(scale=scale2, shear=shear2, rotation=rotation2)

assert_allclose(trans1.params, trans2.params)
print(trans1.params.flatten())
print(trans2.params.flatten())
# output:
# [ 2.78506774 -0.8238026   0.         -1.79175495  0.39032676  0.   0.          0.          1.        ]
# [ 2.78506774 -0.8238026   0.         -1.79175495  0.39032676  0.   0.          0.          1.        ]

# print(trans1.rotation) => ?
# print(trans1.rotation == trans2.rotation) => ?

In this example, we could create the same transformations with different arguments. We can not tell what value the trans1.rotation should return in such a case.
I think this is a theoretical limitation instead of an implementation bug. See the discussion below.

Discussion of a relation between properties and matrix elements

The current AffineTransform class has the following properties: self.scale, self.rotation, self.shear, self.translation. These are re-calculated from the matrix elements. We can explicitly show how these values are calculated.

First, I define the elements of the matrix and the related arguments. A matrix of 2D affine transform can be written in the following form:

$$\begin{pmatrix} x' \\\ y' \\\ 1 \end{pmatrix} = \begin{pmatrix} M & t \\\ 0 & 1 \end{pmatrix} \begin{pmatrix} x \\\ y \\\ 1 \end{pmatrix},$$

where

$$M = R_\theta H_{\phi_x, \phi_y} S_{s_x,s_y} = \begin{pmatrix} s_x (\cos \theta + \tan \phi_y \sin \theta) & -s_y(\tan \phi_x \cos\theta + \sin \theta) \\\ s_x (\sin \theta - \tan \phi_y \cos \theta) & -s_y(\tan \phi_x \sin\theta - \cos \theta) \\ \end{pmatrix}.$$

The $R_\theta, H_{\phi_x, \phi_y}, S_{sx, sy}$ are matrices of rotate, shear, and scale transformations, and $t$ is a translation vector.

$$S_{x, y} = \begin{pmatrix} s_x & 0 \\\ 0 & s_y \end{pmatrix}, R_\theta = \begin{pmatrix} \cos \theta & -\sin \theta \\\ \sin \theta & \cos \theta \end{pmatrix}, H_{\phi_x, \phi_y} = \begin{pmatrix} 1 & -\tan \phi_x \\\ -\tan \phi_y & 1 \end{pmatrix}, t = \begin{pmatrix} t_x \\\ t_y \end{pmatrix},$$

Note we can define different forms with the other matrix orders like $S_{s_x, s_y} R_\theta H_{\phi_x, \phi_y}$. Here, I selected the above definition because it matches the current implementation.

I will focus on the relation between the matrix $M$ and the parameters $s_x, s_y, \theta, ...$ . With the above notations, we can write the $s_x, s_y, \theta, ...$ as a function of the matrix elements $M_{i, j}$:

$$\begin{equation} s_x = \sqrt{M_{0, 0}^2 + M_{1, 0}^2 / (1 + \tan^2 \phi_y)} \qquad \dots (1) \end{equation}$$ $$\begin{equation} s_y = \sqrt{M_{0, 1}^2 + M_{1, 1}^2 / (1 + \tan^2 \phi_x)} \qquad \dots (2) \end{equation}$$ $$\begin{equation} \theta + \phi_x = -\arctan{\frac{M_{0, 1}}{M_{1, 1}}} \qquad \dots (3) \end{equation}$$ $$\begin{equation} \theta - \phi_y = \arctan{\frac{M_{1, 0}}{M_{0, 0}}} \qquad \dots (4) \end{equation}$$

An important remark is that the solution to these equations is not unique! Because the number of parameters (= 5 = 2 scales + 2 shears + 1 rotation) is larger than the number of the 2x2 matrix elements (= 4).
The solutions are given as a function of a free parameter: $u \in (-\pi/2 \lt u \lt \pi/2)$,

$$\begin{equation} s_x(u) = \sqrt{(M_{0, 0}^2 + M_{1, 0}^2) / (1 + \tan^2 u)} \end{equation}$$ $$\begin{equation} s_y(u) = \sqrt{(M_{0, 1}^2 + M_{1, 1}^2) / (1 + \tan^2(\phi_x(u))} \end{equation}$$ $$\begin{equation} \phi_x(u) = -\arctan{\frac{M_{0, 1}}{M_{1, 1}}} - \theta(u) \end{equation}$$ $$\begin{equation} \theta(u) = \arctan{\frac{M_{1, 0}}{M_{0, 0}}} + u \end{equation}$$ $$\begin{equation} \phi_y(u) = u \end{equation}$$

By changing the $u$, we can get arbitrary many solutions $s_x, s_y, \phi_x, ...$, which make the same Affine transformation. This means we can not tell the value that the self.scale should return. The same discussion could be applied to the translations $t_x, t_y$ because we can make complex transformations by combining multiple transformations AffineTransform(...) + AffineTransform(...) + ... , which mixes $t_x, t_y$ and other properties. And then we can make similar equations to the eq.(1)-(4) including $t_x, t_y$.

Appendix

I will show detailed derivations of eq.(1) and (3).
(eq.(2) and (4) are almost the same as the eq.(1) and (3))

For eq.(1):

$$M_{0, 0}^2 + M_{1, 0}^2 = s_x^2 \left[ (\cos \theta + \tan \phi_y \sin\theta )^2 + (\sin\theta - \tan \phi_y \cos \theta)^2 \right]$$ $$= s_x^2\left[\cos^2\theta + \sin^2\theta + \tan^2 \phi_y (\sin^2 \theta + \cos^2 \theta) \right] = s_x^2(1 + \tan \phi_y).$$

Solving this by $s_x$, we can get eq.(1).

For eq.(3):

$$M_{0, 1} / M_{1, 1} = \frac{\tan \phi_x \cos\theta + \sin\theta}{\tan \phi_x \sin \theta - \cos\theta} = \frac{\sin\phi_x \cos \theta + \sin \theta \cos\phi_x}{\sin\theta \sin \phi_x - \cos \phi_y \cos \theta}$$ $$= \frac{\sin(\theta + \phi_x)}{-\cos(\theta + \phi_x)} = -\tan(\theta + \phi_x),$$

Applying arctan to both sides yields eq.(3).

Checklist

  • Docstrings for all functions
  • Gallery example in ./doc/examples (new features only)
  • Benchmark in ./benchmarks, if your changes aren't covered by an
    existing benchmark
  • Unit tests
  • Clean style in the spirit of PEP8
  • Descriptive commit messages (see below)

For reviewers

  • Check that the PR title is short, concise, and will make sense 1 year
    later.
  • Check that new functions are imported in corresponding __init__.py.
  • Check that new features, API changes, and deprecations are mentioned in
    doc/release/release_dev.rst.
  • There is a bot to help automate backporting a PR to an older branch. For
    example, to backport to v0.19.x after merging, add the following in a PR
    comment: @meeseeksdev backport to v0.19.x
  • To run benchmarks on a PR, add the run-benchmark label. To rerun, the label
    can be removed and then added again. The benchmark output can be checked in
    the "Actions" tab.

Update 2023.3.16: Added equation numbers (1) - (4).

@i-aki-y i-aki-y changed the title Add support for y-dimensional shear Add support for y-dimensional shear to the AffineTransform Feb 15, 2023
@stefanv

stefanv commented Feb 15, 2023

Copy link
Copy Markdown
Member

@i-aki-y Thank you for this contribution, and for the fantastically detailed write-up! 🙏

We are currently in feature freeze until the next release comes out (probably end of this week or Monday). I hope that we can integrate your contribution as one of the first for the 0.21 development cycle!

@stefanv

stefanv commented Apr 6, 2023

Copy link
Copy Markdown
Member

Needs an update based on recently marged changes by @i-aki-y.

@i-aki-y

i-aki-y commented Apr 7, 2023

Copy link
Copy Markdown
Contributor Author

@stefanv I have updated.

@stefanv stefanv added this to the 0.21 milestone Apr 7, 2023
@lagru
lagru merged commit 53ee19a into scikit-image:main Apr 7, 2023
@lagru

lagru commented Apr 7, 2023

Copy link
Copy Markdown
Member

Thank you so much @i-aki-y! This closes an issue (#1779) from 2015! 😊

Concerning your suggestion to deprecate the attributes scale, rotation, shear, translation, I see these as convenience. The ground truth of the transformation should be the params attribute. Instead of deprecating these attributes, we could just store scale, etc. in private attributes if the are given and return None or a calculated value otherwise? Though, not saying that is the best option. 🤔

Long-term, we should really think about where we want the API to go. That discussion should probably continue elsewhere, e.g. in #2397?

@lagru lagru mentioned this pull request Apr 7, 2023
@i-aki-y

i-aki-y commented Apr 8, 2023

Copy link
Copy Markdown
Contributor Author

@stefanv @lagru Thank you for your time.

Concerning your suggestion to deprecate the attributes scale, rotation, shear, translation, I see these as convenience. The ground truth of the transformation should be the params attribute. Instead of deprecating these attributes, we could just store scale, etc. in private attributes if the are given and return None or a calculated value otherwise? Though, not saying that is the best option. 🤔

Sure, it depends on how the users use these properties. If there exists a usecase in which these properties are helpful, it would still be meaningful.

rapids-bot Bot pushed a commit to rapidsai/cucim that referenced this pull request Jul 11, 2023
# Description

This MR ports several recent changes implemented upstream in scikit-image 0.21rc0. Some are just minor refactoring or documentation fixes, but I have commented on the more significant changes below so we can reuse that for the release note.

If preferred, I can split the items below into separate small PRs.

## API Changes / Deprecations
- The `random_state` argument of `medial_axis` and `unsupervised_wiener` is now deprecated and will be removed in the future. The new argument name, `seed`, should be used instead.

- The formerly private function `_invariant_denoise` has been renamed `denoise_invariant` and is now part of the public `cucim.skimage.restoration` API.

- The existing function `cucim.skimage.color.get_xyz_coords` has been renamed `cucim.skimage.color.xyz_tristimulus_values`. The former function name is deprecated and will be removed in the future.

## Enhancements
- A new `return_mapping` option was added to `join_segmentations`. This provides an additional output with a mapping between the labels in the joined segmentation and the original ones.

- Added support for y-axis shear to the [2D AffineTransform](scikit-image/scikit-image#6752)

## Backwards Incompatible Changes
- A bug fix to the energy calculation in `chan_vese` may result in different output from previous versions.

## Bug Fixes
- Fixed [bug in energy calculation in Chan-Vese](scikit-image/scikit-image#6902)

- Fixed a [bug in 2D shear calculations for `AffineTransform`](scikit-image/scikit-image#6717)

Authors:
  - Gregory Lee (https://github.com/grlee77)
  - https://github.com/jakirkham

Approvers:
  - Gigon Bae (https://github.com/gigony)

URL: #573
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add shear axis argument to AffineTransform? Specify shear more intuitively by x and y scaling factors?

3 participants