Repository navigation
Fix matrix calculation for shear angle in AffineTransform - #6717
Conversation
lagru
left a comment
There was a problem hiding this comment.
Thanks @i-aki-y for tackling this!
In #3239 (comment) @hmaarrfk notes
Shear should not be a 1D parameter should it? I feel like you should have shear_x shear_y?
I'm a bit new to the math behind Affine transformations but if I follow your equation correctly
And we should think about how bring users of the former behavior up to speed. Maybe we can raise an error or FutureWarning if only a scalar is provided as the shear parameter and expect a tuple of both shear angles from now on...
| return np.sqrt(np.sum(self.params ** 2, axis=0))[:self.dimensionality] | ||
| else: | ||
| ss = np.sum(self.params ** 2, axis=0)[:self.dimensionality] | ||
| ss[1] = ss[1] / (math.tan(self.shear)**2 + 1) |
There was a problem hiding this comment.
Could you help me understand what is happening here? Why do we suddenly need a different calculation for the 2D case? If the matrix in self.params is correct, the dimensionality shouldn't matter?
Also you have moved the the indexing with [:self.dimensionality] into the square root's argument; was that intentional?
There was a problem hiding this comment.
We are not allowed to access self.shear in other dimensionality since the shear parameter is supported only in the case of the 2D version.
See:
scikit-image/skimage/transform/_geometric.py
Lines 934 to 941 in de46b0f
Also you have moved the the indexing with [:self.dimensionality] into the square root's argument; was that intentional?
The result is identical. But I fixed this not to be confusing.
There was a problem hiding this comment.
Ah, I didn't notice that self.shear was only accessed in one case. However, I'm still confused. Why doesn't the
np.sqrt(np.sum(self.params ** 2, axis=0))[:self.dimensionality]work for the 2D case? Testing with
t = ski.transform.AffineTransform(translation=(3, 4), rotation=1, scale=(5, 6), shear=0.2)
np.sqrt(np.sum(t.params ** 2, axis=0))[:t.dimensionality]
# array([5. , 6.12203307])seems to return a wrong factor, although it's suspiciously not far off. t.scale (your calculation in 2a5e6f9) returns the correct result. I'm asking myself if the calculation is even correct for the other non-2D cases... 🤔
There was a problem hiding this comment.
OK. With the new definition of the self.params, I used the following equations:
# (pseudo code)
# For sx
params[0, 0] := sx * cos(rot)
params[1, 0] := sx * sin(rot)
# Calc square sum
sum(params[:, 0]**2)
-> sx**2 (cos(rot)**2 + sin(rot)**2)
-> sx**2
# Solving by sx
sx = sqrt(sum(params[:, 0]**2))
# For sy
params[0, 1] := -sy * (tan(shear) * cos(rot) + sin(rot))
params[1, 1] := -sy * (tan(shear) * sin(rot) - cos(rot))
# the square sum:
sum(params[:, 1]**2)
-> sy**2 (cos(rot)**2 + sin(rot)**2 + tan(shear)**2(cos(rot)**2 + sin(rot)**2))
-> sy**2 (1 + tan(shear)**2)
# Solving by sy
sy = sqrt(sum(params[:, 1]**2) / (1 + tan(shear**2)))
There was a problem hiding this comment.
That deduction seems correct. 👍
However, that the calculation for the 2D case is different from the "general ND" case leads me to believe that the latter may be wrong? Additionally, this property doesn't seem to be tested at all for non-2D cases.
@jni, you seem to have added ND support in #5188. Do you have more context concerning this calculation for ND matrices?
scikit-image/skimage/transform/_geometric.py
Line 924 in f4978b1
I don't consider this blocking for this PR. For the 2D case at least, I'm reasonably sure that this PR is "more" correct. For other cases it leaves the old behavior unchanged.
|
@lagru Hi, thank you for your review! I fixed some code and documentation.
I agree. Adding support for a y-direction shear is a nice idea, but I think the current implementation tries to support only the x-direction, so adding a shear_y is a new feature.
Yes, and I think we should care about the order of operations because matrix multiplication is generally noncommutative. |
|
@i-aki-y do you anticipate adding a second shear direction to be a lot more work?
After some back and forth I tend to agree with you and would be totally fine to split it into different PRs. I was already anticipating how we would adapt our API to support a second shear angle. If the goal is to be consistent with the other parameters, passing in a single scalar value would translate as passing in the same angle for horizontal and vertical shear. Migrating our API towards that behavior is difficult without going through a tedious deprecation cycle for users. We don't do warnings for bug fixes, so I was looking to avoid that by doing both fix and new feature in one sweep. But we could also just fix the old behavior, and only do the second shear transformation if two values are passed to |
|
@lagru I expect that the modification for the new feature is small. So if you prefer to include the feature in this PR, I can. Translating the single I am not sure this is a common case, but I am concerned that it causes some confusion.
So, I prefer this scenario.
This may be off-topic. I am not sure about skimage2, but if possible, I think the construction by method chaining is a good API that the matlibplot employed. This allows the user to change the operation order, which is a matter for affine transform because the different operation order makes different transforms even if all parameters are the same. trans = AffineTransform().translate(tx, ty).rotate(r).scale(sx, sy).shear(shx, shy)...I think this could be added without conflict with the current implementation, but different method names are needed because some of them are already used for the properties |
|
Wow, thanks for the great write-up! I really hadn't considered an API that allows successive application of transformation. I really like the concept of chaining operations. It's both explicit and flexible. And I also learned something new from your example on emulating y-shear with rotation.
No it's fine to keep it for another PR. You make a good argument to focus on the fix here, and to keep the behavior that a single scalar is interpreted as a shear in x-direction. We can worry about how and when to support the second dimension after that in another PR. Though I'd really like to add the functionality even if the API is gonna be a little awkward in the meantime. 🙏 |
|
@lagru Thank you for your comments. |
|
@lagru To clarify, I made a summary of the shear angle definition between the skimage and the Wikipedia definition. I missed the last step |
|
Sorry for taking my sweet time here. 🙏 |
lagru
left a comment
There was a problem hiding this comment.
I'm approving this. https://github.com/scikit-image/scikit-image/pull/6717/files#r1126511731 is still unresolved, but I don't consider it blocking for this PR which is a clear fix and improvement in my book! I've left a few suggestions, but none of them critical.
Thank you @i-aki-y. Your thorough and clear explanations were really useful and appreciated while reviewing this. 👌 Looking forward to #6752.
AffineTransform
|
I renamed to issue and PR title to be a bit more specific. Feel welcome to update, if you can think of a more expressive description. |
|
Thanks for looking into this @i-aki-y! It gets messy pretty quickly. Some of this comes down to the order in which operations are performed, but the current shear equation must be incorrect, just looking at the output: This is a good set of notes: https://people.computing.clemson.edu/~dhouse/courses/401/notes/affines-matrices.pdf I had a hard time trying to come up with the formulation given in this PR, though: This does not follow clearly from the Wikipedia article, or from the above. Minor, but also in the above formulation I think a2 and b2 should be translation_x, translation_y. I've implemented the different transformations in SymPy. If you can show me how the above formulation comes out of the below, I think we'd be in good shape to merge: Yields: I would love to get this in for the next release that is due within a few days. @i-aki-y if you can work with me over the next day or two, I'm confident we can get it in. /cc @ahojnnes, in case you wanted to take a look. |
|
@stefanv Thank you for your review. I think you can get the same form by replacing the variables: The relation between The This is my interpretation of your example. I think it is consistent with the documented definition: Note that the angle direction is slightly confusing, but we should take into account that the y-axis is vertically flipped. |
| X = a0*x + a1*y + a2 = | ||
| = sx*x*cos(rotation) - sy*y*sin(rotation + shear) + a2 | ||
| = sx*x*cos(rotation) - sy*y*(tan(shear) * sin(rotation) + sin(rotation)) + a2 | ||
|
|
||
| Y = b0*x + b1*y + b2 = | ||
| = sx*x*sin(rotation) + sy*y*cos(rotation + shear) + b2 | ||
| = sx*x*sin(rotation) - sy*y*(tan(shear) * sin(rotation) - cos(rotation)) + b2 |
There was a problem hiding this comment.
Modifying @stefanv's snippet according to #6717 (comment), I get the following:
import sympy as sp
s_x, s_y, theta, phi_x, h_x, h_y, x, y = sp.var(['S_x', 'S_y', 'theta', 'phi_x', 'h_x', 'h_y', 'x', 'y'])
scale = sp.Matrix([
[S_x, 0, 0],
[0, S_y, 0],
[0, 0, 1],
])
shear = sp.Matrix([
[1, -sp.tan(phi_x), 0],
[0, 1, 0],
[0, 0, 1],
])
rotate = sp.Matrix([
[sp.cos(theta), -sp.sin(theta), 0],
[sp.sin(theta), sp.cos(theta), 0],
[0, 0, 1],
])
p = sp.Matrix([[x], [y], [1]])
rotate * shear * scale * p # gives
# [S_x*x*cos(theta) + S_y*y*(-sin(theta) - cos(theta)*tan(phi_x))]
# [S_x*x*sin(theta) + S_y*y*(-sin(theta)*tan(phi_x) + cos(theta))]It seems to me that the only difference is the cos(theta)*tan(phi_x) / tan(shear) * sin(rotation) part in the first equation. You actually got this result in your original description #6717 (comment): the last part of the rendered equation seems correct while you than don't carry over the cos... 🤔
|
@stefanv @lagru Ah, I see. You are right. - sx*x*cos(rotation) - sy*y*(tan(shear) * sin(rotation) + sin(rotation))
+ sx*x*cos(rotation) - sy*y*(tan(shear) * cos(rotation) + sin(rotation))I fixed this and the namings of (a2 -> translation_x, b2 -> translation_y). Thanks. |
|
From the sources given in my last comment, it can be seen that adding y-shear is trivial, and adding 3D shear is quite feasible. I will get this in for now, but let's add that in a follow-up PR for completion (issue). |
Co-authored-by: Lars Grüter <[email protected]>
Co-authored-by: Lars Grüter <[email protected]>
d8326bf to
a86064f
Compare
|
🤯 We've been stating that the rotation angle is anti-clockwise for many releases, but that is not the case. Now, I think the updated docstrings are consistent: clockwise everywhere, including shear. |
I consider this to be a clockwise rotation of the y-axis. |
|
@i-aki-y If you can confirm that the angle descriptions are now correct, we can go ahead and merge. |
|
@stefanv OK. I checked some other methods that have a rotation parameter:
And I confirmed that the results are consistent with your definition. In this case, the direction is clockwise.
I agree. |
|
Thanks very much for this contribution @i-aki-y; it wasn't trivial to get all the details right, and I appreciate you doing all the necessary footwork. |
# 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


Description
In this PR, I would like to fix #3239.
I think the following document is not correct for the shear parameter.
scikit-image/skimage/transform/_geometric.py
Lines 717 to 724 in d3b8b6c
I rewrote the code with the following fixed equations:
I would appreciate if you review this PR.
Derivation
For simplicity, ignoring the scale and translation, we can rewrite the original equations:
However, the transformation matrix of rotation and shear should be the followings:
Here is a derivation:
where the$\theta$ and $\phi_x$ correspond to $R_\theta$ and $S_{\phi_x}$ depict rotation and shear matrices.
rotationandshear, andSo, the full expressions that include scale and translation will be:
In this PR, I rewrote the code by using the above equations.
Example
This is an example of a comparison between current and fixed shear transform.
Checklist
./doc/examples(new features only)./benchmarks, if your changes aren't covered by anexisting benchmark
For reviewers
later.
__init__.py.doc/release/release_dev.rst.example, to backport to v0.19.x after merging, add the following in a PR
comment:
@meeseeksdev backport to v0.19.xrun-benchmarklabel. To rerun, the labelcan be removed and then added again. The benchmark output can be checked in
the "Actions" tab.