Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- python_embeded/Lib/site-packages/kornia-0.8.1.dist-info/licenses/LICENSE +176 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/__init__.py +20 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/base.py +151 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/__init__.py +32 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/affine.py +156 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/base.py +305 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/center_crop.py +154 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/crop.py +321 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/elastic_transform.py +133 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/fisheye.py +101 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/horizontal_flip.py +99 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/pad.py +96 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/perspective.py +119 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/resize.py +151 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/resized_crop.py +160 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/rotation.py +232 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/shear.py +133 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/thin_plate_spline.py +88 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/translate.py +129 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/vertical_flip.py +91 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/auto_contrast.py +58 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/base.py +88 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/box_blur.py +72 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/brightness.py +93 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/channel_dropout.py +116 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/channel_shuffle.py +69 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/clahe.py +83 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/color_jiggle.py +113 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/color_jitter.py +192 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/contrast.py +92 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/denormalize.py +83 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/dissolving.py +75 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/equalize.py +69 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/erasing.py +113 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gamma.py +90 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_blur.py +130 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_illumination.py +204 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_noise.py +80 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/grayscale.py +84 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/hue.py +85 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/invert.py +74 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/jpeg.py +75 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/linear_illumination.py +237 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/median_blur.py +68 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/motion_blur.py +125 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/normalize.py +84 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/planckian_jitter.py +203 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_3d/__init__.py +20 -0
- python_embeded/Lib/site-packages/kornia/augmentation/_3d/base.py +138 -0
.gitattributes
CHANGED
|
@@ -331,3 +331,4 @@ python_embeded/Lib/site-packages/pip/_vendor/distlib/w64.exe filter=lfs diff=lfs
|
|
| 331 |
python_embeded/Lib/site-packages/pip/_vendor/distlib/w64-arm.exe filter=lfs diff=lfs merge=lfs -text
|
| 332 |
python_embeded/Lib/site-packages/numpy/random/lib/npyrandom.lib filter=lfs diff=lfs merge=lfs -text
|
| 333 |
python_embeded/Lib/site-packages/onnxruntime/capi/onnxruntime.dll filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 331 |
python_embeded/Lib/site-packages/pip/_vendor/distlib/w64-arm.exe filter=lfs diff=lfs merge=lfs -text
|
| 332 |
python_embeded/Lib/site-packages/numpy/random/lib/npyrandom.lib filter=lfs diff=lfs merge=lfs -text
|
| 333 |
python_embeded/Lib/site-packages/onnxruntime/capi/onnxruntime.dll filter=lfs diff=lfs merge=lfs -text
|
| 334 |
+
python_embeded/Lib/site-packages/numpy/core/lib/npymath.lib filter=lfs diff=lfs merge=lfs -text
|
python_embeded/Lib/site-packages/kornia-0.8.1.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from kornia.augmentation._2d.geometric import *
|
| 19 |
+
from kornia.augmentation._2d.intensity import *
|
| 20 |
+
from kornia.augmentation._2d.mix import *
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/base.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional
|
| 19 |
+
|
| 20 |
+
from torch import float16, float32, float64
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation.base import _AugmentationBase
|
| 23 |
+
from kornia.augmentation.utils import _transform_input, _transform_input_by_shape, _validate_input_dtype
|
| 24 |
+
from kornia.core import Tensor
|
| 25 |
+
from kornia.geometry.boxes import Boxes
|
| 26 |
+
from kornia.geometry.keypoints import Keypoints
|
| 27 |
+
from kornia.utils import eye_like, is_autocast_enabled
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class AugmentationBase2D(_AugmentationBase):
|
| 31 |
+
r"""AugmentationBase2D base class for customized augmentation implementations.
|
| 32 |
+
|
| 33 |
+
AugmentationBase2D aims at offering a generic base class for a greater level of customization.
|
| 34 |
+
If the subclass contains routined matrix-based transformations, `RigidAffineAugmentationBase2D`
|
| 35 |
+
might be a better fit.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
p: probability for applying an augmentation. This param controls the augmentation probabilities
|
| 39 |
+
element-wise for a batch.
|
| 40 |
+
p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
|
| 41 |
+
probabilities batch-wise.
|
| 42 |
+
same_on_batch: apply the same transformation across the batch.
|
| 43 |
+
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch
|
| 44 |
+
form ``False``.
|
| 45 |
+
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def validate_tensor(self, input: Tensor) -> None:
|
| 49 |
+
"""Check if the input tensor is formatted as expected."""
|
| 50 |
+
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
|
| 51 |
+
if len(input.shape) != 4:
|
| 52 |
+
raise RuntimeError(f"Expect (B, C, H, W). Got {input.shape}.")
|
| 53 |
+
|
| 54 |
+
def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor:
|
| 55 |
+
"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
|
| 56 |
+
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
|
| 57 |
+
|
| 58 |
+
if shape is None:
|
| 59 |
+
return _transform_input(input)
|
| 60 |
+
else:
|
| 61 |
+
return _transform_input_by_shape(input, reference_shape=shape, match_channel=match_channel)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class RigidAffineAugmentationBase2D(AugmentationBase2D):
|
| 65 |
+
r"""AugmentationBase2D base class for rigid/affine augmentation implementations.
|
| 66 |
+
|
| 67 |
+
RigidAffineAugmentationBase2D enables routined transformation with given transformation matrices
|
| 68 |
+
for different data types like masks, boxes, and keypoints.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
p: probability for applying an augmentation. This param controls the augmentation probabilities
|
| 72 |
+
element-wise for a batch.
|
| 73 |
+
p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
|
| 74 |
+
probabilities batch-wise.
|
| 75 |
+
same_on_batch: apply the same transformation across the batch.
|
| 76 |
+
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch
|
| 77 |
+
form ``False``.
|
| 78 |
+
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
_transform_matrix: Optional[Tensor]
|
| 82 |
+
|
| 83 |
+
@property
|
| 84 |
+
def transform_matrix(self) -> Optional[Tensor]:
|
| 85 |
+
return self._transform_matrix
|
| 86 |
+
|
| 87 |
+
def identity_matrix(self, input: Tensor) -> Tensor:
|
| 88 |
+
"""Return 3x3 identity matrix."""
|
| 89 |
+
return eye_like(3, input)
|
| 90 |
+
|
| 91 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 92 |
+
raise NotImplementedError
|
| 93 |
+
|
| 94 |
+
def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 95 |
+
"""Generate transformation matrices with the given input and param settings."""
|
| 96 |
+
batch_prob = params["batch_prob"]
|
| 97 |
+
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
|
| 98 |
+
|
| 99 |
+
in_tensor = self.transform_tensor(input)
|
| 100 |
+
if not to_apply.any():
|
| 101 |
+
trans_matrix = self.identity_matrix(in_tensor)
|
| 102 |
+
elif to_apply.all():
|
| 103 |
+
trans_matrix = self.compute_transformation(in_tensor, params=params, flags=flags)
|
| 104 |
+
else:
|
| 105 |
+
trans_matrix_A = self.identity_matrix(in_tensor)
|
| 106 |
+
trans_matrix_B = self.compute_transformation(in_tensor[to_apply], params=params, flags=flags)
|
| 107 |
+
|
| 108 |
+
if is_autocast_enabled():
|
| 109 |
+
trans_matrix_A = trans_matrix_A.type(input.dtype)
|
| 110 |
+
trans_matrix_B = trans_matrix_B.type(input.dtype)
|
| 111 |
+
|
| 112 |
+
trans_matrix = trans_matrix_A.index_put((to_apply,), trans_matrix_B)
|
| 113 |
+
|
| 114 |
+
return trans_matrix
|
| 115 |
+
|
| 116 |
+
def inverse_inputs(
|
| 117 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 118 |
+
) -> Tensor:
|
| 119 |
+
raise NotImplementedError
|
| 120 |
+
|
| 121 |
+
def inverse_masks(
|
| 122 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 123 |
+
) -> Tensor:
|
| 124 |
+
raise NotImplementedError
|
| 125 |
+
|
| 126 |
+
def inverse_boxes(
|
| 127 |
+
self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 128 |
+
) -> Boxes:
|
| 129 |
+
raise NotImplementedError
|
| 130 |
+
|
| 131 |
+
def inverse_keypoints(
|
| 132 |
+
self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 133 |
+
) -> Keypoints:
|
| 134 |
+
raise NotImplementedError
|
| 135 |
+
|
| 136 |
+
def inverse_classes(
|
| 137 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 138 |
+
) -> Tensor:
|
| 139 |
+
raise NotImplementedError
|
| 140 |
+
|
| 141 |
+
def apply_func(
|
| 142 |
+
self, in_tensor: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None
|
| 143 |
+
) -> Tensor:
|
| 144 |
+
if flags is None:
|
| 145 |
+
flags = self.flags
|
| 146 |
+
|
| 147 |
+
trans_matrix = self.generate_transformation_matrix(in_tensor, params, flags)
|
| 148 |
+
output = self.transform_inputs(in_tensor, params, flags, trans_matrix)
|
| 149 |
+
self._transform_matrix = trans_matrix
|
| 150 |
+
|
| 151 |
+
return output
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from kornia.augmentation._2d.geometric.affine import RandomAffine
|
| 19 |
+
from kornia.augmentation._2d.geometric.center_crop import CenterCrop
|
| 20 |
+
from kornia.augmentation._2d.geometric.crop import RandomCrop
|
| 21 |
+
from kornia.augmentation._2d.geometric.elastic_transform import RandomElasticTransform
|
| 22 |
+
from kornia.augmentation._2d.geometric.fisheye import RandomFisheye
|
| 23 |
+
from kornia.augmentation._2d.geometric.horizontal_flip import RandomHorizontalFlip
|
| 24 |
+
from kornia.augmentation._2d.geometric.pad import PadTo
|
| 25 |
+
from kornia.augmentation._2d.geometric.perspective import RandomPerspective
|
| 26 |
+
from kornia.augmentation._2d.geometric.resize import LongestMaxSize, Resize, SmallestMaxSize
|
| 27 |
+
from kornia.augmentation._2d.geometric.resized_crop import RandomResizedCrop
|
| 28 |
+
from kornia.augmentation._2d.geometric.rotation import RandomRotation, RandomRotation90
|
| 29 |
+
from kornia.augmentation._2d.geometric.shear import RandomShear
|
| 30 |
+
from kornia.augmentation._2d.geometric.thin_plate_spline import RandomThinPlateSpline
|
| 31 |
+
from kornia.augmentation._2d.geometric.translate import RandomTranslate
|
| 32 |
+
from kornia.augmentation._2d.geometric.vertical_flip import RandomVerticalFlip
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/affine.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
|
| 22 |
+
from kornia.constants import Resample, SamplePadding
|
| 23 |
+
from kornia.core import Tensor, as_tensor
|
| 24 |
+
from kornia.geometry.conversions import deg2rad
|
| 25 |
+
from kornia.geometry.transform import get_affine_matrix2d, warp_affine
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class RandomAffine(GeometricAugmentationBase2D):
|
| 29 |
+
r"""Apply a random 2D affine transformation to a tensor image.
|
| 30 |
+
|
| 31 |
+
.. image:: _static/img/RandomAffine.png
|
| 32 |
+
|
| 33 |
+
The transformation is computed so that the image center is kept invariant.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
degrees: Range of degrees to select from.
|
| 37 |
+
If degrees is a number instead of sequence like (min, max), the range of degrees
|
| 38 |
+
will be (-degrees, +degrees). Set to 0 to deactivate rotations.
|
| 39 |
+
translate: tuple of maximum absolute fraction for horizontal
|
| 40 |
+
and vertical translations. For example translate=(a, b), then horizontal shift
|
| 41 |
+
is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is
|
| 42 |
+
randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.
|
| 43 |
+
scale: scaling factor interval.
|
| 44 |
+
If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b.
|
| 45 |
+
If (a, b, c, d), the scale is randomly sampled from the range a <= scale_x <= b, c <= scale_y <= d.
|
| 46 |
+
Will keep original scale by default.
|
| 47 |
+
shear: Range of degrees to select from.
|
| 48 |
+
If float, a shear parallel to the x axis in the range (-shear, +shear) will be applied.
|
| 49 |
+
If (a, b), a shear parallel to the x axis in the range (-shear, +shear) will be applied.
|
| 50 |
+
If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3])
|
| 51 |
+
will be applied. Will not apply shear by default.
|
| 52 |
+
resample: resample mode from "nearest" (0) or "bilinear" (1).
|
| 53 |
+
padding_mode: padding mode from "zeros" (0), "border" (1) or "reflection" (2).
|
| 54 |
+
same_on_batch: apply the same transformation across the batch.
|
| 55 |
+
align_corners: interpolation flag.
|
| 56 |
+
p: probability of applying the transformation.
|
| 57 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False).
|
| 58 |
+
|
| 59 |
+
Shape:
|
| 60 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 61 |
+
- Output: :math:`(B, C, H, W)`
|
| 62 |
+
|
| 63 |
+
.. note::
|
| 64 |
+
This function internally uses :func:`kornia.geometry.transform.warp_affine`.
|
| 65 |
+
|
| 66 |
+
Examples:
|
| 67 |
+
>>> import torch
|
| 68 |
+
>>> rng = torch.manual_seed(0)
|
| 69 |
+
>>> input = torch.rand(1, 1, 3, 3)
|
| 70 |
+
>>> aug = RandomAffine((-15., 20.), p=1.)
|
| 71 |
+
>>> out = aug(input)
|
| 72 |
+
>>> out, aug.transform_matrix
|
| 73 |
+
(tensor([[[[0.3961, 0.7310, 0.1574],
|
| 74 |
+
[0.1781, 0.3074, 0.5648],
|
| 75 |
+
[0.4804, 0.8379, 0.4234]]]]), tensor([[[ 0.9923, -0.1241, 0.1319],
|
| 76 |
+
[ 0.1241, 0.9923, -0.1164],
|
| 77 |
+
[ 0.0000, 0.0000, 1.0000]]]))
|
| 78 |
+
>>> aug.inverse(out)
|
| 79 |
+
tensor([[[[0.3890, 0.6573, 0.1865],
|
| 80 |
+
[0.2063, 0.3074, 0.5459],
|
| 81 |
+
[0.3892, 0.7896, 0.4224]]]])
|
| 82 |
+
>>> input
|
| 83 |
+
tensor([[[[0.4963, 0.7682, 0.0885],
|
| 84 |
+
[0.1320, 0.3074, 0.6341],
|
| 85 |
+
[0.4901, 0.8964, 0.4556]]]])
|
| 86 |
+
|
| 87 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 88 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 89 |
+
>>> aug = RandomAffine((-15., 20.), p=1.)
|
| 90 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 91 |
+
tensor(True)
|
| 92 |
+
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
def __init__(
|
| 96 |
+
self,
|
| 97 |
+
degrees: Union[Tensor, float, Tuple[float, float]],
|
| 98 |
+
translate: Optional[Union[Tensor, Tuple[float, float]]] = None,
|
| 99 |
+
scale: Optional[Union[Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
|
| 100 |
+
shear: Optional[Union[Tensor, float, Tuple[float, float]]] = None,
|
| 101 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 102 |
+
same_on_batch: bool = False,
|
| 103 |
+
align_corners: bool = False,
|
| 104 |
+
padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name,
|
| 105 |
+
p: float = 0.5,
|
| 106 |
+
keepdim: bool = False,
|
| 107 |
+
) -> None:
|
| 108 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 109 |
+
self._param_generator: rg.AffineGenerator = rg.AffineGenerator(degrees, translate, scale, shear)
|
| 110 |
+
self.flags = {
|
| 111 |
+
"resample": Resample.get(resample),
|
| 112 |
+
"padding_mode": SamplePadding.get(padding_mode),
|
| 113 |
+
"align_corners": align_corners,
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 117 |
+
return get_affine_matrix2d(
|
| 118 |
+
as_tensor(params["translations"], device=input.device, dtype=input.dtype),
|
| 119 |
+
as_tensor(params["center"], device=input.device, dtype=input.dtype),
|
| 120 |
+
as_tensor(params["scale"], device=input.device, dtype=input.dtype),
|
| 121 |
+
as_tensor(params["angle"], device=input.device, dtype=input.dtype),
|
| 122 |
+
deg2rad(as_tensor(params["shear_x"], device=input.device, dtype=input.dtype)),
|
| 123 |
+
deg2rad(as_tensor(params["shear_y"], device=input.device, dtype=input.dtype)),
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def apply_transform(
|
| 127 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 128 |
+
) -> Tensor:
|
| 129 |
+
_, _, height, width = input.shape
|
| 130 |
+
if not isinstance(transform, Tensor):
|
| 131 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 132 |
+
|
| 133 |
+
return warp_affine(
|
| 134 |
+
input,
|
| 135 |
+
transform[:, :2, :],
|
| 136 |
+
(height, width),
|
| 137 |
+
flags["resample"].name.lower(),
|
| 138 |
+
align_corners=flags["align_corners"],
|
| 139 |
+
padding_mode=flags["padding_mode"].name.lower(),
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
def inverse_transform(
|
| 143 |
+
self,
|
| 144 |
+
input: Tensor,
|
| 145 |
+
flags: Dict[str, Any],
|
| 146 |
+
transform: Optional[Tensor] = None,
|
| 147 |
+
size: Optional[Tuple[int, int]] = None,
|
| 148 |
+
) -> Tensor:
|
| 149 |
+
if not isinstance(transform, Tensor):
|
| 150 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 151 |
+
return self.apply_transform(
|
| 152 |
+
input,
|
| 153 |
+
params=self._params,
|
| 154 |
+
transform=as_tensor(transform, device=input.device, dtype=input.dtype),
|
| 155 |
+
flags=flags,
|
| 156 |
+
)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/base.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D
|
| 21 |
+
from kornia.constants import Resample
|
| 22 |
+
from kornia.core import Tensor, as_tensor
|
| 23 |
+
from kornia.geometry.boxes import Boxes
|
| 24 |
+
from kornia.geometry.keypoints import Keypoints
|
| 25 |
+
from kornia.utils.helpers import _torch_inverse_cast
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
|
| 29 |
+
r"""GeometricAugmentationBase2D base class for customized geometric augmentation implementations.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
p: probability for applying an augmentation. This param controls the augmentation probabilities
|
| 33 |
+
element-wise for a batch.
|
| 34 |
+
p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
|
| 35 |
+
probabilities batch-wise.
|
| 36 |
+
same_on_batch: apply the same transformation across the batch.
|
| 37 |
+
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
|
| 38 |
+
to the batch form ``False``.
|
| 39 |
+
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def inverse_transform(
|
| 43 |
+
self,
|
| 44 |
+
input: Tensor,
|
| 45 |
+
flags: Dict[str, Any],
|
| 46 |
+
transform: Optional[Tensor] = None,
|
| 47 |
+
size: Optional[Tuple[int, int]] = None,
|
| 48 |
+
) -> Tensor:
|
| 49 |
+
"""By default, the exact transformation as ``apply_transform`` will be used."""
|
| 50 |
+
raise NotImplementedError
|
| 51 |
+
|
| 52 |
+
def compute_inverse_transformation(self, transform: Tensor) -> Tensor:
|
| 53 |
+
"""Compute the inverse transform of given transformation matrices."""
|
| 54 |
+
return _torch_inverse_cast(transform)
|
| 55 |
+
|
| 56 |
+
def get_transformation_matrix(
|
| 57 |
+
self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, flags: Optional[Dict[str, Any]] = None
|
| 58 |
+
) -> Tensor:
|
| 59 |
+
"""Obtain transformation matrices.
|
| 60 |
+
|
| 61 |
+
Return the current transformation matrix if existed. Generate a new one, otherwise.
|
| 62 |
+
"""
|
| 63 |
+
flags = self.flags if flags is None else flags
|
| 64 |
+
if params is not None:
|
| 65 |
+
transform = self.generate_transformation_matrix(input, params, flags)
|
| 66 |
+
elif self.transform_matrix is None:
|
| 67 |
+
params = self.forward_parameters(input.shape)
|
| 68 |
+
transform = self.generate_transformation_matrix(input, params, flags)
|
| 69 |
+
else:
|
| 70 |
+
transform = self.transform_matrix
|
| 71 |
+
return as_tensor(transform, device=input.device, dtype=input.dtype)
|
| 72 |
+
|
| 73 |
+
def apply_non_transform_mask(
|
| 74 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 75 |
+
) -> Tensor:
|
| 76 |
+
"""Process masks corresponding to the inputs that are no transformation applied."""
|
| 77 |
+
return input
|
| 78 |
+
|
| 79 |
+
def apply_transform_mask(
|
| 80 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 81 |
+
) -> Tensor:
|
| 82 |
+
"""Process masks corresponding to the inputs that are transformed.
|
| 83 |
+
|
| 84 |
+
Note:
|
| 85 |
+
Convert "resample" arguments to "nearest" by default.
|
| 86 |
+
|
| 87 |
+
"""
|
| 88 |
+
resample_method: Optional[Resample]
|
| 89 |
+
if "resample" in flags:
|
| 90 |
+
resample_method = flags["resample"]
|
| 91 |
+
flags["resample"] = Resample.get("nearest")
|
| 92 |
+
output = self.apply_transform(input, params, flags, transform)
|
| 93 |
+
if resample_method is not None:
|
| 94 |
+
flags["resample"] = resample_method
|
| 95 |
+
return output
|
| 96 |
+
|
| 97 |
+
def apply_non_transform_box(
|
| 98 |
+
self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 99 |
+
) -> Boxes:
|
| 100 |
+
"""Process boxes corresponding to the inputs that are no transformation applied."""
|
| 101 |
+
return input
|
| 102 |
+
|
| 103 |
+
def apply_transform_box(
|
| 104 |
+
self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 105 |
+
) -> Boxes:
|
| 106 |
+
"""Process boxes corresponding to the inputs that are transformed."""
|
| 107 |
+
if transform is None:
|
| 108 |
+
if self.transform_matrix is None:
|
| 109 |
+
raise RuntimeError("No valid transformation matrix found. Please either pass one or forward one first.")
|
| 110 |
+
transform = self.transform_matrix
|
| 111 |
+
input = self.apply_non_transform_box(input, params, flags, transform)
|
| 112 |
+
return input.transform_boxes_(transform)
|
| 113 |
+
|
| 114 |
+
def apply_non_transform_keypoint(
|
| 115 |
+
self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 116 |
+
) -> Keypoints:
|
| 117 |
+
"""Process keypoints corresponding to the inputs that are no transformation applied."""
|
| 118 |
+
return input
|
| 119 |
+
|
| 120 |
+
def apply_transform_keypoint(
|
| 121 |
+
self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 122 |
+
) -> Keypoints:
|
| 123 |
+
"""Process keypoints corresponding to the inputs that are transformed."""
|
| 124 |
+
if transform is None:
|
| 125 |
+
if self.transform_matrix is None:
|
| 126 |
+
raise RuntimeError("No valid transformation matrix found. Please either pass one or forward one first.")
|
| 127 |
+
transform = self.transform_matrix
|
| 128 |
+
input = self.apply_non_transform_keypoint(input, params, flags, transform)
|
| 129 |
+
return input.transform_keypoints_(transform)
|
| 130 |
+
|
| 131 |
+
def apply_non_transform_class(
|
| 132 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 133 |
+
) -> Tensor:
|
| 134 |
+
"""Process class tags corresponding to the inputs that are no transformation applied."""
|
| 135 |
+
return input
|
| 136 |
+
|
| 137 |
+
def apply_transform_class(
|
| 138 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 139 |
+
) -> Tensor:
|
| 140 |
+
"""Process class tags corresponding to the inputs that are transformed."""
|
| 141 |
+
return input
|
| 142 |
+
|
| 143 |
+
def inverse_inputs(
|
| 144 |
+
self,
|
| 145 |
+
input: Tensor,
|
| 146 |
+
params: Dict[str, Tensor],
|
| 147 |
+
flags: Dict[str, Any],
|
| 148 |
+
transform: Optional[Tensor] = None,
|
| 149 |
+
**kwargs: Any,
|
| 150 |
+
) -> Tensor:
|
| 151 |
+
in_tensor = self.transform_tensor(input)
|
| 152 |
+
output = in_tensor.clone()
|
| 153 |
+
batch_prob = params["batch_prob"]
|
| 154 |
+
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
|
| 155 |
+
|
| 156 |
+
params, flags = self._process_kwargs_to_params_and_flags(
|
| 157 |
+
self._params if params is None else params, flags, **kwargs
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
size: Optional[Tuple[int, int]] = None
|
| 161 |
+
if "forward_input_shape" in params:
|
| 162 |
+
# Majorly for cropping functions
|
| 163 |
+
_size = params["forward_input_shape"].tolist()
|
| 164 |
+
size = (_size[-2], _size[-1])
|
| 165 |
+
|
| 166 |
+
# if no augmentation needed
|
| 167 |
+
if not to_apply.any():
|
| 168 |
+
output = in_tensor
|
| 169 |
+
# if all data needs to be augmented
|
| 170 |
+
elif to_apply.all():
|
| 171 |
+
output = self.inverse_transform(in_tensor, flags=flags, transform=transform, size=size)
|
| 172 |
+
else:
|
| 173 |
+
output[to_apply] = self.inverse_transform(
|
| 174 |
+
in_tensor[to_apply],
|
| 175 |
+
transform=transform[to_apply] if transform is not None else transform,
|
| 176 |
+
size=size,
|
| 177 |
+
flags=flags,
|
| 178 |
+
)
|
| 179 |
+
return output
|
| 180 |
+
|
| 181 |
+
def inverse_masks(
|
| 182 |
+
self,
|
| 183 |
+
input: Tensor,
|
| 184 |
+
params: Dict[str, Tensor],
|
| 185 |
+
flags: Dict[str, Any],
|
| 186 |
+
transform: Optional[Tensor] = None,
|
| 187 |
+
**kwargs: Any,
|
| 188 |
+
) -> Tensor:
|
| 189 |
+
resample_method: Optional[Resample] = None
|
| 190 |
+
if "resample" in flags:
|
| 191 |
+
resample_method = flags["resample"]
|
| 192 |
+
flags["resample"] = Resample.get("nearest")
|
| 193 |
+
output = self.inverse_inputs(input, params, flags, transform, **kwargs)
|
| 194 |
+
if resample_method is not None:
|
| 195 |
+
flags["resample"] = resample_method
|
| 196 |
+
return output
|
| 197 |
+
|
| 198 |
+
def inverse_boxes(
|
| 199 |
+
self,
|
| 200 |
+
input: Boxes,
|
| 201 |
+
params: Dict[str, Tensor],
|
| 202 |
+
flags: Dict[str, Any],
|
| 203 |
+
transform: Optional[Tensor] = None,
|
| 204 |
+
**kwargs: Any,
|
| 205 |
+
) -> Boxes:
|
| 206 |
+
output = input.clone()
|
| 207 |
+
batch_prob = params["batch_prob"]
|
| 208 |
+
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
|
| 209 |
+
|
| 210 |
+
if transform is None:
|
| 211 |
+
raise RuntimeError("`transform` has to be a tensor. Got None.")
|
| 212 |
+
|
| 213 |
+
params, flags = self._process_kwargs_to_params_and_flags(
|
| 214 |
+
self._params if params is None else params, flags, **kwargs
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# if no augmentation needed
|
| 218 |
+
if not to_apply.any():
|
| 219 |
+
output = input
|
| 220 |
+
# if all data needs to be augmented
|
| 221 |
+
elif to_apply.all():
|
| 222 |
+
output = input.transform_boxes_(transform)
|
| 223 |
+
else:
|
| 224 |
+
output[to_apply] = input[to_apply].transform_boxes_(transform[to_apply])
|
| 225 |
+
|
| 226 |
+
return output
|
| 227 |
+
|
| 228 |
+
def inverse_keypoints(
|
| 229 |
+
self,
|
| 230 |
+
input: Keypoints,
|
| 231 |
+
params: Dict[str, Tensor],
|
| 232 |
+
flags: Dict[str, Any],
|
| 233 |
+
transform: Optional[Tensor] = None,
|
| 234 |
+
**kwargs: Any,
|
| 235 |
+
) -> Keypoints:
|
| 236 |
+
"""Inverse the transformation on keypoints.
|
| 237 |
+
|
| 238 |
+
Args:
|
| 239 |
+
input: input keypoints tensor or object.
|
| 240 |
+
params: the corresponding parameters for an operation.
|
| 241 |
+
flags: static parameters.
|
| 242 |
+
transform: the inverse transformation matrix
|
| 243 |
+
kwargs: additional arguments
|
| 244 |
+
|
| 245 |
+
"""
|
| 246 |
+
output = input.clone()
|
| 247 |
+
batch_prob = params["batch_prob"]
|
| 248 |
+
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
|
| 249 |
+
|
| 250 |
+
if transform is None:
|
| 251 |
+
raise RuntimeError("`transform` has to be a tensor. Got None.")
|
| 252 |
+
|
| 253 |
+
params, flags = self._process_kwargs_to_params_and_flags(
|
| 254 |
+
self._params if params is None else params, flags, **kwargs
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
# if no augmentation needed
|
| 258 |
+
if not to_apply.any():
|
| 259 |
+
output = input
|
| 260 |
+
# if all data needs to be augmented
|
| 261 |
+
elif to_apply.all():
|
| 262 |
+
output = input.transform_keypoints_(transform)
|
| 263 |
+
else:
|
| 264 |
+
output[to_apply] = input[to_apply].transform_keypoints_(transform[to_apply])
|
| 265 |
+
|
| 266 |
+
return output
|
| 267 |
+
|
| 268 |
+
def inverse_classes(
|
| 269 |
+
self,
|
| 270 |
+
input: Tensor,
|
| 271 |
+
params: Dict[str, Tensor],
|
| 272 |
+
flags: Dict[str, Any],
|
| 273 |
+
transform: Optional[Tensor] = None,
|
| 274 |
+
**kwargs: Any,
|
| 275 |
+
) -> Tensor:
|
| 276 |
+
return input
|
| 277 |
+
|
| 278 |
+
def inverse(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs: Any) -> Tensor:
|
| 279 |
+
"""Perform inverse operations.
|
| 280 |
+
|
| 281 |
+
Args:
|
| 282 |
+
input: the input tensor.
|
| 283 |
+
params: the corresponding parameters for an operation.
|
| 284 |
+
If None, a new parameter suite will be generated.
|
| 285 |
+
**kwargs: key-value pairs to override the parameters and flags.
|
| 286 |
+
|
| 287 |
+
"""
|
| 288 |
+
input_shape = input.shape
|
| 289 |
+
in_tensor = self.transform_tensor(input)
|
| 290 |
+
|
| 291 |
+
params, flags = self._process_kwargs_to_params_and_flags(
|
| 292 |
+
self._params if params is None else params, self.flags, **kwargs
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
if params is None:
|
| 296 |
+
params = self._params
|
| 297 |
+
transform = self.get_transformation_matrix(in_tensor, params=params, flags=flags)
|
| 298 |
+
|
| 299 |
+
transform = self.compute_inverse_transformation(transform)
|
| 300 |
+
output = self.inverse_inputs(in_tensor, params, flags, transform)
|
| 301 |
+
|
| 302 |
+
if self.keepdim:
|
| 303 |
+
return self.transform_output_tensor(output, input_shape)
|
| 304 |
+
|
| 305 |
+
return output
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/center_crop.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
|
| 22 |
+
from kornia.constants import Resample
|
| 23 |
+
from kornia.core import Tensor
|
| 24 |
+
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class CenterCrop(GeometricAugmentationBase2D):
|
| 28 |
+
r"""Crop a given image tensor at the center.
|
| 29 |
+
|
| 30 |
+
.. image:: _static/img/CenterCrop.png
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
size: Desired output size (out_h, out_w) of the crop.
|
| 34 |
+
If integer, out_h = out_w = size.
|
| 35 |
+
If Tuple[int, int], out_h = size[0], out_w = size[1].
|
| 36 |
+
align_corners: interpolation flag.
|
| 37 |
+
resample: The interpolation mode.
|
| 38 |
+
p: probability of applying the transformation for the whole batch.
|
| 39 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 40 |
+
to the batch form (False).
|
| 41 |
+
cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
|
| 42 |
+
on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
|
| 43 |
+
to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
|
| 44 |
+
differentiability.
|
| 45 |
+
|
| 46 |
+
Shape:
|
| 47 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 48 |
+
- Output: :math:`(B, C, out_h, out_w)`
|
| 49 |
+
|
| 50 |
+
.. note::
|
| 51 |
+
This function internally uses :func:`kornia.geometry.transform.crop_by_boxes`.
|
| 52 |
+
|
| 53 |
+
Examples:
|
| 54 |
+
>>> import torch
|
| 55 |
+
>>> rng = torch.manual_seed(0)
|
| 56 |
+
>>> inputs = torch.randn(1, 1, 4, 4)
|
| 57 |
+
>>> inputs
|
| 58 |
+
tensor([[[[-1.1258, -1.1524, -0.2506, -0.4339],
|
| 59 |
+
[ 0.8487, 0.6920, -0.3160, -2.1152],
|
| 60 |
+
[ 0.3223, -1.2633, 0.3500, 0.3081],
|
| 61 |
+
[ 0.1198, 1.2377, 1.1168, -0.2473]]]])
|
| 62 |
+
>>> aug = CenterCrop(2, p=1., cropping_mode="resample")
|
| 63 |
+
>>> out = aug(inputs)
|
| 64 |
+
>>> out
|
| 65 |
+
tensor([[[[ 0.6920, -0.3160],
|
| 66 |
+
[-1.2633, 0.3500]]]])
|
| 67 |
+
>>> aug.inverse(out, padding_mode="border")
|
| 68 |
+
tensor([[[[ 0.6920, 0.6920, -0.3160, -0.3160],
|
| 69 |
+
[ 0.6920, 0.6920, -0.3160, -0.3160],
|
| 70 |
+
[-1.2633, -1.2633, 0.3500, 0.3500],
|
| 71 |
+
[-1.2633, -1.2633, 0.3500, 0.3500]]]])
|
| 72 |
+
|
| 73 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 74 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 75 |
+
>>> aug = CenterCrop(2, p=1., cropping_mode="resample")
|
| 76 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 77 |
+
tensor(True)
|
| 78 |
+
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
def __init__(
|
| 82 |
+
self,
|
| 83 |
+
size: Union[int, Tuple[int, int]],
|
| 84 |
+
align_corners: bool = True,
|
| 85 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 86 |
+
p: float = 1.0,
|
| 87 |
+
keepdim: bool = False,
|
| 88 |
+
cropping_mode: str = "slice",
|
| 89 |
+
) -> None:
|
| 90 |
+
# same_on_batch is always True for CenterCrop
|
| 91 |
+
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
|
| 92 |
+
super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim)
|
| 93 |
+
if isinstance(size, tuple):
|
| 94 |
+
self.size = (size[0], size[1])
|
| 95 |
+
elif isinstance(size, int):
|
| 96 |
+
self.size = (size, size)
|
| 97 |
+
else:
|
| 98 |
+
raise Exception(f"Invalid size type. Expected (int, tuple(int, int). Got: {type(size)}.")
|
| 99 |
+
|
| 100 |
+
self.flags = {
|
| 101 |
+
"resample": Resample.get(resample),
|
| 102 |
+
"cropping_mode": cropping_mode,
|
| 103 |
+
"align_corners": align_corners,
|
| 104 |
+
"size": self.size,
|
| 105 |
+
"padding_mode": "zeros",
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
|
| 109 |
+
return rg.center_crop_generator(batch_shape[0], batch_shape[-2], batch_shape[-1], self.size, self.device)
|
| 110 |
+
|
| 111 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 112 |
+
if flags["cropping_mode"] in ("resample", "slice"):
|
| 113 |
+
transform: Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
|
| 114 |
+
transform = transform.expand(input.shape[0], -1, -1)
|
| 115 |
+
return transform
|
| 116 |
+
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
|
| 117 |
+
|
| 118 |
+
def apply_transform(
|
| 119 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 120 |
+
) -> Tensor:
|
| 121 |
+
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
|
| 122 |
+
if not isinstance(transform, Tensor):
|
| 123 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 124 |
+
|
| 125 |
+
return crop_by_transform_mat(
|
| 126 |
+
input, transform[:, :2, :], self.size, flags["resample"].name.lower(), "zeros", flags["align_corners"]
|
| 127 |
+
)
|
| 128 |
+
if flags["cropping_mode"] == "slice": # uses advanced slicing to crop
|
| 129 |
+
return crop_by_indices(input, params["src"], flags["size"])
|
| 130 |
+
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
|
| 131 |
+
|
| 132 |
+
def inverse_transform(
|
| 133 |
+
self,
|
| 134 |
+
input: Tensor,
|
| 135 |
+
flags: Dict[str, Any],
|
| 136 |
+
transform: Optional[Tensor] = None,
|
| 137 |
+
size: Optional[Tuple[int, int]] = None,
|
| 138 |
+
) -> Tensor:
|
| 139 |
+
if flags["cropping_mode"] != "resample":
|
| 140 |
+
raise NotImplementedError(
|
| 141 |
+
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
|
| 142 |
+
)
|
| 143 |
+
if size is None:
|
| 144 |
+
size = self.size
|
| 145 |
+
if not isinstance(transform, Tensor):
|
| 146 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 147 |
+
return crop_by_transform_mat(
|
| 148 |
+
input,
|
| 149 |
+
transform[:, :2, :],
|
| 150 |
+
size,
|
| 151 |
+
flags["resample"].name.lower(),
|
| 152 |
+
flags["padding_mode"],
|
| 153 |
+
flags["align_corners"],
|
| 154 |
+
)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/crop.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation import random_generator as rg
|
| 23 |
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
|
| 24 |
+
from kornia.constants import Resample
|
| 25 |
+
from kornia.core import Tensor, pad, tensor
|
| 26 |
+
from kornia.geometry.boxes import Boxes
|
| 27 |
+
from kornia.geometry.keypoints import Keypoints
|
| 28 |
+
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class RandomCrop(GeometricAugmentationBase2D):
|
| 32 |
+
r"""Crop random patches of a tensor image on a given size.
|
| 33 |
+
|
| 34 |
+
.. image:: _static/img/RandomCrop.png
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
size: Desired output size (out_h, out_w) of the crop.
|
| 38 |
+
Must be Tuple[int, int], then out_h = size[0], out_w = size[1].
|
| 39 |
+
padding: Optional padding on each border
|
| 40 |
+
of the image. Default is None, i.e no padding. If a sequence of length
|
| 41 |
+
4 is provided, it is used to pad left, top, right, bottom borders
|
| 42 |
+
respectively. If a sequence of length 2 is provided, it is used to
|
| 43 |
+
pad left/right, top/bottom borders, respectively.
|
| 44 |
+
pad_if_needed: It will pad the image if smaller than the
|
| 45 |
+
desired size to avoid raising an exception. Since cropping is done
|
| 46 |
+
after padding, the padding seems to be done at a random offset.
|
| 47 |
+
fill: Pixel fill value for constant fill. Default is 0. If a tuple of
|
| 48 |
+
length 3, it is used to fill R, G, B channels respectively.
|
| 49 |
+
This value is only used when the padding_mode is constant.
|
| 50 |
+
padding_mode: Type of padding. Should be: constant, reflect, replicate.
|
| 51 |
+
resample: the interpolation mode.
|
| 52 |
+
same_on_batch: apply the same transformation across the batch.
|
| 53 |
+
align_corners: interpolation flag.
|
| 54 |
+
p: probability of applying the transformation for the whole batch.
|
| 55 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 56 |
+
to the batch form (False).
|
| 57 |
+
cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
|
| 58 |
+
on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
|
| 59 |
+
to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
|
| 60 |
+
differentiability.
|
| 61 |
+
|
| 62 |
+
Shape:
|
| 63 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 64 |
+
- Output: :math:`(B, C, out_h, out_w)`
|
| 65 |
+
|
| 66 |
+
Note:
|
| 67 |
+
Input tensor must be float and normalized into [0, 1] for the best differentiability support.
|
| 68 |
+
Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
|
| 69 |
+
applied transformation will be merged int to the input transformation tensor and returned.
|
| 70 |
+
|
| 71 |
+
Examples:
|
| 72 |
+
>>> import torch
|
| 73 |
+
>>> _ = torch.manual_seed(0)
|
| 74 |
+
>>> inputs = torch.arange(1*1*3*3.).view(1, 1, 3, 3)
|
| 75 |
+
>>> aug = RandomCrop((2, 2), p=1., cropping_mode="resample")
|
| 76 |
+
>>> out = aug(inputs)
|
| 77 |
+
>>> out
|
| 78 |
+
tensor([[[[3., 4.],
|
| 79 |
+
[6., 7.]]]])
|
| 80 |
+
>>> aug.inverse(out, padding_mode="replicate")
|
| 81 |
+
tensor([[[[3., 4., 4.],
|
| 82 |
+
[3., 4., 4.],
|
| 83 |
+
[6., 7., 7.]]]])
|
| 84 |
+
|
| 85 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 86 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 87 |
+
>>> aug = RandomCrop((2, 2), p=1., cropping_mode="resample")
|
| 88 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 89 |
+
tensor(True)
|
| 90 |
+
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
size: Tuple[int, int],
|
| 96 |
+
padding: Optional[Union[int, Tuple[int, int], Tuple[int, int, int, int]]] = None,
|
| 97 |
+
pad_if_needed: Optional[bool] = False,
|
| 98 |
+
fill: int = 0,
|
| 99 |
+
padding_mode: str = "constant",
|
| 100 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 101 |
+
same_on_batch: bool = False,
|
| 102 |
+
align_corners: bool = True,
|
| 103 |
+
p: float = 1.0,
|
| 104 |
+
keepdim: bool = False,
|
| 105 |
+
cropping_mode: str = "slice",
|
| 106 |
+
) -> None:
|
| 107 |
+
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
|
| 108 |
+
super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
|
| 109 |
+
self._param_generator = rg.CropGenerator(size)
|
| 110 |
+
self.flags = {
|
| 111 |
+
"size": size,
|
| 112 |
+
"padding": padding,
|
| 113 |
+
"pad_if_needed": pad_if_needed,
|
| 114 |
+
"fill": fill,
|
| 115 |
+
"padding_mode": padding_mode,
|
| 116 |
+
"resample": Resample.get(resample),
|
| 117 |
+
"align_corners": align_corners,
|
| 118 |
+
"cropping_mode": cropping_mode,
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
def compute_padding(self, shape: Tuple[int, ...], flags: Optional[Dict[str, Any]] = None) -> List[int]:
|
| 122 |
+
flags = self.flags if flags is None else flags
|
| 123 |
+
if len(shape) != 4:
|
| 124 |
+
raise AssertionError(f"Expected BCHW. Got {shape}.")
|
| 125 |
+
padding = [0, 0, 0, 0] # left, right, top, bottom
|
| 126 |
+
if flags["padding"] is not None:
|
| 127 |
+
if isinstance(flags["padding"], int):
|
| 128 |
+
padding = [flags["padding"]] * 4
|
| 129 |
+
elif isinstance(flags["padding"], tuple) and len(flags["padding"]) == 2:
|
| 130 |
+
padding = [flags["padding"][0], flags["padding"][0], flags["padding"][1], flags["padding"][1]]
|
| 131 |
+
elif isinstance(flags["padding"], tuple) and len(flags["padding"]) == 4:
|
| 132 |
+
padding = [flags["padding"][0], flags["padding"][2], flags["padding"][1], flags["padding"][3]]
|
| 133 |
+
else:
|
| 134 |
+
raise RuntimeError(f"Expect `padding` to be a scalar, or length 2/4 list. Got {flags['padding']}.")
|
| 135 |
+
|
| 136 |
+
if flags["pad_if_needed"]:
|
| 137 |
+
needed_padding: Tuple[int, int] = (flags["size"][0] - shape[-2], flags["size"][1] - shape[-1]) # HW
|
| 138 |
+
# If crop width is larger than input width pad equally left and right
|
| 139 |
+
if needed_padding[1] > 0:
|
| 140 |
+
# Only use the extra padding if actually needed after possible fixed padding
|
| 141 |
+
padding[0] = max(needed_padding[1], padding[0])
|
| 142 |
+
padding[1] = max(needed_padding[1], padding[1])
|
| 143 |
+
# If crop height is larger than input height pad equally top and bottom
|
| 144 |
+
if needed_padding[0] > 0:
|
| 145 |
+
# Only use the extra padding if actually needed after possible fixed padding
|
| 146 |
+
padding[2] = max(needed_padding[0], padding[2])
|
| 147 |
+
padding[3] = max(needed_padding[0], padding[3])
|
| 148 |
+
return padding
|
| 149 |
+
|
| 150 |
+
def precrop_padding(
|
| 151 |
+
self, input: Tensor, padding: Optional[List[int]] = None, flags: Optional[Dict[str, Any]] = None
|
| 152 |
+
) -> Tensor:
|
| 153 |
+
flags = self.flags if flags is None else flags
|
| 154 |
+
if padding is None:
|
| 155 |
+
padding = self.compute_padding(input.shape)
|
| 156 |
+
|
| 157 |
+
if any(padding):
|
| 158 |
+
input = pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
|
| 159 |
+
|
| 160 |
+
return input
|
| 161 |
+
|
| 162 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 163 |
+
if flags["cropping_mode"] in ("resample", "slice"):
|
| 164 |
+
transform: Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
|
| 165 |
+
return transform
|
| 166 |
+
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
|
| 167 |
+
|
| 168 |
+
def apply_transform_keypoint(
|
| 169 |
+
self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 170 |
+
) -> Keypoints:
|
| 171 |
+
"""Process keypoints corresponding to the inputs that are no transformation applied."""
|
| 172 |
+
# For pad the keypoints properly.
|
| 173 |
+
padding_size = params["padding_size"].to(device=input.device)
|
| 174 |
+
input = input.pad(padding_size)
|
| 175 |
+
return super().apply_transform_keypoint(input=input, params=params, flags=flags, transform=transform)
|
| 176 |
+
|
| 177 |
+
def apply_transform_box(
|
| 178 |
+
self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 179 |
+
) -> Boxes:
|
| 180 |
+
"""Process keypoints corresponding to the inputs that are no transformation applied."""
|
| 181 |
+
# For pad the boxes properly.
|
| 182 |
+
padding_size = params["padding_size"]
|
| 183 |
+
input = input.pad(padding_size)
|
| 184 |
+
return super().apply_transform_box(input=input, params=params, flags=flags, transform=transform)
|
| 185 |
+
|
| 186 |
+
def apply_transform(
|
| 187 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 188 |
+
) -> Tensor:
|
| 189 |
+
padding_size: Optional[List[int]] = None
|
| 190 |
+
if "padding_size" in params and isinstance(params["padding_size"], Tensor):
|
| 191 |
+
padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().tolist()
|
| 192 |
+
input = self.precrop_padding(input, padding_size, flags)
|
| 193 |
+
|
| 194 |
+
flags = self.flags if flags is None else flags
|
| 195 |
+
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
|
| 196 |
+
if not isinstance(transform, Tensor):
|
| 197 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 198 |
+
# Fit the arg to F.pad
|
| 199 |
+
if flags["padding_mode"] == "constant":
|
| 200 |
+
padding_mode = "zeros"
|
| 201 |
+
elif flags["padding_mode"] == "replicate":
|
| 202 |
+
padding_mode = "border"
|
| 203 |
+
elif flags["padding_mode"] == "reflect":
|
| 204 |
+
padding_mode = "reflection"
|
| 205 |
+
else:
|
| 206 |
+
padding_mode = flags["padding_mode"]
|
| 207 |
+
|
| 208 |
+
return crop_by_transform_mat(
|
| 209 |
+
input,
|
| 210 |
+
transform,
|
| 211 |
+
flags["size"],
|
| 212 |
+
mode=flags["resample"].name.lower(),
|
| 213 |
+
padding_mode=padding_mode,
|
| 214 |
+
align_corners=flags["align_corners"],
|
| 215 |
+
)
|
| 216 |
+
if flags["cropping_mode"] == "slice": # uses advanced slicing to crop
|
| 217 |
+
return crop_by_indices(input, params["src"], flags["size"])
|
| 218 |
+
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
|
| 219 |
+
|
| 220 |
+
def inverse_transform(
|
| 221 |
+
self,
|
| 222 |
+
input: Tensor,
|
| 223 |
+
flags: Dict[str, Any],
|
| 224 |
+
transform: Optional[Tensor] = None,
|
| 225 |
+
size: Optional[Tuple[int, int]] = None,
|
| 226 |
+
) -> Tensor:
|
| 227 |
+
if flags["cropping_mode"] != "resample":
|
| 228 |
+
raise NotImplementedError(
|
| 229 |
+
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
|
| 230 |
+
)
|
| 231 |
+
if size is None:
|
| 232 |
+
raise RuntimeError("`size` has to be a tuple. Got None.")
|
| 233 |
+
if not isinstance(transform, Tensor):
|
| 234 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 235 |
+
# Fit the arg to F.pad
|
| 236 |
+
if flags["padding_mode"] == "constant":
|
| 237 |
+
padding_mode = "zeros"
|
| 238 |
+
elif flags["padding_mode"] == "replicate":
|
| 239 |
+
padding_mode = "border"
|
| 240 |
+
elif flags["padding_mode"] == "reflect":
|
| 241 |
+
padding_mode = "reflection"
|
| 242 |
+
else:
|
| 243 |
+
padding_mode = flags["padding_mode"]
|
| 244 |
+
return crop_by_transform_mat(
|
| 245 |
+
input,
|
| 246 |
+
transform[:, :2, :],
|
| 247 |
+
size,
|
| 248 |
+
flags["resample"].name.lower(),
|
| 249 |
+
padding_mode=padding_mode,
|
| 250 |
+
align_corners=flags["align_corners"],
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
def inverse_inputs(
|
| 254 |
+
self,
|
| 255 |
+
input: Tensor,
|
| 256 |
+
params: Dict[str, Tensor],
|
| 257 |
+
flags: Dict[str, Any],
|
| 258 |
+
transform: Optional[Tensor] = None,
|
| 259 |
+
**kwargs: Any,
|
| 260 |
+
) -> Tensor:
|
| 261 |
+
if flags["cropping_mode"] != "resample":
|
| 262 |
+
raise NotImplementedError(
|
| 263 |
+
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
|
| 264 |
+
)
|
| 265 |
+
out = super().inverse_inputs(input, params, flags, transform, **kwargs)
|
| 266 |
+
if not params["batch_prob"].all():
|
| 267 |
+
return out
|
| 268 |
+
padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().tolist()
|
| 269 |
+
padding_size = [-padding_size[0], -padding_size[1], -padding_size[2], -padding_size[3]]
|
| 270 |
+
return self.precrop_padding(out, padding_size)
|
| 271 |
+
|
| 272 |
+
def inverse_boxes(
|
| 273 |
+
self,
|
| 274 |
+
input: Boxes,
|
| 275 |
+
params: Dict[str, Tensor],
|
| 276 |
+
flags: Dict[str, Any],
|
| 277 |
+
transform: Optional[Tensor] = None,
|
| 278 |
+
**kwargs: Any,
|
| 279 |
+
) -> Boxes:
|
| 280 |
+
if flags["cropping_mode"] != "resample":
|
| 281 |
+
raise NotImplementedError(
|
| 282 |
+
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
|
| 283 |
+
)
|
| 284 |
+
output = super().inverse_boxes(input, params, flags, transform, **kwargs)
|
| 285 |
+
if not params["batch_prob"].all():
|
| 286 |
+
return output
|
| 287 |
+
|
| 288 |
+
return output.unpad(params["padding_size"])
|
| 289 |
+
|
| 290 |
+
def inverse_keypoints(
|
| 291 |
+
self,
|
| 292 |
+
input: Keypoints,
|
| 293 |
+
params: Dict[str, Tensor],
|
| 294 |
+
flags: Dict[str, Any],
|
| 295 |
+
transform: Optional[Tensor] = None,
|
| 296 |
+
**kwargs: Any,
|
| 297 |
+
) -> Keypoints:
|
| 298 |
+
if flags["cropping_mode"] != "resample":
|
| 299 |
+
raise NotImplementedError(
|
| 300 |
+
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
|
| 301 |
+
)
|
| 302 |
+
output = super().inverse_keypoints(input, params, flags, transform, **kwargs)
|
| 303 |
+
if not params["batch_prob"].all():
|
| 304 |
+
return output
|
| 305 |
+
|
| 306 |
+
return output.unpad(params["padding_size"].to(device=input.device))
|
| 307 |
+
|
| 308 |
+
# Override parameters for precrop
|
| 309 |
+
def forward_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
|
| 310 |
+
input_pad = self.compute_padding(batch_shape)
|
| 311 |
+
batch_shape_new = torch.Size(
|
| 312 |
+
(
|
| 313 |
+
*batch_shape[:2],
|
| 314 |
+
batch_shape[2] + input_pad[2] + input_pad[3], # original height + top + bottom padding
|
| 315 |
+
batch_shape[3] + input_pad[0] + input_pad[1], # original width + left + right padding
|
| 316 |
+
)
|
| 317 |
+
)
|
| 318 |
+
padding_size = tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)
|
| 319 |
+
_params = super().forward_parameters(batch_shape_new)
|
| 320 |
+
_params.update({"padding_size": padding_size})
|
| 321 |
+
return _params
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/elastic_transform.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation._2d.base import AugmentationBase2D
|
| 23 |
+
from kornia.constants import Resample
|
| 24 |
+
from kornia.core import Tensor
|
| 25 |
+
from kornia.geometry.boxes import Boxes
|
| 26 |
+
from kornia.geometry.transform import elastic_transform2d
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class RandomElasticTransform(AugmentationBase2D):
|
| 30 |
+
r"""Add random elastic transformation to a tensor image.
|
| 31 |
+
|
| 32 |
+
.. image:: _static/img/RandomElasticTransform.png
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
kernel_size: the size of the Gaussian kernel.
|
| 36 |
+
sigma: The standard deviation of the Gaussian in the y and x directions,
|
| 37 |
+
respectively. Larger sigma results in smaller pixel displacements.
|
| 38 |
+
alpha: The scaling factor that controls the intensity of the deformation
|
| 39 |
+
in the y and x directions, respectively.
|
| 40 |
+
align_corners: Interpolation flag used by `grid_sample`.
|
| 41 |
+
resample: Interpolation mode used by `grid_sample`. Either 'nearest' (0) or 'bilinear' (1).
|
| 42 |
+
padding_mode: The padding used by ```grid_sample```. Either 'zeros', 'border' or 'refection'.
|
| 43 |
+
same_on_batch: apply the same transformation across the batch.
|
| 44 |
+
p: probability of applying the transformation.
|
| 45 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 46 |
+
to the batch form (False).
|
| 47 |
+
|
| 48 |
+
.. note::
|
| 49 |
+
This function internally uses :func:`kornia.geometry.transform.elastic_transform2d`.
|
| 50 |
+
|
| 51 |
+
Examples:
|
| 52 |
+
>>> import torch
|
| 53 |
+
>>> img = torch.ones(1, 1, 2, 2)
|
| 54 |
+
>>> out = RandomElasticTransform()(img)
|
| 55 |
+
>>> out.shape
|
| 56 |
+
torch.Size([1, 1, 2, 2])
|
| 57 |
+
|
| 58 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 59 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 60 |
+
>>> aug = RandomElasticTransform(p=1.)
|
| 61 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 62 |
+
tensor(True)
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
def __init__(
|
| 67 |
+
self,
|
| 68 |
+
kernel_size: Tuple[int, int] = (63, 63),
|
| 69 |
+
sigma: Tuple[float, float] = (32.0, 32.0),
|
| 70 |
+
alpha: Tuple[float, float] = (1.0, 1.0),
|
| 71 |
+
align_corners: bool = False,
|
| 72 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 73 |
+
padding_mode: str = "zeros",
|
| 74 |
+
same_on_batch: bool = False,
|
| 75 |
+
p: float = 0.5,
|
| 76 |
+
keepdim: bool = False,
|
| 77 |
+
) -> None:
|
| 78 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 79 |
+
|
| 80 |
+
self.flags = {
|
| 81 |
+
"kernel_size": kernel_size,
|
| 82 |
+
"sigma": sigma,
|
| 83 |
+
"alpha": alpha,
|
| 84 |
+
"align_corners": align_corners,
|
| 85 |
+
"resample": Resample.get(resample),
|
| 86 |
+
"padding_mode": padding_mode,
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:
|
| 90 |
+
B, _, H, W = shape
|
| 91 |
+
if self.same_on_batch:
|
| 92 |
+
noise = torch.rand(1, 2, H, W, device=self.device, dtype=self.dtype).expand(B, 2, H, W)
|
| 93 |
+
else:
|
| 94 |
+
noise = torch.rand(B, 2, H, W, device=self.device, dtype=self.dtype)
|
| 95 |
+
return {"noise": noise * 2 - 1}
|
| 96 |
+
|
| 97 |
+
def apply_transform(
|
| 98 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 99 |
+
) -> Tensor:
|
| 100 |
+
return elastic_transform2d(
|
| 101 |
+
input,
|
| 102 |
+
params["noise"].to(input),
|
| 103 |
+
flags["kernel_size"],
|
| 104 |
+
flags["sigma"],
|
| 105 |
+
flags["alpha"],
|
| 106 |
+
flags["align_corners"],
|
| 107 |
+
flags["resample"].name.lower(),
|
| 108 |
+
flags["padding_mode"],
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def apply_non_transform_mask(
|
| 112 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 113 |
+
) -> Tensor:
|
| 114 |
+
return input
|
| 115 |
+
|
| 116 |
+
def apply_transform_mask(
|
| 117 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 118 |
+
) -> Tensor:
|
| 119 |
+
"""Process masks corresponding to the inputs that are transformed."""
|
| 120 |
+
return self.apply_transform(input, params=params, flags=flags, transform=transform)
|
| 121 |
+
|
| 122 |
+
def apply_transform_box(
|
| 123 |
+
self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 124 |
+
) -> Boxes:
|
| 125 |
+
"""Process masks corresponding to the inputs that are transformed."""
|
| 126 |
+
# We assume that boxes may not be affected too much by the deformation.
|
| 127 |
+
return input
|
| 128 |
+
|
| 129 |
+
def apply_transform_class(
|
| 130 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 131 |
+
) -> Tensor:
|
| 132 |
+
"""Process class tags corresponding to the inputs that are transformed."""
|
| 133 |
+
return input
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/fisheye.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.base import AugmentationBase2D
|
| 22 |
+
from kornia.core import Tensor
|
| 23 |
+
from kornia.geometry.transform import remap
|
| 24 |
+
from kornia.utils import create_meshgrid
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RandomFisheye(AugmentationBase2D):
|
| 28 |
+
r"""Add random camera radial distortion.
|
| 29 |
+
|
| 30 |
+
.. image:: _static/img/RandomFisheye.png
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
center_x: Ranges to sample respect to x-coordinate center with shape (2,).
|
| 34 |
+
center_y: Ranges to sample respect to y-coordinate center with shape (2,).
|
| 35 |
+
gamma: Ranges to sample for the gamma values respect to optical center with shape (2,).
|
| 36 |
+
same_on_batch: apply the same transformation across the batch.
|
| 37 |
+
p: probability of applying the transformation.
|
| 38 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 39 |
+
to the batch form (False).
|
| 40 |
+
|
| 41 |
+
Examples:
|
| 42 |
+
>>> import torch
|
| 43 |
+
>>> img = torch.ones(1, 1, 2, 2)
|
| 44 |
+
>>> center_x = torch.tensor([-.3, .3])
|
| 45 |
+
>>> center_y = torch.tensor([-.3, .3])
|
| 46 |
+
>>> gamma = torch.tensor([.9, 1.])
|
| 47 |
+
>>> out = RandomFisheye(center_x, center_y, gamma)(img)
|
| 48 |
+
>>> out.shape
|
| 49 |
+
torch.Size([1, 1, 2, 2])
|
| 50 |
+
|
| 51 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 52 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 53 |
+
>>> aug = RandomFisheye(center_x, center_y, gamma, p=1.)
|
| 54 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 55 |
+
tensor(True)
|
| 56 |
+
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
center_x: Tensor,
|
| 62 |
+
center_y: Tensor,
|
| 63 |
+
gamma: Tensor,
|
| 64 |
+
same_on_batch: bool = False,
|
| 65 |
+
p: float = 0.5,
|
| 66 |
+
keepdim: bool = False,
|
| 67 |
+
) -> None:
|
| 68 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 69 |
+
self._check_tensor(center_x)
|
| 70 |
+
self._check_tensor(center_y)
|
| 71 |
+
self._check_tensor(gamma)
|
| 72 |
+
self._param_generator = rg.PlainUniformGenerator(
|
| 73 |
+
(center_x[:, None], "center_x", None, None),
|
| 74 |
+
(center_y[:, None], "center_y", None, None),
|
| 75 |
+
(gamma[:, None], "gamma", None, None),
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
def _check_tensor(self, data: Tensor) -> None:
|
| 79 |
+
if not isinstance(data, Tensor):
|
| 80 |
+
raise TypeError(f"Invalid input type. Expected Tensor - got: {type(data)}")
|
| 81 |
+
|
| 82 |
+
if len(data.shape) != 1 and data.shape[0] != 2:
|
| 83 |
+
raise ValueError(f"Tensor must be of shape (2,). Got: {data.shape}.")
|
| 84 |
+
|
| 85 |
+
def apply_transform(
|
| 86 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 87 |
+
) -> Tensor:
|
| 88 |
+
# create the initial sampling fields
|
| 89 |
+
B, _, H, W = input.shape
|
| 90 |
+
grid = create_meshgrid(H, W, normalized_coordinates=True)
|
| 91 |
+
field_x = grid[..., 0].to(input) # 1xHxW
|
| 92 |
+
field_y = grid[..., 1].to(input) # 1xHxW
|
| 93 |
+
# vectorize the random parameters
|
| 94 |
+
center_x = params["center_x"].view(B, 1, 1).to(input)
|
| 95 |
+
center_y = params["center_y"].view(B, 1, 1).to(input)
|
| 96 |
+
gamma = params["gamma"].view(B, 1, 1).to(input)
|
| 97 |
+
# compute and apply the distances respect to the camera optical center
|
| 98 |
+
distance = ((center_x - field_x) ** 2 + (center_y - field_y) ** 2) ** 0.5
|
| 99 |
+
field_x = field_x + field_x * distance**gamma # BxHxw
|
| 100 |
+
field_y = field_y + field_y * distance**gamma # BxHxW
|
| 101 |
+
return remap(input, field_x, field_y, normalized_coordinates=True, align_corners=True)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/horizontal_flip.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from torch import Tensor
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
|
| 23 |
+
from kornia.core import as_tensor, tensor
|
| 24 |
+
from kornia.geometry.transform import hflip
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RandomHorizontalFlip(GeometricAugmentationBase2D):
|
| 28 |
+
r"""Apply a random horizontal flip to a tensor image or a batch of tensor images with a given probability.
|
| 29 |
+
|
| 30 |
+
.. image:: _static/img/RandomHorizontalFlip.png
|
| 31 |
+
|
| 32 |
+
Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.
|
| 33 |
+
If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
|
| 34 |
+
the corresponding transformation matrix that has been applied to them. In this case the module
|
| 35 |
+
will Horizontally flip the tensors and concatenate the corresponding transformation matrix to the
|
| 36 |
+
previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
p: probability of the image being flipped.
|
| 40 |
+
same_on_batch: apply the same transformation across the batch.
|
| 41 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 42 |
+
to the batch form (False).
|
| 43 |
+
|
| 44 |
+
Shape:
|
| 45 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 46 |
+
- Output: :math:`(B, C, H, W)`
|
| 47 |
+
|
| 48 |
+
.. note::
|
| 49 |
+
This function internally uses :func:`kornia.geometry.transform.hflip`.
|
| 50 |
+
|
| 51 |
+
Examples:
|
| 52 |
+
>>> import torch
|
| 53 |
+
>>> input = torch.tensor([[[[0., 0., 0.],
|
| 54 |
+
... [0., 0., 0.],
|
| 55 |
+
... [0., 1., 1.]]]])
|
| 56 |
+
>>> seq = RandomHorizontalFlip(p=1.0)
|
| 57 |
+
>>> seq(input), seq.transform_matrix
|
| 58 |
+
(tensor([[[[0., 0., 0.],
|
| 59 |
+
[0., 0., 0.],
|
| 60 |
+
[1., 1., 0.]]]]), tensor([[[-1., 0., 2.],
|
| 61 |
+
[ 0., 1., 0.],
|
| 62 |
+
[ 0., 0., 1.]]]))
|
| 63 |
+
>>> seq.inverse(seq(input)).equal(input)
|
| 64 |
+
True
|
| 65 |
+
|
| 66 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 67 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 68 |
+
>>> seq = RandomHorizontalFlip(p=1.0)
|
| 69 |
+
>>> (seq(input) == seq(input, params=seq._params)).all()
|
| 70 |
+
tensor(True)
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 75 |
+
w: int = int(params["forward_input_shape"][-1])
|
| 76 |
+
flip_mat: Tensor = tensor([[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype)
|
| 77 |
+
|
| 78 |
+
return flip_mat.expand(input.shape[0], 3, 3)
|
| 79 |
+
|
| 80 |
+
def apply_transform(
|
| 81 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 82 |
+
) -> Tensor:
|
| 83 |
+
return hflip(input)
|
| 84 |
+
|
| 85 |
+
def inverse_transform(
|
| 86 |
+
self,
|
| 87 |
+
input: Tensor,
|
| 88 |
+
flags: Dict[str, Any],
|
| 89 |
+
transform: Optional[Tensor] = None,
|
| 90 |
+
size: Optional[Tuple[int, int]] = None,
|
| 91 |
+
) -> Tensor:
|
| 92 |
+
if not isinstance(transform, Tensor):
|
| 93 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 94 |
+
return self.apply_transform(
|
| 95 |
+
input,
|
| 96 |
+
params=self._params,
|
| 97 |
+
transform=as_tensor(transform, device=input.device, dtype=input.dtype),
|
| 98 |
+
flags=flags,
|
| 99 |
+
)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/pad.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import Tensor
|
| 22 |
+
|
| 23 |
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PadTo(GeometricAugmentationBase2D):
|
| 27 |
+
r"""Pad the given sample to a specific size. Always occurs (p=1.0).
|
| 28 |
+
|
| 29 |
+
.. image:: _static/img/PadTo.png
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
size: a tuple of ints in the format (height, width) that give the spatial
|
| 33 |
+
dimensions to pad inputs to.
|
| 34 |
+
pad_mode: the type of padding to perform on the image (valid values
|
| 35 |
+
are those accepted by torch.nn.functional.pad)
|
| 36 |
+
pad_value: fill value for 'constant' padding applied to the image
|
| 37 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 38 |
+
to the batch form (False).
|
| 39 |
+
|
| 40 |
+
Shape:
|
| 41 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 42 |
+
- Output: :math:`(B, C, H, W)`
|
| 43 |
+
|
| 44 |
+
.. note::
|
| 45 |
+
This function internally uses :func:`torch.nn.functional.pad`.
|
| 46 |
+
|
| 47 |
+
Examples:
|
| 48 |
+
>>> import torch
|
| 49 |
+
>>> img = torch.tensor([[[[0., 0., 0.],
|
| 50 |
+
... [0., 0., 0.],
|
| 51 |
+
... [0., 0., 0.]]]])
|
| 52 |
+
>>> pad = PadTo((4, 5), pad_value=1.)
|
| 53 |
+
>>> out = pad(img)
|
| 54 |
+
>>> out
|
| 55 |
+
tensor([[[[0., 0., 0., 1., 1.],
|
| 56 |
+
[0., 0., 0., 1., 1.],
|
| 57 |
+
[0., 0., 0., 1., 1.],
|
| 58 |
+
[1., 1., 1., 1., 1.]]]])
|
| 59 |
+
>>> pad.inverse(out)
|
| 60 |
+
tensor([[[[0., 0., 0.],
|
| 61 |
+
[0., 0., 0.],
|
| 62 |
+
[0., 0., 0.]]]])
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
def __init__(
|
| 67 |
+
self, size: Tuple[int, int], pad_mode: str = "constant", pad_value: float = 0, keepdim: bool = False
|
| 68 |
+
) -> None:
|
| 69 |
+
super().__init__(p=1.0, same_on_batch=True, p_batch=1.0, keepdim=keepdim)
|
| 70 |
+
self.flags = {"size": size, "pad_mode": pad_mode, "pad_value": pad_value}
|
| 71 |
+
|
| 72 |
+
# TODO: It is incorrect to return identity
|
| 73 |
+
# TODO: Having a resampled version with ``warp_affine``
|
| 74 |
+
def compute_transformation(self, image: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 75 |
+
return self.identity_matrix(image)
|
| 76 |
+
|
| 77 |
+
def apply_transform(
|
| 78 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 79 |
+
) -> Tensor:
|
| 80 |
+
_, _, height, width = input.shape
|
| 81 |
+
height_pad: int = flags["size"][0] - height
|
| 82 |
+
width_pad: int = flags["size"][1] - width
|
| 83 |
+
return torch.nn.functional.pad(
|
| 84 |
+
input, [0, width_pad, 0, height_pad], mode=flags["pad_mode"], value=flags["pad_value"]
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
def inverse_transform(
|
| 88 |
+
self,
|
| 89 |
+
input: Tensor,
|
| 90 |
+
flags: Dict[str, Any],
|
| 91 |
+
transform: Optional[Tensor] = None,
|
| 92 |
+
size: Optional[Tuple[int, int]] = None,
|
| 93 |
+
) -> Tensor:
|
| 94 |
+
if size is None:
|
| 95 |
+
raise RuntimeError("`size` has to be a tuple. Got None.")
|
| 96 |
+
return input[..., : size[0], : size[1]]
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/perspective.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
|
| 22 |
+
from kornia.constants import Resample
|
| 23 |
+
from kornia.core import Tensor, as_tensor
|
| 24 |
+
from kornia.geometry.transform import get_perspective_transform, warp_perspective
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RandomPerspective(GeometricAugmentationBase2D):
|
| 28 |
+
r"""Apply a random perspective transformation to an image tensor with a given probability.
|
| 29 |
+
|
| 30 |
+
.. image:: _static/img/RandomPerspective.png
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
distortion_scale: the degree of distortion, ranged from 0 to 1.
|
| 34 |
+
resample: the interpolation method to use.
|
| 35 |
+
same_on_batch: apply the same transformation across the batch. Default: False.
|
| 36 |
+
align_corners: interpolation flag.
|
| 37 |
+
p: probability of the image being perspectively transformed.
|
| 38 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 39 |
+
to the batch form (False).
|
| 40 |
+
sampling_method: ``'basic'`` | ``'area_preserving'``. Default: ``'basic'``
|
| 41 |
+
If ``'basic'``, samples by translating the image corners randomly inwards.
|
| 42 |
+
If ``'area_preserving'``, samples by randomly translating the image corners in any direction.
|
| 43 |
+
Preserves area on average. See https://arxiv.org/abs/2104.03308 for further details.
|
| 44 |
+
|
| 45 |
+
Shape:
|
| 46 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 47 |
+
- Output: :math:`(B, C, H, W)`
|
| 48 |
+
|
| 49 |
+
.. note::
|
| 50 |
+
This function internally uses :func:`kornia.geometry.transform.warp_pespective`.
|
| 51 |
+
|
| 52 |
+
Examples:
|
| 53 |
+
>>> rng = torch.manual_seed(0)
|
| 54 |
+
>>> inputs= torch.tensor([[[[1., 0., 0.],
|
| 55 |
+
... [0., 1., 0.],
|
| 56 |
+
... [0., 0., 1.]]]])
|
| 57 |
+
>>> aug = RandomPerspective(0.5, p=0.5)
|
| 58 |
+
>>> out = aug(inputs)
|
| 59 |
+
>>> out
|
| 60 |
+
tensor([[[[0.0000, 0.2289, 0.0000],
|
| 61 |
+
[0.0000, 0.4800, 0.0000],
|
| 62 |
+
[0.0000, 0.0000, 0.0000]]]])
|
| 63 |
+
>>> aug.inverse(out)
|
| 64 |
+
tensor([[[[0.0500, 0.0961, 0.0000],
|
| 65 |
+
[0.2011, 0.3144, 0.0000],
|
| 66 |
+
[0.0031, 0.0130, 0.0053]]]])
|
| 67 |
+
|
| 68 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 69 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 70 |
+
>>> aug = RandomPerspective(0.5, p=1.)
|
| 71 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 72 |
+
tensor(True)
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
distortion_scale: Union[Tensor, float] = 0.5,
|
| 79 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 80 |
+
same_on_batch: bool = False,
|
| 81 |
+
align_corners: bool = False,
|
| 82 |
+
p: float = 0.5,
|
| 83 |
+
keepdim: bool = False,
|
| 84 |
+
sampling_method: str = "basic",
|
| 85 |
+
) -> None:
|
| 86 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 87 |
+
self._param_generator = rg.PerspectiveGenerator(distortion_scale, sampling_method=sampling_method)
|
| 88 |
+
|
| 89 |
+
self.flags: Dict[str, Any] = {"align_corners": align_corners, "resample": Resample.get(resample)}
|
| 90 |
+
|
| 91 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 92 |
+
return get_perspective_transform(params["start_points"].to(input), params["end_points"].to(input))
|
| 93 |
+
|
| 94 |
+
def apply_transform(
|
| 95 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 96 |
+
) -> Tensor:
|
| 97 |
+
_, _, height, width = input.shape
|
| 98 |
+
if not isinstance(transform, Tensor):
|
| 99 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 100 |
+
|
| 101 |
+
return warp_perspective(
|
| 102 |
+
input, transform, (height, width), mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
def inverse_transform(
|
| 106 |
+
self,
|
| 107 |
+
input: Tensor,
|
| 108 |
+
flags: Dict[str, Any],
|
| 109 |
+
transform: Optional[Tensor] = None,
|
| 110 |
+
size: Optional[Tuple[int, int]] = None,
|
| 111 |
+
) -> Tensor:
|
| 112 |
+
if not isinstance(transform, Tensor):
|
| 113 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 114 |
+
return self.apply_transform(
|
| 115 |
+
input,
|
| 116 |
+
params=self._params,
|
| 117 |
+
transform=as_tensor(transform, device=input.device, dtype=input.dtype),
|
| 118 |
+
flags=flags,
|
| 119 |
+
)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/resize.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation import random_generator as rg
|
| 23 |
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
|
| 24 |
+
from kornia.constants import Resample
|
| 25 |
+
from kornia.core import Tensor
|
| 26 |
+
from kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform, resize
|
| 27 |
+
from kornia.utils import eye_like
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Resize(GeometricAugmentationBase2D):
|
| 31 |
+
"""Resize to size.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
size: Size (h, w) in pixels of the resized region or just one side.
|
| 35 |
+
side: Which side to resize, if size is only of type int.
|
| 36 |
+
resample: Resampling mode.
|
| 37 |
+
align_corners: interpolation flag.
|
| 38 |
+
antialias: if True, then image will be filtered with Gaussian before downscaling. No effect for upscaling.
|
| 39 |
+
p: probability of the augmentation been applied.
|
| 40 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 41 |
+
to the batch form (False).
|
| 42 |
+
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
size: Union[int, Tuple[int, int]],
|
| 48 |
+
side: str = "short",
|
| 49 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 50 |
+
align_corners: bool = True,
|
| 51 |
+
antialias: bool = False,
|
| 52 |
+
p: float = 1.0,
|
| 53 |
+
keepdim: bool = False,
|
| 54 |
+
) -> None:
|
| 55 |
+
super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim)
|
| 56 |
+
self._param_generator = rg.ResizeGenerator(resize_to=size, side=side)
|
| 57 |
+
self.flags = {
|
| 58 |
+
"size": size,
|
| 59 |
+
"side": side,
|
| 60 |
+
"resample": Resample.get(resample),
|
| 61 |
+
"align_corners": align_corners,
|
| 62 |
+
"antialias": antialias,
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 66 |
+
if params["output_size"] == input.shape[-2:]:
|
| 67 |
+
return eye_like(3, input)
|
| 68 |
+
|
| 69 |
+
transform: Tensor = torch.as_tensor(
|
| 70 |
+
get_perspective_transform(params["src"], params["dst"]), dtype=input.dtype, device=input.device
|
| 71 |
+
)
|
| 72 |
+
transform = transform.expand(input.shape[0], -1, -1)
|
| 73 |
+
return transform
|
| 74 |
+
|
| 75 |
+
def apply_transform(
|
| 76 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 77 |
+
) -> Tensor:
|
| 78 |
+
B, C, _, _ = input.shape
|
| 79 |
+
out_size = tuple(params["output_size"][0].tolist())
|
| 80 |
+
out = torch.empty(B, C, *out_size, device=input.device, dtype=input.dtype)
|
| 81 |
+
|
| 82 |
+
for i in range(B):
|
| 83 |
+
x1 = int(params["src"][i, 0, 0])
|
| 84 |
+
x2 = int(params["src"][i, 1, 0]) + 1
|
| 85 |
+
y1 = int(params["src"][i, 0, 1])
|
| 86 |
+
y2 = int(params["src"][i, 3, 1]) + 1
|
| 87 |
+
out[i] = resize(
|
| 88 |
+
input[i : i + 1, :, y1:y2, x1:x2],
|
| 89 |
+
out_size,
|
| 90 |
+
interpolation=flags["resample"].name.lower(),
|
| 91 |
+
align_corners=(
|
| 92 |
+
flags["align_corners"] if flags["resample"] in [Resample.BILINEAR, Resample.BICUBIC] else None
|
| 93 |
+
),
|
| 94 |
+
antialias=flags["antialias"],
|
| 95 |
+
)
|
| 96 |
+
return out
|
| 97 |
+
|
| 98 |
+
def inverse_transform(
|
| 99 |
+
self,
|
| 100 |
+
input: Tensor,
|
| 101 |
+
flags: Dict[str, Any],
|
| 102 |
+
transform: Optional[Tensor] = None,
|
| 103 |
+
size: Optional[Tuple[int, int]] = None,
|
| 104 |
+
) -> Tensor:
|
| 105 |
+
if not isinstance(size, tuple):
|
| 106 |
+
raise TypeError(f"Expected the size be a tuple. Gotcha {type(size)}")
|
| 107 |
+
|
| 108 |
+
if not isinstance(transform, Tensor):
|
| 109 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 110 |
+
|
| 111 |
+
return crop_by_transform_mat(
|
| 112 |
+
input, transform[:, :2, :], size, flags["resample"].name.lower(), "zeros", flags["align_corners"]
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class LongestMaxSize(Resize):
|
| 117 |
+
"""Rescale an image so that maximum side is equal to max_size, keeping the aspect ratio of the initial image.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
max_size: maximum size of the image after the transformation.
|
| 121 |
+
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
def __init__(
|
| 125 |
+
self,
|
| 126 |
+
max_size: int,
|
| 127 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 128 |
+
align_corners: bool = True,
|
| 129 |
+
p: float = 1.0,
|
| 130 |
+
) -> None:
|
| 131 |
+
# TODO: Support max_size list input to randomly select from
|
| 132 |
+
super().__init__(size=max_size, side="long", resample=resample, align_corners=align_corners, p=p)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class SmallestMaxSize(Resize):
|
| 136 |
+
"""Rescale an image so that minimum side is equal to max_size, keeping the aspect ratio of the initial image.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
max_size: maximum size of the image after the transformation.
|
| 140 |
+
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
def __init__(
|
| 144 |
+
self,
|
| 145 |
+
max_size: int,
|
| 146 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 147 |
+
align_corners: bool = True,
|
| 148 |
+
p: float = 1.0,
|
| 149 |
+
) -> None:
|
| 150 |
+
# TODO: Support max_size list input to randomly select from
|
| 151 |
+
super().__init__(size=max_size, side="short", resample=resample, align_corners=align_corners, p=p)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/resized_crop.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
|
| 22 |
+
from kornia.constants import Resample
|
| 23 |
+
from kornia.core import Tensor
|
| 24 |
+
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RandomResizedCrop(GeometricAugmentationBase2D):
|
| 28 |
+
r"""Crop random patches in an image tensor and resizes to a given size.
|
| 29 |
+
|
| 30 |
+
.. image:: _static/img/RandomResizedCrop.png
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
size: Desired output size (out_h, out_w) of each edge.
|
| 34 |
+
Must be Tuple[int, int], then out_h = size[0], out_w = size[1].
|
| 35 |
+
scale: range of size of the origin size cropped.
|
| 36 |
+
ratio: range of aspect ratio of the origin aspect ratio cropped.
|
| 37 |
+
resample: the interpolation mode.
|
| 38 |
+
same_on_batch: apply the same transformation across the batch.
|
| 39 |
+
align_corners: interpolation flag.
|
| 40 |
+
p: probability of the augmentation been applied.
|
| 41 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 42 |
+
to the batch form (False).
|
| 43 |
+
cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
|
| 44 |
+
on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
|
| 45 |
+
to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
|
| 46 |
+
differentiability.
|
| 47 |
+
|
| 48 |
+
Shape:
|
| 49 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 50 |
+
- Output: :math:`(B, C, out_h, out_w)`
|
| 51 |
+
|
| 52 |
+
Note:
|
| 53 |
+
Input tensor must be float and normalized into [0, 1] for the best differentiability support.
|
| 54 |
+
Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
|
| 55 |
+
applied transformation will be merged int to the input transformation tensor and returned.
|
| 56 |
+
|
| 57 |
+
Example:
|
| 58 |
+
>>> rng = torch.manual_seed(0)
|
| 59 |
+
>>> inputs = torch.tensor([[[0., 1., 2.],
|
| 60 |
+
... [3., 4., 5.],
|
| 61 |
+
... [6., 7., 8.]]])
|
| 62 |
+
>>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1., cropping_mode="resample")
|
| 63 |
+
>>> out = aug(inputs)
|
| 64 |
+
>>> out
|
| 65 |
+
tensor([[[[1.0000, 1.5000, 2.0000],
|
| 66 |
+
[4.0000, 4.5000, 5.0000],
|
| 67 |
+
[7.0000, 7.5000, 8.0000]]]])
|
| 68 |
+
>>> aug.inverse(out, padding_mode="border")
|
| 69 |
+
tensor([[[[1., 1., 2.],
|
| 70 |
+
[4., 4., 5.],
|
| 71 |
+
[7., 7., 8.]]]])
|
| 72 |
+
|
| 73 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 74 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 75 |
+
>>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1., cropping_mode="resample")
|
| 76 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 77 |
+
tensor(True)
|
| 78 |
+
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
def __init__(
|
| 82 |
+
self,
|
| 83 |
+
size: Tuple[int, int],
|
| 84 |
+
scale: Union[Tensor, Tuple[float, float]] = (0.08, 1.0),
|
| 85 |
+
ratio: Union[Tensor, Tuple[float, float]] = (3.0 / 4.0, 4.0 / 3.0),
|
| 86 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 87 |
+
same_on_batch: bool = False,
|
| 88 |
+
align_corners: bool = True,
|
| 89 |
+
p: float = 1.0,
|
| 90 |
+
keepdim: bool = False,
|
| 91 |
+
cropping_mode: str = "slice",
|
| 92 |
+
) -> None:
|
| 93 |
+
# Since PyTorch does not support ragged tensor. So cropping function happens all the time.
|
| 94 |
+
super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
|
| 95 |
+
self._param_generator = rg.ResizedCropGenerator(size, scale, ratio)
|
| 96 |
+
self.flags = {
|
| 97 |
+
"size": size,
|
| 98 |
+
"resample": Resample.get(resample),
|
| 99 |
+
"align_corners": align_corners,
|
| 100 |
+
"cropping_mode": cropping_mode,
|
| 101 |
+
"padding_mode": "zeros",
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 105 |
+
if flags["cropping_mode"] in ("resample", "slice"):
|
| 106 |
+
transform: Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
|
| 107 |
+
transform = transform.expand(input.shape[0], -1, -1)
|
| 108 |
+
return transform
|
| 109 |
+
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
|
| 110 |
+
|
| 111 |
+
def apply_transform(
|
| 112 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 113 |
+
) -> Tensor:
|
| 114 |
+
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
|
| 115 |
+
if not isinstance(transform, Tensor):
|
| 116 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 117 |
+
|
| 118 |
+
return crop_by_transform_mat(
|
| 119 |
+
input,
|
| 120 |
+
transform,
|
| 121 |
+
flags["size"],
|
| 122 |
+
mode=flags["resample"].name.lower(),
|
| 123 |
+
padding_mode="zeros",
|
| 124 |
+
align_corners=flags["align_corners"],
|
| 125 |
+
)
|
| 126 |
+
if flags["cropping_mode"] == "slice": # uses advanced slicing to crop
|
| 127 |
+
return crop_by_indices(
|
| 128 |
+
input,
|
| 129 |
+
params["src"],
|
| 130 |
+
flags["size"],
|
| 131 |
+
interpolation=flags["resample"].name.lower(),
|
| 132 |
+
align_corners=flags["align_corners"],
|
| 133 |
+
)
|
| 134 |
+
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
|
| 135 |
+
|
| 136 |
+
def inverse_transform(
|
| 137 |
+
self,
|
| 138 |
+
input: Tensor,
|
| 139 |
+
flags: Dict[str, Any],
|
| 140 |
+
transform: Optional[Tensor] = None,
|
| 141 |
+
size: Optional[Tuple[int, int]] = None,
|
| 142 |
+
) -> Tensor:
|
| 143 |
+
if flags["cropping_mode"] != "resample":
|
| 144 |
+
raise NotImplementedError(
|
| 145 |
+
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
|
| 146 |
+
)
|
| 147 |
+
if not isinstance(size, tuple):
|
| 148 |
+
raise TypeError(f"Expected the size be a tuple. Gotcha {type(size)}")
|
| 149 |
+
|
| 150 |
+
if not isinstance(transform, Tensor):
|
| 151 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 152 |
+
|
| 153 |
+
return crop_by_transform_mat(
|
| 154 |
+
input,
|
| 155 |
+
transform[:, :2, :],
|
| 156 |
+
size,
|
| 157 |
+
flags["resample"].name.lower(),
|
| 158 |
+
flags["padding_mode"],
|
| 159 |
+
flags["align_corners"],
|
| 160 |
+
)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/rotation.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
|
| 22 |
+
from kornia.constants import Resample
|
| 23 |
+
from kornia.core import Tensor, as_tensor
|
| 24 |
+
from kornia.geometry.transform import affine
|
| 25 |
+
from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center
|
| 26 |
+
from kornia.utils.misc import eye_like
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class RandomRotation(GeometricAugmentationBase2D):
|
| 30 |
+
r"""Apply a random rotation to a tensor image or a batch of tensor images given an amount of degrees.
|
| 31 |
+
|
| 32 |
+
.. image:: _static/img/RandomRotation.png
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
degrees: range of degrees to select from. If degrees is a number the
|
| 36 |
+
range of degrees to select from will be (-degrees, +degrees).
|
| 37 |
+
resample: Default: the interpolation mode.
|
| 38 |
+
same_on_batch: apply the same transformation across the batch.
|
| 39 |
+
align_corners: interpolation flag.
|
| 40 |
+
p: probability of applying the transformation.
|
| 41 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 42 |
+
to the batch form (False).
|
| 43 |
+
|
| 44 |
+
Shape:
|
| 45 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 46 |
+
- Output: :math:`(B, C, H, W)`
|
| 47 |
+
|
| 48 |
+
.. note::
|
| 49 |
+
This function internally uses :func:`kornia.geometry.transform.affine`.
|
| 50 |
+
|
| 51 |
+
Examples:
|
| 52 |
+
>>> rng = torch.manual_seed(0)
|
| 53 |
+
>>> input = torch.tensor([[1., 0., 0., 2.],
|
| 54 |
+
... [0., 0., 0., 0.],
|
| 55 |
+
... [0., 1., 2., 0.],
|
| 56 |
+
... [0., 0., 1., 2.]])
|
| 57 |
+
>>> aug = RandomRotation(degrees=45.0, p=1.)
|
| 58 |
+
>>> out = aug(input)
|
| 59 |
+
>>> out
|
| 60 |
+
tensor([[[[0.9824, 0.0088, 0.0000, 1.9649],
|
| 61 |
+
[0.0000, 0.0029, 0.0000, 0.0176],
|
| 62 |
+
[0.0029, 1.0000, 1.9883, 0.0000],
|
| 63 |
+
[0.0000, 0.0088, 1.0117, 1.9649]]]])
|
| 64 |
+
>>> aug.transform_matrix
|
| 65 |
+
tensor([[[ 1.0000, -0.0059, 0.0088],
|
| 66 |
+
[ 0.0059, 1.0000, -0.0088],
|
| 67 |
+
[ 0.0000, 0.0000, 1.0000]]])
|
| 68 |
+
>>> inv = aug.inverse(out)
|
| 69 |
+
|
| 70 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 71 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 72 |
+
>>> aug = RandomRotation(degrees=45.0, p=1.)
|
| 73 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 74 |
+
tensor(True)
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
# Note: Extra params, center=None, fill=0 in TorchVision
|
| 79 |
+
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
degrees: Union[Tensor, float, Tuple[float, float], List[float]],
|
| 83 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 84 |
+
same_on_batch: bool = False,
|
| 85 |
+
align_corners: bool = True,
|
| 86 |
+
p: float = 0.5,
|
| 87 |
+
keepdim: bool = False,
|
| 88 |
+
) -> None:
|
| 89 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 90 |
+
self._param_generator = rg.PlainUniformGenerator((degrees, "degrees", 0.0, (-360.0, 360.0)))
|
| 91 |
+
|
| 92 |
+
self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}
|
| 93 |
+
|
| 94 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 95 |
+
# TODO: Update to use `get_rotation_matrix2d`
|
| 96 |
+
angles: Tensor = params["degrees"].to(input)
|
| 97 |
+
|
| 98 |
+
center: Tensor = _compute_tensor_center(input)
|
| 99 |
+
rotation_mat: Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))
|
| 100 |
+
|
| 101 |
+
# rotation_mat is B x 2 x 3 and we need a B x 3 x 3 matrix
|
| 102 |
+
trans_mat: Tensor = eye_like(3, input, shared_memory=False)
|
| 103 |
+
trans_mat[:, 0] = rotation_mat[:, 0]
|
| 104 |
+
trans_mat[:, 1] = rotation_mat[:, 1]
|
| 105 |
+
|
| 106 |
+
return trans_mat
|
| 107 |
+
|
| 108 |
+
def apply_transform(
|
| 109 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 110 |
+
) -> Tensor:
|
| 111 |
+
if not isinstance(transform, Tensor):
|
| 112 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 113 |
+
|
| 114 |
+
return affine(input, transform[..., :2, :3], flags["resample"].name.lower(), "zeros", flags["align_corners"])
|
| 115 |
+
|
| 116 |
+
def inverse_transform(
|
| 117 |
+
self,
|
| 118 |
+
input: Tensor,
|
| 119 |
+
flags: Dict[str, Any],
|
| 120 |
+
transform: Optional[Tensor] = None,
|
| 121 |
+
size: Optional[Tuple[int, int]] = None,
|
| 122 |
+
) -> Tensor:
|
| 123 |
+
if not isinstance(transform, Tensor):
|
| 124 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 125 |
+
return self.apply_transform(
|
| 126 |
+
input,
|
| 127 |
+
params=self._params,
|
| 128 |
+
transform=as_tensor(transform, device=input.device, dtype=input.dtype),
|
| 129 |
+
flags=flags,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class RandomRotation90(GeometricAugmentationBase2D):
|
| 134 |
+
r"""Apply a random 90 * n degree rotation to a tensor image or a batch of tensor images.
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
times: the range of n times 90 degree rotation needs to be applied.
|
| 138 |
+
resample: Default: the interpolation mode.
|
| 139 |
+
same_on_batch: apply the same transformation across the batch.
|
| 140 |
+
align_corners: interpolation flag.
|
| 141 |
+
p: probability of applying the transformation.
|
| 142 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 143 |
+
to the batch form (False).
|
| 144 |
+
|
| 145 |
+
Shape:
|
| 146 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 147 |
+
- Output: :math:`(B, C, H, W)`
|
| 148 |
+
|
| 149 |
+
.. note::
|
| 150 |
+
This function internally uses :func:`kornia.geometry.transform.affine`. This version is relatively
|
| 151 |
+
slow as it operates based on affine transformations.
|
| 152 |
+
|
| 153 |
+
Examples:
|
| 154 |
+
>>> rng = torch.manual_seed(1)
|
| 155 |
+
>>> torch.set_printoptions(sci_mode=False)
|
| 156 |
+
>>> input = torch.tensor([[1., 0., 0., 2.],
|
| 157 |
+
... [0., 0., 0., 0.],
|
| 158 |
+
... [0., 1., 2., 0.],
|
| 159 |
+
... [0., 0., 1., 2.]])
|
| 160 |
+
>>> aug = RandomRotation90(times=(1, 1), p=1.)
|
| 161 |
+
>>> out = aug(input)
|
| 162 |
+
>>> out
|
| 163 |
+
tensor([[[[ 2.0000, 0.0000, 0.0000, 2.0000],
|
| 164 |
+
[ 0.0000, 0.0000, 2.0000, 1.0000],
|
| 165 |
+
[ 0.0000, 0.0000, 1.0000, 0.0000],
|
| 166 |
+
[ 1.0000, 0.0000, 0.0000, 0.0000]]]])
|
| 167 |
+
>>> aug.transform_matrix
|
| 168 |
+
tensor([[[ -0.0000, 1.0000, 0.0000],
|
| 169 |
+
[ -1.0000, -0.0000, 3.0000],
|
| 170 |
+
[ 0.0000, 0.0000, 1.0000]]])
|
| 171 |
+
>>> inv = aug.inverse(out)
|
| 172 |
+
>>> torch.set_printoptions(profile='default')
|
| 173 |
+
|
| 174 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 175 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 176 |
+
>>> aug = RandomRotation90(times=(-1, 1), p=1.)
|
| 177 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 178 |
+
tensor(True)
|
| 179 |
+
|
| 180 |
+
"""
|
| 181 |
+
|
| 182 |
+
def __init__(
|
| 183 |
+
self,
|
| 184 |
+
times: tuple[int, int],
|
| 185 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 186 |
+
same_on_batch: bool = False,
|
| 187 |
+
align_corners: bool = True,
|
| 188 |
+
p: float = 0.5,
|
| 189 |
+
keepdim: bool = False,
|
| 190 |
+
) -> None:
|
| 191 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 192 |
+
self._param_generator = rg.PlainUniformGenerator((times, "times", 0.0, (-3, 3)))
|
| 193 |
+
|
| 194 |
+
self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}
|
| 195 |
+
|
| 196 |
+
def compute_transformation(self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any]) -> Tensor:
|
| 197 |
+
# TODO: Update to use `get_rotation_matrix2d`
|
| 198 |
+
angles: Tensor = 90.0 * params["times"].round().to(input)
|
| 199 |
+
|
| 200 |
+
center: Tensor = _compute_tensor_center(input)
|
| 201 |
+
rotation_mat: Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))
|
| 202 |
+
|
| 203 |
+
# rotation_mat is B x 2 x 3 and we need a B x 3 x 3 matrix
|
| 204 |
+
trans_mat: Tensor = eye_like(3, input, shared_memory=False)
|
| 205 |
+
trans_mat[:, 0] = rotation_mat[:, 0]
|
| 206 |
+
trans_mat[:, 1] = rotation_mat[:, 1]
|
| 207 |
+
|
| 208 |
+
return trans_mat
|
| 209 |
+
|
| 210 |
+
def apply_transform(
|
| 211 |
+
self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None
|
| 212 |
+
) -> Tensor:
|
| 213 |
+
if not isinstance(transform, Tensor):
|
| 214 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 215 |
+
|
| 216 |
+
return affine(input, transform[..., :2, :3], flags["resample"].name.lower(), "zeros", flags["align_corners"])
|
| 217 |
+
|
| 218 |
+
def inverse_transform(
|
| 219 |
+
self,
|
| 220 |
+
input: Tensor,
|
| 221 |
+
flags: dict[str, Any],
|
| 222 |
+
transform: Optional[Tensor] = None,
|
| 223 |
+
size: Optional[tuple[int, int]] = None,
|
| 224 |
+
) -> Tensor:
|
| 225 |
+
if not isinstance(transform, Tensor):
|
| 226 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 227 |
+
return self.apply_transform(
|
| 228 |
+
input,
|
| 229 |
+
params=self._params,
|
| 230 |
+
transform=as_tensor(transform, device=input.device, dtype=input.dtype),
|
| 231 |
+
flags=flags,
|
| 232 |
+
)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/shear.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
|
| 22 |
+
from kornia.constants import Resample, SamplePadding
|
| 23 |
+
from kornia.core import Tensor, as_tensor
|
| 24 |
+
from kornia.geometry.conversions import deg2rad
|
| 25 |
+
from kornia.geometry.transform import get_shear_matrix2d, warp_affine
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class RandomShear(GeometricAugmentationBase2D):
|
| 29 |
+
r"""Apply a random 2D shear transformation to a tensor image.
|
| 30 |
+
|
| 31 |
+
The transformation is computed so that the image center is kept invariant.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
shear: Range of degrees to select from.
|
| 35 |
+
If float, a shear parallel to the x axis in the range (-shear, +shear) will be applied.
|
| 36 |
+
If (a, b), a shear parallel to the x axis in the range (-shear, +shear) will be applied.
|
| 37 |
+
If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3])
|
| 38 |
+
will be applied. Will not apply shear by default.
|
| 39 |
+
resample: resample mode from "nearest" (0) or "bilinear" (1).
|
| 40 |
+
padding_mode: padding mode from "zeros" (0), "border" (1) or "reflection" (2).
|
| 41 |
+
same_on_batch: apply the same transformation across the batch.
|
| 42 |
+
align_corners: interpolation flag.
|
| 43 |
+
p: probability of applying the transformation.
|
| 44 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False).
|
| 45 |
+
|
| 46 |
+
Shape:
|
| 47 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
|
| 48 |
+
- Output: :math:`(B, C, H, W)`
|
| 49 |
+
|
| 50 |
+
.. note::
|
| 51 |
+
This function internally uses :func:`kornia.geometry.transform.warp_affine`.
|
| 52 |
+
|
| 53 |
+
Examples:
|
| 54 |
+
>>> import torch
|
| 55 |
+
>>> rng = torch.manual_seed(0)
|
| 56 |
+
>>> input = torch.rand(1, 1, 3, 3)
|
| 57 |
+
>>> aug = RandomShear((-5., 2., 5., 10.), p=1.)
|
| 58 |
+
>>> out = aug(input)
|
| 59 |
+
>>> out, aug.transform_matrix
|
| 60 |
+
(tensor([[[[0.4403, 0.7614, 0.1516],
|
| 61 |
+
[0.1753, 0.3074, 0.6127],
|
| 62 |
+
[0.4438, 0.8924, 0.4061]]]]), tensor([[[ 1.0000, 0.0100, -0.0100],
|
| 63 |
+
[-0.1183, 0.9988, 0.1194],
|
| 64 |
+
[ 0.0000, 0.0000, 1.0000]]]))
|
| 65 |
+
>>> aug.inverse(out)
|
| 66 |
+
tensor([[[[0.4045, 0.7577, 0.1393],
|
| 67 |
+
[0.2071, 0.3074, 0.5582],
|
| 68 |
+
[0.3958, 0.8868, 0.4265]]]])
|
| 69 |
+
|
| 70 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 71 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 72 |
+
>>> aug = RandomShear((-15., 20.), p=1.)
|
| 73 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 74 |
+
tensor(True)
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
shear: Union[Tensor, float, Tuple[float, float], Tuple[float, float, float, float]],
|
| 81 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 82 |
+
same_on_batch: bool = False,
|
| 83 |
+
align_corners: bool = False,
|
| 84 |
+
padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name,
|
| 85 |
+
p: float = 0.5,
|
| 86 |
+
keepdim: bool = False,
|
| 87 |
+
) -> None:
|
| 88 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 89 |
+
self._param_generator: rg.ShearGenerator = rg.ShearGenerator(shear)
|
| 90 |
+
self.flags = {
|
| 91 |
+
"resample": Resample.get(resample),
|
| 92 |
+
"padding_mode": SamplePadding.get(padding_mode),
|
| 93 |
+
"align_corners": align_corners,
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 97 |
+
return get_shear_matrix2d(
|
| 98 |
+
as_tensor(params["center"], device=input.device, dtype=input.dtype),
|
| 99 |
+
deg2rad(as_tensor(params["shear_x"], device=input.device, dtype=input.dtype)),
|
| 100 |
+
deg2rad(as_tensor(params["shear_y"], device=input.device, dtype=input.dtype)),
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def apply_transform(
|
| 104 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 105 |
+
) -> Tensor:
|
| 106 |
+
_, _, height, width = input.shape
|
| 107 |
+
if not isinstance(transform, Tensor):
|
| 108 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 109 |
+
|
| 110 |
+
return warp_affine(
|
| 111 |
+
input,
|
| 112 |
+
transform[:, :2, :],
|
| 113 |
+
(height, width),
|
| 114 |
+
flags["resample"].name.lower(),
|
| 115 |
+
align_corners=flags["align_corners"],
|
| 116 |
+
padding_mode=flags["padding_mode"].name.lower(),
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
def inverse_transform(
|
| 120 |
+
self,
|
| 121 |
+
input: Tensor,
|
| 122 |
+
flags: Dict[str, Any],
|
| 123 |
+
transform: Optional[Tensor] = None,
|
| 124 |
+
size: Optional[Tuple[int, int]] = None,
|
| 125 |
+
) -> Tensor:
|
| 126 |
+
if not isinstance(transform, Tensor):
|
| 127 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 128 |
+
return self.apply_transform(
|
| 129 |
+
input,
|
| 130 |
+
params=self._params,
|
| 131 |
+
transform=as_tensor(transform, device=input.device, dtype=input.dtype),
|
| 132 |
+
flags=flags,
|
| 133 |
+
)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/thin_plate_spline.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation._2d.base import AugmentationBase2D
|
| 23 |
+
from kornia.constants import SamplePadding
|
| 24 |
+
from kornia.core import Tensor, tensor
|
| 25 |
+
from kornia.geometry.transform import get_tps_transform, warp_image_tps
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# NOTE: This NEEDS to be updated. It is out of the random generator controller.
|
| 29 |
+
class RandomThinPlateSpline(AugmentationBase2D):
|
| 30 |
+
r"""Add random noise to the Thin Plate Spline algorithm.
|
| 31 |
+
|
| 32 |
+
.. image:: _static/img/RandomThinPlateSpline.png
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
scale: the scale factor to apply to the destination points.
|
| 36 |
+
align_corners: Interpolation flag used by ``grid_sample``.
|
| 37 |
+
mode: Interpolation mode used by `grid_sample`. Either 'bilinear' or 'nearest'.
|
| 38 |
+
same_on_batch: apply the same transformation across the batch.
|
| 39 |
+
p: probability of applying the transformation.
|
| 40 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 41 |
+
to the batch form (False).
|
| 42 |
+
.. note::
|
| 43 |
+
This function internally uses :func:`kornia.geometry.transform.warp_image_tps`.
|
| 44 |
+
|
| 45 |
+
Examples:
|
| 46 |
+
>>> img = torch.ones(1, 1, 2, 2)
|
| 47 |
+
>>> out = RandomThinPlateSpline()(img)
|
| 48 |
+
>>> out.shape
|
| 49 |
+
torch.Size([1, 1, 2, 2])
|
| 50 |
+
|
| 51 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 52 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 53 |
+
>>> aug = RandomThinPlateSpline(p=1.)
|
| 54 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 55 |
+
tensor(True)
|
| 56 |
+
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
scale: float = 0.2,
|
| 62 |
+
align_corners: bool = False,
|
| 63 |
+
padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name,
|
| 64 |
+
same_on_batch: bool = False,
|
| 65 |
+
p: float = 0.5,
|
| 66 |
+
keepdim: bool = False,
|
| 67 |
+
) -> None:
|
| 68 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 69 |
+
self.flags = {
|
| 70 |
+
"align_corners": align_corners,
|
| 71 |
+
"padding_mode": SamplePadding.get(padding_mode),
|
| 72 |
+
}
|
| 73 |
+
self.dist = torch.distributions.Uniform(-scale, scale)
|
| 74 |
+
|
| 75 |
+
def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:
|
| 76 |
+
B, _, _, _ = shape
|
| 77 |
+
src = tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]]]).expand(B, 5, 2) # Bx5x2
|
| 78 |
+
dst = src + self.dist.rsample(src.shape)
|
| 79 |
+
return {"src": src, "dst": dst}
|
| 80 |
+
|
| 81 |
+
def apply_transform(
|
| 82 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 83 |
+
) -> Tensor:
|
| 84 |
+
src = params["src"].to(input)
|
| 85 |
+
dst = params["dst"].to(input)
|
| 86 |
+
# NOTE: warp_image_tps need to use inverse parameters
|
| 87 |
+
kernel, affine = get_tps_transform(dst, src)
|
| 88 |
+
return warp_image_tps(input, src, kernel, affine, flags["align_corners"], flags["padding_mode"].name.lower())
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/translate.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
|
| 22 |
+
from kornia.constants import Resample, SamplePadding
|
| 23 |
+
from kornia.core import Tensor, as_tensor, stack
|
| 24 |
+
from kornia.geometry.transform import get_translation_matrix2d, warp_affine
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RandomTranslate(GeometricAugmentationBase2D):
|
| 28 |
+
r"""Apply a random 2D affine transformation to a tensor image.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
translate_x: tuple of maximum absolute fraction for horizontal translations.
|
| 32 |
+
For example translate_x=(a, b), then horizontal shift
|
| 33 |
+
is randomly sampled in the range img_width * a < dx < img_width * b
|
| 34 |
+
translate_y: tuple of maximum absolute fraction for vertical translations.
|
| 35 |
+
For example translate_y=(a, b), then vertical shift
|
| 36 |
+
is randomly sampled in the range img_height * a < dy < img_height * b.
|
| 37 |
+
resample: resample mode from "nearest" (0) or "bilinear" (1).
|
| 38 |
+
padding_mode: padding mode from "zeros" (0), "border" (1) or "reflection" (2).
|
| 39 |
+
same_on_batch: apply the same transformation across the batch.
|
| 40 |
+
align_corners: interpolation flag.
|
| 41 |
+
p: probability of applying the transformation.
|
| 42 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False).
|
| 43 |
+
|
| 44 |
+
Shape:
|
| 45 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
|
| 46 |
+
- Output: :math:`(B, C, H, W)`
|
| 47 |
+
|
| 48 |
+
.. note::
|
| 49 |
+
This function internally uses :func:`kornia.geometry.transform.warp_affine`.
|
| 50 |
+
|
| 51 |
+
Examples:
|
| 52 |
+
>>> import torch
|
| 53 |
+
>>> rng = torch.manual_seed(0)
|
| 54 |
+
>>> input = torch.rand(1, 1, 3, 3)
|
| 55 |
+
>>> aug = RandomTranslate((-0.2, 0.2), (-0.1, 0.1), p=1.)
|
| 56 |
+
>>> out = aug(input)
|
| 57 |
+
>>> out, aug.transform_matrix
|
| 58 |
+
(tensor([[[[0.3403, 0.6439, 0.2920],
|
| 59 |
+
[0.1377, 0.3383, 0.5569],
|
| 60 |
+
[0.3226, 0.6909, 0.4844]]]]), tensor([[[ 1.0000, 0.0000, 0.1588],
|
| 61 |
+
[ 0.0000, 1.0000, -0.0907],
|
| 62 |
+
[ 0.0000, 0.0000, 1.0000]]]))
|
| 63 |
+
>>> aug.inverse(out)
|
| 64 |
+
tensor([[[[0.3565, 0.4839, 0.1922],
|
| 65 |
+
[0.2164, 0.4134, 0.3968],
|
| 66 |
+
[0.3797, 0.6075, 0.3765]]]])
|
| 67 |
+
|
| 68 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 69 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 70 |
+
>>> aug = RandomTranslate((-0.2, 0.2), (-0.1, 0.1), p=1.)
|
| 71 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 72 |
+
tensor(True)
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
translate_x: Optional[Union[Tensor, Tuple[float, float]]] = None,
|
| 79 |
+
translate_y: Optional[Union[Tensor, Tuple[float, float]]] = None,
|
| 80 |
+
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
|
| 81 |
+
same_on_batch: bool = False,
|
| 82 |
+
align_corners: bool = False,
|
| 83 |
+
padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name,
|
| 84 |
+
p: float = 0.5,
|
| 85 |
+
keepdim: bool = False,
|
| 86 |
+
) -> None:
|
| 87 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 88 |
+
self._param_generator: rg.TranslateGenerator = rg.TranslateGenerator(translate_x, translate_y)
|
| 89 |
+
self.flags = {
|
| 90 |
+
"resample": Resample.get(resample),
|
| 91 |
+
"padding_mode": SamplePadding.get(padding_mode),
|
| 92 |
+
"align_corners": align_corners,
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 96 |
+
translations = stack([params["translate_x"], params["translate_y"]], dim=-1)
|
| 97 |
+
return get_translation_matrix2d(as_tensor(translations, device=input.device, dtype=input.dtype))
|
| 98 |
+
|
| 99 |
+
def apply_transform(
|
| 100 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 101 |
+
) -> Tensor:
|
| 102 |
+
_, _, height, width = input.shape
|
| 103 |
+
if not isinstance(transform, Tensor):
|
| 104 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 105 |
+
|
| 106 |
+
return warp_affine(
|
| 107 |
+
input,
|
| 108 |
+
transform[:, :2, :],
|
| 109 |
+
(height, width),
|
| 110 |
+
flags["resample"].name.lower(),
|
| 111 |
+
align_corners=flags["align_corners"],
|
| 112 |
+
padding_mode=flags["padding_mode"].name.lower(),
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def inverse_transform(
|
| 116 |
+
self,
|
| 117 |
+
input: Tensor,
|
| 118 |
+
flags: Dict[str, Any],
|
| 119 |
+
transform: Optional[Tensor] = None,
|
| 120 |
+
size: Optional[Tuple[int, int]] = None,
|
| 121 |
+
) -> Tensor:
|
| 122 |
+
if not isinstance(transform, Tensor):
|
| 123 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 124 |
+
return self.apply_transform(
|
| 125 |
+
input,
|
| 126 |
+
params=self._params,
|
| 127 |
+
transform=as_tensor(transform, device=input.device, dtype=input.dtype),
|
| 128 |
+
flags=flags,
|
| 129 |
+
)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/geometric/vertical_flip.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
|
| 21 |
+
from kornia.core import Tensor, as_tensor, tensor
|
| 22 |
+
from kornia.geometry.transform import vflip
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class RandomVerticalFlip(GeometricAugmentationBase2D):
|
| 26 |
+
r"""Apply a random vertical flip to a tensor image or a batch of tensor images with a given probability.
|
| 27 |
+
|
| 28 |
+
.. image:: _static/img/RandomVerticalFlip.png
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
p: probability of the image being flipped.
|
| 32 |
+
same_on_batch: apply the same transformation across the batch.
|
| 33 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 34 |
+
to the batch form (False).
|
| 35 |
+
|
| 36 |
+
Shape:
|
| 37 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 38 |
+
- Output: :math:`(B, C, H, W)`
|
| 39 |
+
|
| 40 |
+
.. note::
|
| 41 |
+
This function internally uses :func:`kornia.geometry.transform.vflip`.
|
| 42 |
+
|
| 43 |
+
Examples:
|
| 44 |
+
>>> import torch
|
| 45 |
+
>>> input = torch.tensor([[[[0., 0., 0.],
|
| 46 |
+
... [0., 0., 0.],
|
| 47 |
+
... [0., 1., 1.]]]])
|
| 48 |
+
>>> seq = RandomVerticalFlip(p=1.0)
|
| 49 |
+
>>> seq(input), seq.transform_matrix
|
| 50 |
+
(tensor([[[[0., 1., 1.],
|
| 51 |
+
[0., 0., 0.],
|
| 52 |
+
[0., 0., 0.]]]]), tensor([[[ 1., 0., 0.],
|
| 53 |
+
[ 0., -1., 2.],
|
| 54 |
+
[ 0., 0., 1.]]]))
|
| 55 |
+
>>> seq.inverse(seq(input)).equal(input)
|
| 56 |
+
True
|
| 57 |
+
|
| 58 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 59 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 60 |
+
>>> seq = RandomVerticalFlip(p=1.0)
|
| 61 |
+
>>> (seq(input) == seq(input, params=seq._params)).all()
|
| 62 |
+
tensor(True)
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 67 |
+
h: int = int(params["forward_input_shape"][-2])
|
| 68 |
+
flip_mat: Tensor = tensor([[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype)
|
| 69 |
+
|
| 70 |
+
return flip_mat.expand(input.shape[0], 3, 3)
|
| 71 |
+
|
| 72 |
+
def apply_transform(
|
| 73 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 74 |
+
) -> Tensor:
|
| 75 |
+
return vflip(input)
|
| 76 |
+
|
| 77 |
+
def inverse_transform(
|
| 78 |
+
self,
|
| 79 |
+
input: Tensor,
|
| 80 |
+
flags: Dict[str, Any],
|
| 81 |
+
transform: Optional[Tensor] = None,
|
| 82 |
+
size: Optional[Tuple[int, int]] = None,
|
| 83 |
+
) -> Tensor:
|
| 84 |
+
if not isinstance(transform, Tensor):
|
| 85 |
+
raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
|
| 86 |
+
return self.apply_transform(
|
| 87 |
+
input,
|
| 88 |
+
params=self._params,
|
| 89 |
+
transform=as_tensor(transform, device=input.device, dtype=input.dtype),
|
| 90 |
+
flags=flags,
|
| 91 |
+
)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/auto_contrast.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 21 |
+
from kornia.core import Tensor
|
| 22 |
+
from kornia.enhance import normalize_min_max
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class RandomAutoContrast(IntensityAugmentationBase2D):
|
| 26 |
+
r"""Apply a random auto-contrast of a tensor image.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
p: probability of applying the transformation.
|
| 30 |
+
clip_output: if true clip output
|
| 31 |
+
same_on_batch: apply the same transformation across the batch.
|
| 32 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 33 |
+
to the batch form (False).
|
| 34 |
+
Shape:
|
| 35 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
|
| 36 |
+
- Output: :math:`(B, C, H, W)`
|
| 37 |
+
|
| 38 |
+
.. note::
|
| 39 |
+
This function internally uses :func:`kornia.enhance.normalize_min_max`
|
| 40 |
+
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self, clip_output: bool = True, same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False
|
| 45 |
+
) -> None:
|
| 46 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 47 |
+
|
| 48 |
+
self.clip_output = clip_output
|
| 49 |
+
|
| 50 |
+
def apply_transform(
|
| 51 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 52 |
+
) -> Tensor:
|
| 53 |
+
out = normalize_min_max(input)
|
| 54 |
+
|
| 55 |
+
if self.clip_output:
|
| 56 |
+
return out.clamp(0.0, 1.0)
|
| 57 |
+
|
| 58 |
+
return out
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/base.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional
|
| 19 |
+
|
| 20 |
+
from torch import Tensor
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D
|
| 23 |
+
from kornia.geometry.boxes import Boxes
|
| 24 |
+
from kornia.geometry.keypoints import Keypoints
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):
|
| 28 |
+
r"""IntensityAugmentationBase2D base class for customized intensity augmentation implementations.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
p: probability for applying an augmentation. This param controls the augmentation probabilities
|
| 32 |
+
element-wise for a batch.
|
| 33 |
+
p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
|
| 34 |
+
probabilities batch-wise.
|
| 35 |
+
same_on_batch: apply the same transformation across the batch.
|
| 36 |
+
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
|
| 37 |
+
to the batch form ``False``.
|
| 38 |
+
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 42 |
+
return self.identity_matrix(input)
|
| 43 |
+
|
| 44 |
+
def apply_non_transform(
|
| 45 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 46 |
+
) -> Tensor:
|
| 47 |
+
# For the images where batch_prob == False.
|
| 48 |
+
return input
|
| 49 |
+
|
| 50 |
+
def apply_non_transform_mask(
|
| 51 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 52 |
+
) -> Tensor:
|
| 53 |
+
return input
|
| 54 |
+
|
| 55 |
+
def apply_transform_mask(
|
| 56 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 57 |
+
) -> Tensor:
|
| 58 |
+
return input
|
| 59 |
+
|
| 60 |
+
def apply_non_transform_boxes(
|
| 61 |
+
self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 62 |
+
) -> Boxes:
|
| 63 |
+
return input
|
| 64 |
+
|
| 65 |
+
def apply_transform_boxes(
|
| 66 |
+
self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 67 |
+
) -> Boxes:
|
| 68 |
+
return input
|
| 69 |
+
|
| 70 |
+
def apply_non_transform_keypoint(
|
| 71 |
+
self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 72 |
+
) -> Keypoints:
|
| 73 |
+
return input
|
| 74 |
+
|
| 75 |
+
def apply_transform_keypoint(
|
| 76 |
+
self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 77 |
+
) -> Keypoints:
|
| 78 |
+
return input
|
| 79 |
+
|
| 80 |
+
def apply_non_transform_class(
|
| 81 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 82 |
+
) -> Tensor:
|
| 83 |
+
return input
|
| 84 |
+
|
| 85 |
+
def apply_transform_class(
|
| 86 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 87 |
+
) -> Tensor:
|
| 88 |
+
return input
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/box_blur.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from torch import Tensor
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 23 |
+
from kornia.filters import box_blur
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RandomBoxBlur(IntensityAugmentationBase2D):
|
| 27 |
+
"""Add random blur with a box filter to an image tensor.
|
| 28 |
+
|
| 29 |
+
.. image:: _static/img/RandomBoxBlur.png
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
kernel_size: the blurring kernel size.
|
| 33 |
+
border_type: the padding mode to be applied before convolving.
|
| 34 |
+
The expected modes are: ``constant``, ``reflect``, ``replicate`` or ``circular``.
|
| 35 |
+
normalized: if True, L1 norm of the kernel is set to 1.
|
| 36 |
+
same_on_batch: apply the same transformation across the batch.
|
| 37 |
+
p: probability of applying the transformation.
|
| 38 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 39 |
+
to the batch form (False).
|
| 40 |
+
.. note::
|
| 41 |
+
This function internally uses :func:`kornia.filters.box_blur`.
|
| 42 |
+
|
| 43 |
+
Examples:
|
| 44 |
+
>>> img = torch.ones(1, 1, 24, 24)
|
| 45 |
+
>>> out = RandomBoxBlur((7, 7))(img)
|
| 46 |
+
>>> out.shape
|
| 47 |
+
torch.Size([1, 1, 24, 24])
|
| 48 |
+
|
| 49 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 50 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 51 |
+
>>> aug = RandomBoxBlur((7, 7), p=1.)
|
| 52 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 53 |
+
tensor(True)
|
| 54 |
+
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
kernel_size: Tuple[int, int] = (3, 3),
|
| 60 |
+
border_type: str = "reflect",
|
| 61 |
+
normalized: bool = True,
|
| 62 |
+
same_on_batch: bool = False,
|
| 63 |
+
p: float = 0.5,
|
| 64 |
+
keepdim: bool = False,
|
| 65 |
+
) -> None:
|
| 66 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 67 |
+
self.flags = {"kernel_size": kernel_size, "border_type": border_type, "normalized": normalized}
|
| 68 |
+
|
| 69 |
+
def apply_transform(
|
| 70 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 71 |
+
) -> Tensor:
|
| 72 |
+
return box_blur(input, flags["kernel_size"], flags["border_type"], flags["normalized"])
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/brightness.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 22 |
+
from kornia.augmentation.utils import _range_bound
|
| 23 |
+
from kornia.core import Tensor
|
| 24 |
+
from kornia.enhance.adjust import adjust_brightness
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RandomBrightness(IntensityAugmentationBase2D):
|
| 28 |
+
r"""Apply a random transformation to the brightness of a tensor image.
|
| 29 |
+
|
| 30 |
+
This implementation aligns PIL. Hence, the output is close to TorchVision.
|
| 31 |
+
|
| 32 |
+
.. image:: _static/img/RandomBrightness.png
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
brightness: the brightness factor to apply
|
| 36 |
+
clip_output: if true clip output
|
| 37 |
+
silence_instantiation_warning: if True, silence the warning at instantiation.
|
| 38 |
+
same_on_batch: apply the same transformation across the batch.
|
| 39 |
+
p: probability of applying the transformation.
|
| 40 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 41 |
+
to the batch form (False).
|
| 42 |
+
Shape:
|
| 43 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 44 |
+
- Output: :math:`(B, C, H, W)`
|
| 45 |
+
|
| 46 |
+
.. note::
|
| 47 |
+
This function internally uses :func:`kornia.enhance.adjust_brightness`
|
| 48 |
+
|
| 49 |
+
Examples:
|
| 50 |
+
>>> rng = torch.manual_seed(0)
|
| 51 |
+
>>> inputs = torch.rand(1, 3, 3, 3)
|
| 52 |
+
>>> aug = RandomBrightness(brightness = (0.5,2.),p=1.)
|
| 53 |
+
>>> aug(inputs)
|
| 54 |
+
tensor([[[[0.0505, 0.3225, 0.0000],
|
| 55 |
+
[0.0000, 0.0000, 0.1883],
|
| 56 |
+
[0.0443, 0.4507, 0.0099]],
|
| 57 |
+
<BLANKLINE>
|
| 58 |
+
[[0.1866, 0.0000, 0.0000],
|
| 59 |
+
[0.0000, 0.0000, 0.0000],
|
| 60 |
+
[0.0728, 0.2519, 0.3543]],
|
| 61 |
+
<BLANKLINE>
|
| 62 |
+
[[0.0000, 0.0000, 0.2359],
|
| 63 |
+
[0.4694, 0.0000, 0.4284],
|
| 64 |
+
[0.0000, 0.1072, 0.5070]]]])
|
| 65 |
+
|
| 66 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 67 |
+
|
| 68 |
+
>>> input = torch.rand(1, 3, 32, 32)
|
| 69 |
+
>>> aug = RandomBrightness((0.8,1.2), p=1.)
|
| 70 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 71 |
+
tensor(True)
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
brightness: Tuple[float, float] = (1.0, 1.0),
|
| 78 |
+
clip_output: bool = True,
|
| 79 |
+
same_on_batch: bool = False,
|
| 80 |
+
p: float = 1.0,
|
| 81 |
+
keepdim: bool = False,
|
| 82 |
+
) -> None:
|
| 83 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 84 |
+
self.brightness: Tensor = _range_bound(brightness, "brightness", center=1.0, bounds=(0.0, 2.0))
|
| 85 |
+
self._param_generator = rg.PlainUniformGenerator((self.brightness, "brightness_factor", None, None))
|
| 86 |
+
|
| 87 |
+
self.clip_output = clip_output
|
| 88 |
+
|
| 89 |
+
def apply_transform(
|
| 90 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 91 |
+
) -> Tensor:
|
| 92 |
+
brightness_factor = params["brightness_factor"].to(input)
|
| 93 |
+
return adjust_brightness(input, brightness_factor - 1, self.clip_output)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/channel_dropout.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 21 |
+
from kornia.augmentation.random_generator._2d import ChannelDropoutGenerator
|
| 22 |
+
from kornia.core import Tensor, tensor
|
| 23 |
+
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RandomChannelDropout(IntensityAugmentationBase2D):
|
| 27 |
+
r"""Apply random channel dropout to a batch of images.
|
| 28 |
+
|
| 29 |
+
.. image:: _static/img/RandomChannelDropout.png
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
num_drop_channels: Number of channels to drop randomly. Default is 1.
|
| 33 |
+
fill_value: Value to fill the dropped channels with. Default is 0.0.
|
| 34 |
+
same_on_batch: Apply the same transformation across the batch. Defaults to False.
|
| 35 |
+
p: Probability of applying the transformation. Defaults to 0.5.
|
| 36 |
+
keepdim: Whether to keep the output shape the same as input ``True`` or broadcast it
|
| 37 |
+
to the batch form ``False``. Defaults to False.
|
| 38 |
+
|
| 39 |
+
Shape:
|
| 40 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
|
| 41 |
+
- Output: :math:`(C, H, W)` or :math:`(B, C, H, W)`
|
| 42 |
+
|
| 43 |
+
.. note::
|
| 44 |
+
If `num_drop_channels` is set to 1, it means that for each image in the batch,
|
| 45 |
+
we will randomly choose one channel to drop.
|
| 46 |
+
If `num_drop_channels` is set to 2, it means that for each image in the batch,
|
| 47 |
+
we will randomly choose two channels to drop.
|
| 48 |
+
If num_drop_channels is set to 3, it means that for each image in the batch,
|
| 49 |
+
we will randomly choose three channels to drop (all image).
|
| 50 |
+
|
| 51 |
+
Examples:
|
| 52 |
+
>>> rng = torch.manual_seed(1)
|
| 53 |
+
>>> img = torch.ones(1, 3, 3, 3)
|
| 54 |
+
>>> aug = RandomChannelDropout(num_drop_channels=1, fill_value=0.0, p=1.0)
|
| 55 |
+
>>> aug(img)
|
| 56 |
+
tensor([[[[1., 1., 1.],
|
| 57 |
+
[1., 1., 1.],
|
| 58 |
+
[1., 1., 1.]],
|
| 59 |
+
<BLANKLINE>
|
| 60 |
+
[[0., 0., 0.],
|
| 61 |
+
[0., 0., 0.],
|
| 62 |
+
[0., 0., 0.]],
|
| 63 |
+
<BLANKLINE>
|
| 64 |
+
[[1., 1., 1.],
|
| 65 |
+
[1., 1., 1.],
|
| 66 |
+
[1., 1., 1.]]]])
|
| 67 |
+
|
| 68 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 69 |
+
>>> input = torch.rand(1, 3, 32, 32)
|
| 70 |
+
>>> aug = RandomChannelDropout(num_drop_channels=1, fill_value=0.0, p=1.0)
|
| 71 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 72 |
+
tensor(True)
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
num_drop_channels: int = 1,
|
| 79 |
+
fill_value: float = 0.0,
|
| 80 |
+
same_on_batch: bool = False,
|
| 81 |
+
p: float = 0.5,
|
| 82 |
+
keepdim: bool = False,
|
| 83 |
+
) -> None:
|
| 84 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 85 |
+
|
| 86 |
+
KORNIA_CHECK_TYPE(fill_value, float, f"`fill_value` must be a float. Got: {type(fill_value)}")
|
| 87 |
+
KORNIA_CHECK(
|
| 88 |
+
0.0 <= fill_value <= 1.0,
|
| 89 |
+
f"Invalid value in `fill_value`. Must be a float between 0 and 1. Got: {fill_value}",
|
| 90 |
+
)
|
| 91 |
+
self.fill_value = tensor(fill_value)
|
| 92 |
+
|
| 93 |
+
KORNIA_CHECK_TYPE(num_drop_channels, int, f"`num_drop_channels` must be an int. Got: {type(num_drop_channels)}")
|
| 94 |
+
KORNIA_CHECK(
|
| 95 |
+
num_drop_channels >= 1,
|
| 96 |
+
f"Invalid value in `num_drop_channels`. Must be an int greater than 1. Got: {num_drop_channels}",
|
| 97 |
+
)
|
| 98 |
+
self.num_drop_channels = num_drop_channels
|
| 99 |
+
# Generator of random parameters.
|
| 100 |
+
self._param_generator = ChannelDropoutGenerator(self.num_drop_channels)
|
| 101 |
+
|
| 102 |
+
def apply_transform(
|
| 103 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 104 |
+
) -> Tensor:
|
| 105 |
+
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
|
| 106 |
+
KORNIA_CHECK(
|
| 107 |
+
self.num_drop_channels <= input.shape[1],
|
| 108 |
+
"Invalid value in `num_drop_channels`. Cannot be greater than the number of channels of `input`.",
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
out = input.clone()
|
| 112 |
+
out[params["batch_idx"], params["channel_idx"], ...] = self.fill_value.to(
|
| 113 |
+
device=input.device, dtype=input.dtype
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
return out
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/channel_shuffle.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 23 |
+
from kornia.core import Tensor
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RandomChannelShuffle(IntensityAugmentationBase2D):
|
| 27 |
+
r"""Shuffle the channels of a batch of multi-dimensional images.
|
| 28 |
+
|
| 29 |
+
.. image:: _static/img/RandomChannelShuffle.png
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
same_on_batch: apply the same transformation across the batch.
|
| 33 |
+
p: probability of applying the transformation.
|
| 34 |
+
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
|
| 35 |
+
to the batch form ``False``.
|
| 36 |
+
|
| 37 |
+
Examples:
|
| 38 |
+
>>> rng = torch.manual_seed(0)
|
| 39 |
+
>>> img = torch.arange(1*2*2*2.).view(1,2,2,2)
|
| 40 |
+
>>> RandomChannelShuffle()(img)
|
| 41 |
+
tensor([[[[4., 5.],
|
| 42 |
+
[6., 7.]],
|
| 43 |
+
<BLANKLINE>
|
| 44 |
+
[[0., 1.],
|
| 45 |
+
[2., 3.]]]])
|
| 46 |
+
|
| 47 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 48 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 49 |
+
>>> aug = RandomChannelShuffle(p=1.)
|
| 50 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 51 |
+
tensor(True)
|
| 52 |
+
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
|
| 56 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 57 |
+
|
| 58 |
+
def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:
|
| 59 |
+
B, C, _, _ = shape
|
| 60 |
+
channels = torch.rand(B, C).argsort(dim=1)
|
| 61 |
+
return {"channels": channels}
|
| 62 |
+
|
| 63 |
+
def apply_transform(
|
| 64 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 65 |
+
) -> Tensor:
|
| 66 |
+
out = torch.empty_like(input)
|
| 67 |
+
for i in range(out.shape[0]):
|
| 68 |
+
out[i] = input[i, params["channels"][i]]
|
| 69 |
+
return out
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/clahe.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
from typing import Any, Optional
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation import random_generator as rg
|
| 23 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 24 |
+
from kornia.core import Tensor
|
| 25 |
+
from kornia.enhance import equalize_clahe
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class RandomClahe(IntensityAugmentationBase2D):
|
| 29 |
+
r"""Apply CLAHE equalization on the input tensor randomly.
|
| 30 |
+
|
| 31 |
+
.. image:: _static/img/equalize_clahe.png
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
clip_limit: threshold value for contrast limiting. If 0 clipping is disabled.
|
| 35 |
+
grid_size: number of tiles to be cropped in each direction (GH, GW).
|
| 36 |
+
slow_and_differentiable: flag to select implementation
|
| 37 |
+
same_on_batch: apply the same transformation across the batch.
|
| 38 |
+
p: probability of applying the transformation.
|
| 39 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 40 |
+
to the batch form (False).
|
| 41 |
+
.. note::
|
| 42 |
+
This function internally uses :func:`kornia.enhance.equalize_clahe`.
|
| 43 |
+
|
| 44 |
+
Examples:
|
| 45 |
+
>>> img = torch.rand(1, 10, 20)
|
| 46 |
+
>>> aug = RandomClahe()
|
| 47 |
+
>>> res = aug(img)
|
| 48 |
+
>>> res.shape
|
| 49 |
+
torch.Size([1, 1, 10, 20])
|
| 50 |
+
|
| 51 |
+
>>> img = torch.rand(2, 3, 10, 20)
|
| 52 |
+
>>> aug = RandomClahe()
|
| 53 |
+
>>> res = aug(img)
|
| 54 |
+
>>> res.shape
|
| 55 |
+
torch.Size([2, 3, 10, 20])
|
| 56 |
+
|
| 57 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 58 |
+
>>> input = torch.rand(1, 3, 32, 32)
|
| 59 |
+
>>> aug = RandomClahe(p=1.)
|
| 60 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 61 |
+
tensor(True)
|
| 62 |
+
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
clip_limit: tuple[float, float] = (40.0, 40.0),
|
| 68 |
+
grid_size: tuple[int, int] = (8, 8),
|
| 69 |
+
slow_and_differentiable: bool = False,
|
| 70 |
+
same_on_batch: bool = False,
|
| 71 |
+
p: float = 0.5,
|
| 72 |
+
keepdim: bool = False,
|
| 73 |
+
) -> None:
|
| 74 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 75 |
+
self.clip_limit = clip_limit
|
| 76 |
+
self._param_generator = rg.PlainUniformGenerator((self.clip_limit, "clip_limit_factor", None, None))
|
| 77 |
+
self.flags = {"grid_size": grid_size, "slow_and_differentiable": slow_and_differentiable}
|
| 78 |
+
|
| 79 |
+
def apply_transform(
|
| 80 |
+
self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None
|
| 81 |
+
) -> Tensor:
|
| 82 |
+
clip_limit = float(params["clip_limit_factor"][0])
|
| 83 |
+
return equalize_clahe(input, clip_limit, flags["grid_size"], flags["slow_and_differentiable"])
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/color_jiggle.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 22 |
+
from kornia.constants import pi
|
| 23 |
+
from kornia.core import Tensor
|
| 24 |
+
from kornia.enhance import adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ColorJiggle(IntensityAugmentationBase2D):
|
| 28 |
+
r"""Apply a random transformation to the brightness, contrast, saturation and hue of a tensor image.
|
| 29 |
+
|
| 30 |
+
.. image:: _static/img/ColorJiggle.png
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
p: probability of applying the transformation.
|
| 34 |
+
brightness: The brightness factor to apply.
|
| 35 |
+
contrast: The contrast factor to apply.
|
| 36 |
+
saturation: The saturation factor to apply.
|
| 37 |
+
hue: The hue factor to apply.
|
| 38 |
+
same_on_batch: apply the same transformation across the batch.
|
| 39 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 40 |
+
to the batch form (False).
|
| 41 |
+
Shape:
|
| 42 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 43 |
+
- Output: :math:`(B, C, H, W)`
|
| 44 |
+
|
| 45 |
+
.. note::
|
| 46 |
+
This function internally uses :func:`kornia.enhance.adjust_brightness`,
|
| 47 |
+
:func:`kornia.enhance.adjust_contrast`. :func:`kornia.enhance.adjust_saturation`,
|
| 48 |
+
:func:`kornia.enhance.adjust_hue`.
|
| 49 |
+
|
| 50 |
+
Examples:
|
| 51 |
+
>>> rng = torch.manual_seed(0)
|
| 52 |
+
>>> inputs = torch.ones(1, 3, 3, 3)
|
| 53 |
+
>>> aug = ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.)
|
| 54 |
+
>>> aug(inputs)
|
| 55 |
+
tensor([[[[0.9993, 0.9993, 0.9993],
|
| 56 |
+
[0.9993, 0.9993, 0.9993],
|
| 57 |
+
[0.9993, 0.9993, 0.9993]],
|
| 58 |
+
<BLANKLINE>
|
| 59 |
+
[[0.9993, 0.9993, 0.9993],
|
| 60 |
+
[0.9993, 0.9993, 0.9993],
|
| 61 |
+
[0.9993, 0.9993, 0.9993]],
|
| 62 |
+
<BLANKLINE>
|
| 63 |
+
[[0.9993, 0.9993, 0.9993],
|
| 64 |
+
[0.9993, 0.9993, 0.9993],
|
| 65 |
+
[0.9993, 0.9993, 0.9993]]]])
|
| 66 |
+
|
| 67 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 68 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 69 |
+
>>> aug = ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.)
|
| 70 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 71 |
+
tensor(True)
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
brightness: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
|
| 78 |
+
contrast: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
|
| 79 |
+
saturation: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
|
| 80 |
+
hue: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
|
| 81 |
+
same_on_batch: bool = False,
|
| 82 |
+
p: float = 1.0,
|
| 83 |
+
keepdim: bool = False,
|
| 84 |
+
) -> None:
|
| 85 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 86 |
+
self.brightness = brightness
|
| 87 |
+
self.contrast = contrast
|
| 88 |
+
self.saturation = saturation
|
| 89 |
+
self.hue = hue
|
| 90 |
+
self._param_generator = rg.ColorJiggleGenerator(brightness, contrast, saturation, hue)
|
| 91 |
+
|
| 92 |
+
def apply_transform(
|
| 93 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 94 |
+
) -> Tensor:
|
| 95 |
+
transforms = [
|
| 96 |
+
lambda img: adjust_brightness(img, params["brightness_factor"] - 1)
|
| 97 |
+
if (params["brightness_factor"] - 1 != 0).any()
|
| 98 |
+
else img,
|
| 99 |
+
lambda img: adjust_contrast(img, params["contrast_factor"])
|
| 100 |
+
if (params["contrast_factor"] != 1).any()
|
| 101 |
+
else img,
|
| 102 |
+
lambda img: adjust_saturation(img, params["saturation_factor"])
|
| 103 |
+
if (params["saturation_factor"] != 1).any()
|
| 104 |
+
else img,
|
| 105 |
+
lambda img: adjust_hue(img, params["hue_factor"] * 2 * pi) if (params["hue_factor"] != 0).any() else img,
|
| 106 |
+
]
|
| 107 |
+
|
| 108 |
+
jittered = input
|
| 109 |
+
for idx in params["order"].tolist():
|
| 110 |
+
t = transforms[idx]
|
| 111 |
+
jittered = t(jittered)
|
| 112 |
+
|
| 113 |
+
return jittered
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/color_jitter.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation import random_generator as rg
|
| 23 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 24 |
+
from kornia.constants import pi
|
| 25 |
+
from kornia.core import Tensor
|
| 26 |
+
from kornia.enhance import (
|
| 27 |
+
adjust_brightness_accumulative,
|
| 28 |
+
adjust_contrast_with_mean_subtraction,
|
| 29 |
+
adjust_hue,
|
| 30 |
+
adjust_saturation_with_gray_subtraction,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class ColorJitter(IntensityAugmentationBase2D):
|
| 35 |
+
r"""Apply a random transformation to the brightness, contrast, saturation and hue of a tensor image.
|
| 36 |
+
|
| 37 |
+
This implementation aligns PIL. Hence, the output is close to TorchVision. However, it does not
|
| 38 |
+
follow the color theory and is not be actively maintained. Prefer using
|
| 39 |
+
:func:`kornia.augmentation.ColorJiggle`
|
| 40 |
+
|
| 41 |
+
.. image:: _static/img/ColorJitter.png
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
brightness: The brightness factor to apply.
|
| 45 |
+
contrast: The contrast factor to apply.
|
| 46 |
+
saturation: The saturation factor to apply.
|
| 47 |
+
hue: The hue factor to apply.
|
| 48 |
+
silence_instantiation_warning: if True, silence the warning at instantiation.
|
| 49 |
+
same_on_batch: apply the same transformation across the batch.
|
| 50 |
+
p: probability of applying the transformation.
|
| 51 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 52 |
+
to the batch form (False).
|
| 53 |
+
Shape:
|
| 54 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 55 |
+
- Output: :math:`(B, C, H, W)`
|
| 56 |
+
|
| 57 |
+
.. note::
|
| 58 |
+
This function internally uses :func:`kornia.enhance.adjust_brightness_accumulative`,
|
| 59 |
+
:func:`kornia.enhance.adjust_contrast_with_mean_subtraction`,
|
| 60 |
+
:func:`kornia.enhance.adjust_saturation_with_gray_subtraction`,
|
| 61 |
+
:func:`kornia.enhance.adjust_hue`.
|
| 62 |
+
|
| 63 |
+
Examples:
|
| 64 |
+
>>> rng = torch.manual_seed(0)
|
| 65 |
+
>>> inputs = torch.ones(1, 3, 3, 3)
|
| 66 |
+
>>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)
|
| 67 |
+
>>> aug(inputs)
|
| 68 |
+
tensor([[[[0.9993, 0.9993, 0.9993],
|
| 69 |
+
[0.9993, 0.9993, 0.9993],
|
| 70 |
+
[0.9993, 0.9993, 0.9993]],
|
| 71 |
+
<BLANKLINE>
|
| 72 |
+
[[0.9993, 0.9993, 0.9993],
|
| 73 |
+
[0.9993, 0.9993, 0.9993],
|
| 74 |
+
[0.9993, 0.9993, 0.9993]],
|
| 75 |
+
<BLANKLINE>
|
| 76 |
+
[[0.9993, 0.9993, 0.9993],
|
| 77 |
+
[0.9993, 0.9993, 0.9993],
|
| 78 |
+
[0.9993, 0.9993, 0.9993]]]])
|
| 79 |
+
|
| 80 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 81 |
+
|
| 82 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 83 |
+
>>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)
|
| 84 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 85 |
+
tensor(True)
|
| 86 |
+
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
brightness: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
|
| 92 |
+
contrast: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
|
| 93 |
+
saturation: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
|
| 94 |
+
hue: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,
|
| 95 |
+
same_on_batch: bool = False,
|
| 96 |
+
p: float = 1.0,
|
| 97 |
+
keepdim: bool = False,
|
| 98 |
+
) -> None:
|
| 99 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 100 |
+
|
| 101 |
+
self.brightness = brightness
|
| 102 |
+
self.contrast = contrast
|
| 103 |
+
self.saturation = saturation
|
| 104 |
+
self.hue = hue
|
| 105 |
+
self._param_generator = rg.ColorJitterGenerator(brightness, contrast, saturation, hue)
|
| 106 |
+
|
| 107 |
+
# native functions
|
| 108 |
+
self._brightness_fn = adjust_brightness_accumulative
|
| 109 |
+
self._contrast_fn = adjust_contrast_with_mean_subtraction
|
| 110 |
+
self._saturation_fn = adjust_saturation_with_gray_subtraction
|
| 111 |
+
self._hue_fn = adjust_hue
|
| 112 |
+
|
| 113 |
+
def apply_transform(
|
| 114 |
+
self,
|
| 115 |
+
input: Tensor,
|
| 116 |
+
params: Dict[str, Tensor],
|
| 117 |
+
flags: Dict[str, Any],
|
| 118 |
+
transform: Optional[Tensor] = None,
|
| 119 |
+
) -> Tensor:
|
| 120 |
+
transforms = [
|
| 121 |
+
lambda img: (
|
| 122 |
+
self._brightness_fn(img, params["brightness_factor"])
|
| 123 |
+
if (params["brightness_factor"] != 0).any()
|
| 124 |
+
else img
|
| 125 |
+
),
|
| 126 |
+
lambda img: (
|
| 127 |
+
self._contrast_fn(img, params["contrast_factor"]) if (params["contrast_factor"] != 1).any() else img
|
| 128 |
+
),
|
| 129 |
+
lambda img: (
|
| 130 |
+
self._saturation_fn(img, params["saturation_factor"])
|
| 131 |
+
if (params["saturation_factor"] != 1).any()
|
| 132 |
+
else img
|
| 133 |
+
),
|
| 134 |
+
lambda img: (
|
| 135 |
+
self._hue_fn(img, params["hue_factor"] * 2 * pi) if (params["hue_factor"] != 0).any() else img
|
| 136 |
+
),
|
| 137 |
+
]
|
| 138 |
+
|
| 139 |
+
jittered = input
|
| 140 |
+
for idx in params["order"]:
|
| 141 |
+
t = transforms[idx]
|
| 142 |
+
jittered = t(jittered)
|
| 143 |
+
|
| 144 |
+
return jittered
|
| 145 |
+
|
| 146 |
+
def compile(
|
| 147 |
+
self,
|
| 148 |
+
*,
|
| 149 |
+
fullgraph: bool = False,
|
| 150 |
+
dynamic: bool = False,
|
| 151 |
+
backend: str = "inductor",
|
| 152 |
+
mode: Optional[str] = None,
|
| 153 |
+
options: Optional[Dict[Any, Any]] = None,
|
| 154 |
+
disable: bool = False,
|
| 155 |
+
) -> "ColorJitter":
|
| 156 |
+
self.brightness_fn = torch.compile(
|
| 157 |
+
self._brightness_fn,
|
| 158 |
+
fullgraph=fullgraph,
|
| 159 |
+
dynamic=dynamic,
|
| 160 |
+
backend=backend,
|
| 161 |
+
mode=mode,
|
| 162 |
+
options=options,
|
| 163 |
+
disable=disable,
|
| 164 |
+
)
|
| 165 |
+
self.contrast_fn = torch.compile(
|
| 166 |
+
self._contrast_fn,
|
| 167 |
+
fullgraph=fullgraph,
|
| 168 |
+
dynamic=dynamic,
|
| 169 |
+
backend=backend,
|
| 170 |
+
mode=mode,
|
| 171 |
+
options=options,
|
| 172 |
+
disable=disable,
|
| 173 |
+
)
|
| 174 |
+
self.saturation_fn = torch.compile(
|
| 175 |
+
self._saturation_fn,
|
| 176 |
+
fullgraph=fullgraph,
|
| 177 |
+
dynamic=dynamic,
|
| 178 |
+
backend=backend,
|
| 179 |
+
mode=mode,
|
| 180 |
+
options=options,
|
| 181 |
+
disable=disable,
|
| 182 |
+
)
|
| 183 |
+
self.hue_fn = torch.compile(
|
| 184 |
+
self._hue_fn,
|
| 185 |
+
fullgraph=fullgraph,
|
| 186 |
+
dynamic=dynamic,
|
| 187 |
+
backend=backend,
|
| 188 |
+
mode=mode,
|
| 189 |
+
options=options,
|
| 190 |
+
disable=disable,
|
| 191 |
+
)
|
| 192 |
+
return self
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/contrast.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 22 |
+
from kornia.augmentation.utils import _range_bound
|
| 23 |
+
from kornia.core import Tensor
|
| 24 |
+
from kornia.enhance.adjust import adjust_contrast
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RandomContrast(IntensityAugmentationBase2D):
|
| 28 |
+
r"""Apply a random transformation to the contrast of a tensor image.
|
| 29 |
+
|
| 30 |
+
This implementation aligns PIL. Hence, the output is close to TorchVision.
|
| 31 |
+
|
| 32 |
+
.. image:: _static/img/RandomContrast.png
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
contrast: the contrast factor to apply.
|
| 36 |
+
clip_output: if true clip output.
|
| 37 |
+
same_on_batch: apply the same transformation across the batch.
|
| 38 |
+
p: probability of applying the transformation.
|
| 39 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 40 |
+
to the batch form (False).
|
| 41 |
+
Shape:
|
| 42 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 43 |
+
- Output: :math:`(B, C, H, W)`
|
| 44 |
+
|
| 45 |
+
.. note::
|
| 46 |
+
This function internally uses :func:`kornia.enhance.adjust_contrast`
|
| 47 |
+
|
| 48 |
+
Examples:
|
| 49 |
+
>>> rng = torch.manual_seed(0)
|
| 50 |
+
>>> inputs = torch.rand(1, 3, 3, 3)
|
| 51 |
+
>>> aug = RandomContrast(contrast = (0.5, 2.), p = 1.)
|
| 52 |
+
>>> aug(inputs)
|
| 53 |
+
tensor([[[[0.2750, 0.4258, 0.0490],
|
| 54 |
+
[0.0732, 0.1704, 0.3514],
|
| 55 |
+
[0.2716, 0.4969, 0.2525]],
|
| 56 |
+
<BLANKLINE>
|
| 57 |
+
[[0.3505, 0.1934, 0.2227],
|
| 58 |
+
[0.0124, 0.0936, 0.1629],
|
| 59 |
+
[0.2874, 0.3867, 0.4434]],
|
| 60 |
+
<BLANKLINE>
|
| 61 |
+
[[0.0893, 0.1564, 0.3778],
|
| 62 |
+
[0.5072, 0.2201, 0.4845],
|
| 63 |
+
[0.2325, 0.3064, 0.5281]]]])
|
| 64 |
+
|
| 65 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 66 |
+
|
| 67 |
+
>>> input = torch.rand(1, 3, 32, 32)
|
| 68 |
+
>>> aug = RandomContrast((0.8,1.2), p=1.)
|
| 69 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 70 |
+
tensor(True)
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(
|
| 75 |
+
self,
|
| 76 |
+
contrast: Tuple[float, float] = (1.0, 1.0),
|
| 77 |
+
clip_output: bool = True,
|
| 78 |
+
same_on_batch: bool = False,
|
| 79 |
+
p: float = 1.0,
|
| 80 |
+
keepdim: bool = False,
|
| 81 |
+
) -> None:
|
| 82 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 83 |
+
self.contrast: Tensor = _range_bound(contrast, "contrast", center=1.0)
|
| 84 |
+
self._param_generator = rg.PlainUniformGenerator((self.contrast, "contrast_factor", None, None))
|
| 85 |
+
|
| 86 |
+
self.clip_output = clip_output
|
| 87 |
+
|
| 88 |
+
def apply_transform(
|
| 89 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 90 |
+
) -> Tensor:
|
| 91 |
+
contrast_factor = params["contrast_factor"].to(input)
|
| 92 |
+
return adjust_contrast(input, contrast_factor, self.clip_output)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/denormalize.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import Tensor
|
| 22 |
+
|
| 23 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 24 |
+
from kornia.enhance import denormalize
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class Denormalize(IntensityAugmentationBase2D):
|
| 28 |
+
r"""Denormalize tensor images with mean and standard deviation.
|
| 29 |
+
|
| 30 |
+
.. math::
|
| 31 |
+
\text{input[channel] = (input[channel] * std[channel]) + mean[channel]}
|
| 32 |
+
|
| 33 |
+
Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
mean: Mean for each channel.
|
| 37 |
+
std: Standard deviations for each channel.
|
| 38 |
+
same_on_batch: apply the same transformation across the batch.
|
| 39 |
+
p: probability of applying the transformation.
|
| 40 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 41 |
+
to the batch form (False).
|
| 42 |
+
|
| 43 |
+
Return:
|
| 44 |
+
Denormalised tensor with same size as input :math:`(*, C, H, W)`.
|
| 45 |
+
|
| 46 |
+
.. note::
|
| 47 |
+
This function internally uses :func:`kornia.enhance.denormalize`.
|
| 48 |
+
|
| 49 |
+
Examples:
|
| 50 |
+
>>> norm = Denormalize(mean=torch.zeros(1, 4), std=torch.ones(1, 4))
|
| 51 |
+
>>> x = torch.rand(1, 4, 3, 3)
|
| 52 |
+
>>> out = norm(x)
|
| 53 |
+
>>> out.shape
|
| 54 |
+
torch.Size([1, 4, 3, 3])
|
| 55 |
+
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
def __init__(
|
| 59 |
+
self,
|
| 60 |
+
mean: Union[Tensor, Tuple[float], List[float], float],
|
| 61 |
+
std: Union[Tensor, Tuple[float], List[float], float],
|
| 62 |
+
p: float = 1.0,
|
| 63 |
+
keepdim: bool = False,
|
| 64 |
+
) -> None:
|
| 65 |
+
super().__init__(p=p, same_on_batch=True, keepdim=keepdim)
|
| 66 |
+
if isinstance(mean, float):
|
| 67 |
+
mean = torch.tensor([mean])
|
| 68 |
+
|
| 69 |
+
if isinstance(std, float):
|
| 70 |
+
std = torch.tensor([std])
|
| 71 |
+
|
| 72 |
+
if isinstance(mean, (tuple, list)):
|
| 73 |
+
mean = torch.tensor(mean)
|
| 74 |
+
|
| 75 |
+
if isinstance(std, (tuple, list)):
|
| 76 |
+
std = torch.tensor(std)
|
| 77 |
+
|
| 78 |
+
self.flags = {"mean": mean, "std": std}
|
| 79 |
+
|
| 80 |
+
def apply_transform(
|
| 81 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 82 |
+
) -> Tensor:
|
| 83 |
+
return denormalize(input, flags["mean"], flags["std"])
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/dissolving.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 22 |
+
from kornia.core import Tensor
|
| 23 |
+
from kornia.filters import StableDiffusionDissolving
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RandomDissolving(IntensityAugmentationBase2D):
|
| 27 |
+
r"""Perform dissolving transformation using StableDiffusion models.
|
| 28 |
+
|
| 29 |
+
Based on :cite:`shi2024dissolving`, the dissolving transformation is essentially applying one-step
|
| 30 |
+
reverse diffusion. Our implementation currently supports HuggingFace implementations of SD 1.4, 1.5
|
| 31 |
+
and 2.1. SD 1.X tends to remove more details than SD2.1.
|
| 32 |
+
|
| 33 |
+
.. list-table:: Title
|
| 34 |
+
:widths: 32 32 32
|
| 35 |
+
:header-rows: 1
|
| 36 |
+
|
| 37 |
+
* - SD 1.4
|
| 38 |
+
- SD 1.5
|
| 39 |
+
- SD 2.1
|
| 40 |
+
* - figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-1.4.png
|
| 41 |
+
- figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-1.5.png
|
| 42 |
+
- figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-2.1.png
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
p: probability of applying the transformation.
|
| 46 |
+
version: the version of the stable diffusion model.
|
| 47 |
+
step_range: the step range of the diffusion model steps. Higher the step, stronger
|
| 48 |
+
the dissolving effects.
|
| 49 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 50 |
+
to the batch form (False).
|
| 51 |
+
**kwargs: additional arguments for `.from_pretrained` for HF StableDiffusionPipeline.
|
| 52 |
+
|
| 53 |
+
Shape:
|
| 54 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`.
|
| 55 |
+
- Output: :math:`(B, C, H, W)`
|
| 56 |
+
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
step_range: Tuple[float, float] = (100, 500),
|
| 62 |
+
version: str = "2.1",
|
| 63 |
+
p: float = 0.5,
|
| 64 |
+
keepdim: bool = False,
|
| 65 |
+
**kwargs: Any,
|
| 66 |
+
) -> None:
|
| 67 |
+
super().__init__(p=p, same_on_batch=True, keepdim=keepdim)
|
| 68 |
+
self.step_range = step_range
|
| 69 |
+
self._dslv = StableDiffusionDissolving(version, **kwargs)
|
| 70 |
+
self._param_generator = rg.PlainUniformGenerator((self.step_range, "step_range_factor", None, None))
|
| 71 |
+
|
| 72 |
+
def apply_transform(
|
| 73 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 74 |
+
) -> Tensor:
|
| 75 |
+
return self._dslv(input, params["step_range_factor"][0].long().item())
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/equalize.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional
|
| 19 |
+
|
| 20 |
+
from torch import Tensor
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 23 |
+
from kornia.enhance import equalize
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RandomEqualize(IntensityAugmentationBase2D):
|
| 27 |
+
r"""Equalize given tensor image or a batch of tensor images randomly.
|
| 28 |
+
|
| 29 |
+
.. image:: _static/img/RandomEqualize.png
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
p: Probability to equalize an image.
|
| 33 |
+
same_on_batch: apply the same transformation across the batch.
|
| 34 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 35 |
+
to the batch form (False).
|
| 36 |
+
|
| 37 |
+
Shape:
|
| 38 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 39 |
+
- Output: :math:`(B, C, H, W)`
|
| 40 |
+
|
| 41 |
+
.. note::
|
| 42 |
+
This function internally uses :func:`kornia.enhance.equalize`.
|
| 43 |
+
|
| 44 |
+
Examples:
|
| 45 |
+
>>> rng = torch.manual_seed(0)
|
| 46 |
+
>>> input = torch.rand(1, 1, 5, 5)
|
| 47 |
+
>>> equalize = RandomEqualize(p=1.)
|
| 48 |
+
>>> equalize(input)
|
| 49 |
+
tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],
|
| 50 |
+
[0.6341, 0.4901, 0.8964, 0.4556, 0.6323],
|
| 51 |
+
[0.3489, 0.4017, 0.0223, 0.1689, 0.2939],
|
| 52 |
+
[0.5185, 0.6977, 0.8000, 0.1610, 0.2823],
|
| 53 |
+
[0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
|
| 54 |
+
|
| 55 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 56 |
+
>>> input = torch.rand(1, 3, 32, 32)
|
| 57 |
+
>>> aug = RandomEqualize(p=1.)
|
| 58 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 59 |
+
tensor(True)
|
| 60 |
+
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
|
| 64 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 65 |
+
|
| 66 |
+
def apply_transform(
|
| 67 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 68 |
+
) -> Tensor:
|
| 69 |
+
return equalize(input)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/erasing.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 22 |
+
from kornia.core import Tensor, where
|
| 23 |
+
from kornia.geometry.bbox import bbox_generator, bbox_to_mask
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RandomErasing(IntensityAugmentationBase2D):
|
| 27 |
+
r"""Erase a random rectangle of a tensor image according to a probability p value.
|
| 28 |
+
|
| 29 |
+
.. image:: _static/img/RandomErasing.png
|
| 30 |
+
|
| 31 |
+
The operator removes image parts and fills them with zero values at a selected rectangle
|
| 32 |
+
for each of the images in the batch.
|
| 33 |
+
|
| 34 |
+
The rectangle will have an area equal to the original image area multiplied by a value uniformly
|
| 35 |
+
sampled between the range [scale[0], scale[1]) and an aspect ratio sampled
|
| 36 |
+
between [ratio[0], ratio[1])
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
scale: range of proportion of erased area against input image.
|
| 40 |
+
ratio: range of aspect ratio of erased area.
|
| 41 |
+
value: the value to fill the erased area.
|
| 42 |
+
same_on_batch: apply the same transformation across the batch.
|
| 43 |
+
p: probability that the random erasing operation will be performed.
|
| 44 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 45 |
+
to the batch form (False).
|
| 46 |
+
|
| 47 |
+
Shape:
|
| 48 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 49 |
+
- Output: :math:`(B, C, H, W)`
|
| 50 |
+
|
| 51 |
+
Note:
|
| 52 |
+
Input tensor must be float and normalized into [0, 1] for the best differentiability support.
|
| 53 |
+
Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
|
| 54 |
+
applied transformation will be merged int to the input transformation tensor and returned.
|
| 55 |
+
|
| 56 |
+
Examples:
|
| 57 |
+
>>> rng = torch.manual_seed(0)
|
| 58 |
+
>>> inputs = torch.ones(1, 1, 3, 3)
|
| 59 |
+
>>> aug = RandomErasing((.4, .8), (.3, 1/.3), p=0.5)
|
| 60 |
+
>>> aug(inputs)
|
| 61 |
+
tensor([[[[1., 0., 0.],
|
| 62 |
+
[1., 0., 0.],
|
| 63 |
+
[1., 0., 0.]]]])
|
| 64 |
+
|
| 65 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 66 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 67 |
+
>>> aug = RandomErasing((.4, .8), (.3, 1/.3), p=1.)
|
| 68 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 69 |
+
tensor(True)
|
| 70 |
+
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
scale: Union[Tensor, Tuple[float, float]] = (0.02, 0.33),
|
| 76 |
+
ratio: Union[Tensor, Tuple[float, float]] = (0.3, 3.3),
|
| 77 |
+
value: float = 0.0,
|
| 78 |
+
same_on_batch: bool = False,
|
| 79 |
+
p: float = 0.5,
|
| 80 |
+
keepdim: bool = False,
|
| 81 |
+
) -> None:
|
| 82 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 83 |
+
self.scale = scale
|
| 84 |
+
self.ratio = ratio
|
| 85 |
+
self.value = value
|
| 86 |
+
self._param_generator = rg.RectangleEraseGenerator(scale, ratio, value)
|
| 87 |
+
|
| 88 |
+
def apply_transform(
|
| 89 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 90 |
+
) -> Tensor:
|
| 91 |
+
_, c, h, w = input.size()
|
| 92 |
+
values = params["values"].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).repeat(1, *input.shape[1:]).to(input)
|
| 93 |
+
|
| 94 |
+
bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"])
|
| 95 |
+
mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W
|
| 96 |
+
mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W
|
| 97 |
+
transformed = where(mask == 1.0, values, input)
|
| 98 |
+
return transformed
|
| 99 |
+
|
| 100 |
+
def apply_transform_mask(
|
| 101 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 102 |
+
) -> Tensor:
|
| 103 |
+
_, c, h, w = input.size()
|
| 104 |
+
|
| 105 |
+
values = params["values"][..., None, None, None].repeat(1, *input.shape[1:]).to(input)
|
| 106 |
+
# Erase the corresponding areas on masks.
|
| 107 |
+
values = values.zero_()
|
| 108 |
+
|
| 109 |
+
bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"])
|
| 110 |
+
mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W
|
| 111 |
+
mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W
|
| 112 |
+
transformed = where(mask == 1.0, values, input)
|
| 113 |
+
return transformed
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gamma.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 22 |
+
from kornia.core import Tensor
|
| 23 |
+
from kornia.enhance.adjust import adjust_gamma
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RandomGamma(IntensityAugmentationBase2D):
|
| 27 |
+
r"""Apply a random transformation to the gamma of a tensor image.
|
| 28 |
+
|
| 29 |
+
This implementation aligns PIL. Hence, the output is close to TorchVision.
|
| 30 |
+
|
| 31 |
+
.. image:: _static/img/RandomGamma.png
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
p: probability of applying the transformation.
|
| 35 |
+
gamma: the gamma factor to apply.
|
| 36 |
+
gain: the gain factor to apply.
|
| 37 |
+
same_on_batch: apply the same transformation across the batch.
|
| 38 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 39 |
+
to the batch form (False).
|
| 40 |
+
Shape:
|
| 41 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 42 |
+
- Output: :math:`(B, C, H, W)`
|
| 43 |
+
|
| 44 |
+
.. note::
|
| 45 |
+
This function internally uses :func:`kornia.enhance.adjust_gamma`
|
| 46 |
+
|
| 47 |
+
Examples:
|
| 48 |
+
>>> rng = torch.manual_seed(0)
|
| 49 |
+
>>> inputs = torch.rand(1, 3, 3, 3)
|
| 50 |
+
>>> aug = RandomGamma((0.5,2.),(1.5,1.5),p=1.)
|
| 51 |
+
>>> aug(inputs)
|
| 52 |
+
tensor([[[[1.0000, 1.0000, 0.3912],
|
| 53 |
+
[0.4883, 0.7801, 1.0000],
|
| 54 |
+
[1.0000, 1.0000, 0.9702]],
|
| 55 |
+
<BLANKLINE>
|
| 56 |
+
[[1.0000, 0.8368, 0.9048],
|
| 57 |
+
[0.1824, 0.5597, 0.7609],
|
| 58 |
+
[1.0000, 1.0000, 1.0000]],
|
| 59 |
+
<BLANKLINE>
|
| 60 |
+
[[0.5452, 0.7441, 1.0000],
|
| 61 |
+
[1.0000, 0.8990, 1.0000],
|
| 62 |
+
[0.9267, 1.0000, 1.0000]]]])
|
| 63 |
+
|
| 64 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 65 |
+
>>> input = torch.rand(1, 3, 32, 32)
|
| 66 |
+
>>> aug = RandomGamma((0.8,1.2), p=1.)
|
| 67 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 68 |
+
tensor(True)
|
| 69 |
+
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self,
|
| 74 |
+
gamma: Tuple[float, float] = (1.0, 1.0),
|
| 75 |
+
gain: Tuple[float, float] = (1.0, 1.0),
|
| 76 |
+
same_on_batch: bool = False,
|
| 77 |
+
p: float = 1.0,
|
| 78 |
+
keepdim: bool = False,
|
| 79 |
+
) -> None:
|
| 80 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 81 |
+
self._param_generator = rg.PlainUniformGenerator(
|
| 82 |
+
(gamma, "gamma_factor", None, None), (gain, "gain_factor", None, None)
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def apply_transform(
|
| 86 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 87 |
+
) -> Tensor:
|
| 88 |
+
gamma_factor = params["gamma_factor"].to(input)
|
| 89 |
+
gain_factor = params["gain_factor"].to(input)
|
| 90 |
+
return adjust_gamma(input, gamma_factor, gain_factor)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_blur.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import Tensor
|
| 22 |
+
|
| 23 |
+
from kornia.augmentation import random_generator as rg
|
| 24 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 25 |
+
from kornia.constants import BorderType
|
| 26 |
+
from kornia.filters import gaussian_blur2d
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class RandomGaussianBlur(IntensityAugmentationBase2D):
|
| 30 |
+
r"""Apply gaussian blur given tensor image or a batch of tensor images randomly.
|
| 31 |
+
|
| 32 |
+
The standard deviation is sampled for each instance.
|
| 33 |
+
|
| 34 |
+
.. image:: _static/img/RandomGaussianBlur.png
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
kernel_size: the size of the kernel.
|
| 38 |
+
sigma: the range for the standard deviation of the kernel.
|
| 39 |
+
border_type: the padding mode to be applied before convolving.
|
| 40 |
+
The expected modes are: ``constant``, ``reflect``, ``replicate`` or ``circular``.
|
| 41 |
+
separable: run as composition of two 1d-convolutions.
|
| 42 |
+
same_on_batch: apply the same transformation across the batch.
|
| 43 |
+
p: probability of applying the transformation.
|
| 44 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 45 |
+
to the batch form (False).
|
| 46 |
+
silence_instantiation_warning: if True, silence the warning at instantiation.
|
| 47 |
+
|
| 48 |
+
Shape:
|
| 49 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 50 |
+
- Output: :math:`(B, C, H, W)`
|
| 51 |
+
|
| 52 |
+
.. note::
|
| 53 |
+
This function internally uses :func:`kornia.filters.gaussian_blur2d`.
|
| 54 |
+
|
| 55 |
+
Examples:
|
| 56 |
+
>>> rng = torch.manual_seed(0)
|
| 57 |
+
>>> input = torch.rand(1, 1, 5, 5)
|
| 58 |
+
>>> blur = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.)
|
| 59 |
+
>>> blur(input)
|
| 60 |
+
tensor([[[[0.5941, 0.5833, 0.5022, 0.4384, 0.3934],
|
| 61 |
+
[0.5310, 0.4964, 0.4113, 0.3637, 0.3472],
|
| 62 |
+
[0.4991, 0.4997, 0.4312, 0.3620, 0.3081],
|
| 63 |
+
[0.6082, 0.5667, 0.4954, 0.3825, 0.3508],
|
| 64 |
+
[0.7042, 0.6849, 0.6275, 0.4753, 0.4105]]]])
|
| 65 |
+
|
| 66 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 67 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 68 |
+
>>> aug = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.)
|
| 69 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 70 |
+
tensor(True)
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(
|
| 75 |
+
self,
|
| 76 |
+
kernel_size: Union[Tuple[int, int], int],
|
| 77 |
+
sigma: Union[Tuple[float, float], Tensor],
|
| 78 |
+
border_type: str = "reflect",
|
| 79 |
+
separable: bool = True,
|
| 80 |
+
same_on_batch: bool = False,
|
| 81 |
+
p: float = 0.5,
|
| 82 |
+
keepdim: bool = False,
|
| 83 |
+
) -> None:
|
| 84 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 85 |
+
|
| 86 |
+
self.flags = {
|
| 87 |
+
"kernel_size": kernel_size,
|
| 88 |
+
"separable": separable,
|
| 89 |
+
"border_type": BorderType.get(border_type),
|
| 90 |
+
}
|
| 91 |
+
self._param_generator = rg.RandomGaussianBlurGenerator(sigma)
|
| 92 |
+
|
| 93 |
+
self._gaussian_blur2d_fn = gaussian_blur2d
|
| 94 |
+
|
| 95 |
+
def apply_transform(
|
| 96 |
+
self,
|
| 97 |
+
input: Tensor,
|
| 98 |
+
params: Dict[str, Tensor],
|
| 99 |
+
flags: Dict[str, Any],
|
| 100 |
+
transform: Optional[Tensor] = None,
|
| 101 |
+
) -> Tensor:
|
| 102 |
+
sigma = params["sigma"].unsqueeze(-1).expand(-1, 2)
|
| 103 |
+
return self._gaussian_blur2d_fn(
|
| 104 |
+
input,
|
| 105 |
+
kernel_size=self.flags["kernel_size"],
|
| 106 |
+
sigma=sigma,
|
| 107 |
+
border_type=self.flags["border_type"].name.lower(),
|
| 108 |
+
separable=self.flags["separable"],
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def compile(
|
| 112 |
+
self,
|
| 113 |
+
*,
|
| 114 |
+
fullgraph: bool = False,
|
| 115 |
+
dynamic: bool = False,
|
| 116 |
+
backend: str = "inductor",
|
| 117 |
+
mode: Optional[str] = None,
|
| 118 |
+
options: Optional[Dict[Any, Any]] = None,
|
| 119 |
+
disable: bool = False,
|
| 120 |
+
) -> "RandomGaussianBlur":
|
| 121 |
+
self._gaussian_blur2d_fn = torch.compile(
|
| 122 |
+
self._gaussian_blur2d_fn,
|
| 123 |
+
fullgraph=fullgraph,
|
| 124 |
+
dynamic=dynamic,
|
| 125 |
+
backend=backend,
|
| 126 |
+
mode=mode,
|
| 127 |
+
options=options,
|
| 128 |
+
disable=disable,
|
| 129 |
+
)
|
| 130 |
+
return self
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_illumination.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 23 |
+
from kornia.augmentation.random_generator._2d import GaussianIlluminationGenerator
|
| 24 |
+
from kornia.core import Tensor
|
| 25 |
+
from kornia.core.check import KORNIA_CHECK
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class RandomGaussianIllumination(IntensityAugmentationBase2D):
|
| 29 |
+
r"""Applies random 2D Gaussian illumination patterns to a batch of images.
|
| 30 |
+
|
| 31 |
+
.. image:: _static/img/RandomGaussianIllumination.png
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
gain: Range for the gain factor (intensity) applied to the generated illumination.
|
| 35 |
+
center: The center coordinates of the Gaussian distribution are expressed as a
|
| 36 |
+
percentage of the spatial dimensions :math:(H, W).
|
| 37 |
+
sigma: The sigma values (standard deviation) of the Gaussian distribution are expressed as a
|
| 38 |
+
percentage of the spatial dimensions :math:(H, W).
|
| 39 |
+
sign: Range for the sign of the Gaussian distribution. If only one sign is needed,
|
| 40 |
+
insert only as a tuple or float.
|
| 41 |
+
p: Probability of applying the transformation.
|
| 42 |
+
same_on_batch: If True, apply the same transformation across the entire batch. Default is False.
|
| 43 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 44 |
+
to the batch form (False).
|
| 45 |
+
|
| 46 |
+
Shape:
|
| 47 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
|
| 48 |
+
- Output: :math:`(B, C, H, W)`
|
| 49 |
+
|
| 50 |
+
.. note::
|
| 51 |
+
The generated random numbers are not reproducible across different devices and dtypes. By default,
|
| 52 |
+
the parameters will be generated on CPU. This can be changed by calling
|
| 53 |
+
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
|
| 54 |
+
|
| 55 |
+
Examples:
|
| 56 |
+
>>> rng = torch.manual_seed(1)
|
| 57 |
+
>>> input = torch.ones(1, 3, 3, 3) * 0.5
|
| 58 |
+
>>> aug = RandomGaussianIllumination(gain=0.5, p=1.)
|
| 59 |
+
>>> aug(input)
|
| 60 |
+
tensor([[[[0.7266, 1.0000, 0.7266],
|
| 61 |
+
[0.6621, 0.9121, 0.6621],
|
| 62 |
+
[0.5000, 0.6911, 0.5000]],
|
| 63 |
+
<BLANKLINE>
|
| 64 |
+
[[0.7266, 1.0000, 0.7266],
|
| 65 |
+
[0.6621, 0.9121, 0.6621],
|
| 66 |
+
[0.5000, 0.6911, 0.5000]],
|
| 67 |
+
<BLANKLINE>
|
| 68 |
+
[[0.7266, 1.0000, 0.7266],
|
| 69 |
+
[0.6621, 0.9121, 0.6621],
|
| 70 |
+
[0.5000, 0.6911, 0.5000]]]])
|
| 71 |
+
|
| 72 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 73 |
+
>>> input = torch.rand(1, 3, 32, 32)
|
| 74 |
+
>>> aug = RandomGaussianIllumination(p=1.)
|
| 75 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 76 |
+
tensor(True)
|
| 77 |
+
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
gain: Optional[Union[float, Tuple[float, float]]] = (0.01, 0.15),
|
| 83 |
+
center: Optional[Union[float, Tuple[float, float]]] = (0.1, 0.9),
|
| 84 |
+
sigma: Optional[Union[float, Tuple[float, float]]] = (0.2, 1.0),
|
| 85 |
+
sign: Optional[Union[float, Tuple[float, float]]] = (-1.0, 1.0),
|
| 86 |
+
p: float = 0.5,
|
| 87 |
+
same_on_batch: bool = False,
|
| 88 |
+
keepdim: bool = False,
|
| 89 |
+
) -> None:
|
| 90 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 91 |
+
|
| 92 |
+
# Validation and initialization of amount parameter.
|
| 93 |
+
if isinstance(gain, (tuple, float)):
|
| 94 |
+
if isinstance(gain, float):
|
| 95 |
+
gain = (gain, gain)
|
| 96 |
+
elif len(gain) == 1:
|
| 97 |
+
gain = (gain[0], gain[0])
|
| 98 |
+
elif len(gain) > 2 or len(gain) <= 0:
|
| 99 |
+
raise ValueError(
|
| 100 |
+
"The length of gain must be greater than 0 \
|
| 101 |
+
and less than or equal to 2, and it should be a tuple or a float."
|
| 102 |
+
)
|
| 103 |
+
else:
|
| 104 |
+
raise ValueError("gain must be a tuple or a float")
|
| 105 |
+
KORNIA_CHECK(
|
| 106 |
+
all(0 <= el <= 1 for el in gain),
|
| 107 |
+
"gain values must be between 0 and 1. Recommended values less than 0.2.",
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
if isinstance(center, (tuple, float)):
|
| 111 |
+
if isinstance(center, float):
|
| 112 |
+
center = (center, center)
|
| 113 |
+
elif len(center) == 1:
|
| 114 |
+
center = (center[0], center[0])
|
| 115 |
+
elif len(center) > 2 or len(center) <= 0:
|
| 116 |
+
raise ValueError(
|
| 117 |
+
"The length of center must be greater than 0 \
|
| 118 |
+
and less than or equal to 2, and it should be a tuple or a float."
|
| 119 |
+
)
|
| 120 |
+
else:
|
| 121 |
+
raise ValueError("center must be a tuple or a float")
|
| 122 |
+
KORNIA_CHECK(
|
| 123 |
+
all(0 <= el <= 1 for el in center),
|
| 124 |
+
"center of gaussian value must be between 0 and 1.",
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if isinstance(sigma, (tuple, float)):
|
| 128 |
+
if isinstance(sigma, float):
|
| 129 |
+
sigma = (sigma, sigma)
|
| 130 |
+
elif len(sigma) == 1:
|
| 131 |
+
sigma = (sigma[0], sigma[0])
|
| 132 |
+
elif len(sigma) > 2 or len(sigma) <= 0:
|
| 133 |
+
raise ValueError(
|
| 134 |
+
"The length of sigma must be greater than 0 \
|
| 135 |
+
and less than or equal to 2, and it should be a tuple or a float."
|
| 136 |
+
)
|
| 137 |
+
else:
|
| 138 |
+
raise ValueError("sigma must be a tuple or a float")
|
| 139 |
+
KORNIA_CHECK(
|
| 140 |
+
all(0 <= el <= 1 for el in sigma),
|
| 141 |
+
"sigma of gaussian value must be between 0 and 1.",
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
if isinstance(sign, (tuple, float)):
|
| 145 |
+
if isinstance(sign, float):
|
| 146 |
+
sign = (sign, sign)
|
| 147 |
+
elif len(sign) == 1:
|
| 148 |
+
sign = (sign[0], sign[0])
|
| 149 |
+
elif len(sign) > 2 or len(sign) <= 0:
|
| 150 |
+
raise ValueError(
|
| 151 |
+
"The length of sign must be greater than 0 \
|
| 152 |
+
and less than or equal to 2, and it should be a tuple or a float."
|
| 153 |
+
)
|
| 154 |
+
else:
|
| 155 |
+
raise ValueError("sign must be a tuple or a float")
|
| 156 |
+
KORNIA_CHECK(
|
| 157 |
+
all(-1 <= el <= 1 for el in sign),
|
| 158 |
+
"sign of gaussian value must be between -1 and 1.",
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
# Generator of random parameters and masks.
|
| 162 |
+
self._param_generator = GaussianIlluminationGenerator(gain, center, sigma, sign)
|
| 163 |
+
|
| 164 |
+
def _apply_transform(
|
| 165 |
+
input: Tensor,
|
| 166 |
+
params: Dict[str, Tensor],
|
| 167 |
+
flags: Dict[str, Any],
|
| 168 |
+
transform: Optional[Tensor] = None,
|
| 169 |
+
) -> Tensor:
|
| 170 |
+
return input.add_(params["gradient"]).clamp_(0, 1)
|
| 171 |
+
|
| 172 |
+
self._fn = _apply_transform
|
| 173 |
+
|
| 174 |
+
def apply_transform(
|
| 175 |
+
self,
|
| 176 |
+
input: Tensor,
|
| 177 |
+
params: Dict[str, Tensor],
|
| 178 |
+
flags: Dict[str, Any],
|
| 179 |
+
transform: Optional[Tensor] = None,
|
| 180 |
+
) -> Tensor:
|
| 181 |
+
r"""Apply random gaussian gradient illumination to the input image."""
|
| 182 |
+
return self._fn(input=input, params=params, flags=flags, transform=transform)
|
| 183 |
+
|
| 184 |
+
def compile(
|
| 185 |
+
self,
|
| 186 |
+
*,
|
| 187 |
+
fullgraph: bool = False,
|
| 188 |
+
dynamic: bool = False,
|
| 189 |
+
backend: str = "inductor",
|
| 190 |
+
mode: Optional[str] = None,
|
| 191 |
+
options: Optional[Dict[Any, Any]] = None,
|
| 192 |
+
disable: bool = False,
|
| 193 |
+
) -> "RandomGaussianIllumination":
|
| 194 |
+
self._fn = torch.compile(
|
| 195 |
+
self._fn,
|
| 196 |
+
fullgraph=fullgraph,
|
| 197 |
+
dynamic=dynamic,
|
| 198 |
+
backend=backend,
|
| 199 |
+
mode=mode,
|
| 200 |
+
options=options,
|
| 201 |
+
disable=disable,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
return self
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/gaussian_noise.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 23 |
+
from kornia.core import Tensor
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _randn_like(input: Tensor, mean: float, std: float) -> Tensor:
|
| 27 |
+
x = torch.randn_like(input) # Generating on GPU is fastest with `torch.randn_like(...)`
|
| 28 |
+
if std != 1.0: # `if` is cheaper than multiplication
|
| 29 |
+
x *= std
|
| 30 |
+
if mean != 0.0: # `if` is cheaper than addition
|
| 31 |
+
x += mean
|
| 32 |
+
return x
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class RandomGaussianNoise(IntensityAugmentationBase2D):
|
| 36 |
+
r"""Add gaussian noise to a batch of multi-dimensional images.
|
| 37 |
+
|
| 38 |
+
.. image:: _static/img/RandomGaussianNoise.png
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
mean: The mean of the gaussian distribution.
|
| 42 |
+
std: The standard deviation of the gaussian distribution.
|
| 43 |
+
same_on_batch: apply the same transformation across the batch.
|
| 44 |
+
p: probability of applying the transformation.
|
| 45 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 46 |
+
to the batch form (False).
|
| 47 |
+
|
| 48 |
+
Examples:
|
| 49 |
+
>>> rng = torch.manual_seed(0)
|
| 50 |
+
>>> img = torch.ones(1, 1, 2, 2)
|
| 51 |
+
>>> RandomGaussianNoise(mean=0., std=1., p=1.)(img)
|
| 52 |
+
tensor([[[[ 2.5410, 0.7066],
|
| 53 |
+
[-1.1788, 1.5684]]]])
|
| 54 |
+
|
| 55 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 56 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 57 |
+
>>> aug = RandomGaussianNoise(mean=0., std=1., p=1.)
|
| 58 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 59 |
+
tensor(True)
|
| 60 |
+
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(
|
| 64 |
+
self, mean: float = 0.0, std: float = 1.0, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
|
| 65 |
+
) -> None:
|
| 66 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 67 |
+
self.flags = {"mean": mean, "std": std}
|
| 68 |
+
|
| 69 |
+
def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:
|
| 70 |
+
return {}
|
| 71 |
+
|
| 72 |
+
def apply_transform(
|
| 73 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 74 |
+
) -> Tensor:
|
| 75 |
+
if "gaussian_noise" in params:
|
| 76 |
+
gaussian_noise = params["gaussian_noise"]
|
| 77 |
+
else:
|
| 78 |
+
gaussian_noise = _randn_like(input, mean=flags["mean"], std=flags["std"])
|
| 79 |
+
self._params["gaussian_noise"] = gaussian_noise
|
| 80 |
+
return input + gaussian_noise
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/grayscale.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import Tensor
|
| 22 |
+
|
| 23 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 24 |
+
from kornia.color import rgb_to_grayscale
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RandomGrayscale(IntensityAugmentationBase2D):
|
| 28 |
+
r"""Apply random transformation to Grayscale according to a probability p value.
|
| 29 |
+
|
| 30 |
+
.. image:: _static/img/RandomGrayscale.png
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
rgb_weights: Weights that will be applied on each channel (RGB).
|
| 34 |
+
The sum of the weights should add up to one.
|
| 35 |
+
p: probability of the image to be transformed to grayscale.
|
| 36 |
+
same_on_batch: apply the same transformation across the batch.
|
| 37 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 38 |
+
to the batch form (False).
|
| 39 |
+
|
| 40 |
+
Shape:
|
| 41 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 42 |
+
- Output: :math:`(B, C, H, W)`
|
| 43 |
+
|
| 44 |
+
.. note::
|
| 45 |
+
This function internally uses :func:`kornia.color.rgb_to_grayscale`.
|
| 46 |
+
|
| 47 |
+
Examples:
|
| 48 |
+
>>> rng = torch.manual_seed(0)
|
| 49 |
+
>>> inputs = torch.randn((1, 3, 3, 3))
|
| 50 |
+
>>> aug = RandomGrayscale(p=1.0)
|
| 51 |
+
>>> aug(inputs)
|
| 52 |
+
tensor([[[[-1.1344, -0.1330, 0.1517],
|
| 53 |
+
[-0.0791, 0.6711, -0.1413],
|
| 54 |
+
[-0.1717, -0.9023, 0.0819]],
|
| 55 |
+
<BLANKLINE>
|
| 56 |
+
[[-1.1344, -0.1330, 0.1517],
|
| 57 |
+
[-0.0791, 0.6711, -0.1413],
|
| 58 |
+
[-0.1717, -0.9023, 0.0819]],
|
| 59 |
+
<BLANKLINE>
|
| 60 |
+
[[-1.1344, -0.1330, 0.1517],
|
| 61 |
+
[-0.0791, 0.6711, -0.1413],
|
| 62 |
+
[-0.1717, -0.9023, 0.0819]]]])
|
| 63 |
+
|
| 64 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 65 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 66 |
+
>>> aug = RandomGrayscale(p=1.0)
|
| 67 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 68 |
+
tensor(True)
|
| 69 |
+
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self, rgb_weights: Optional[Tensor] = None, same_on_batch: bool = False, p: float = 0.1, keepdim: bool = False
|
| 74 |
+
) -> None:
|
| 75 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 76 |
+
self.rgb_weights = rgb_weights
|
| 77 |
+
|
| 78 |
+
def apply_transform(
|
| 79 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 80 |
+
) -> Tensor:
|
| 81 |
+
# Make sure it returns (*, 3, H, W)
|
| 82 |
+
grayscale = torch.ones_like(input)
|
| 83 |
+
grayscale[:] = rgb_to_grayscale(input, rgb_weights=self.rgb_weights)
|
| 84 |
+
return grayscale
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/hue.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 22 |
+
from kornia.augmentation.utils import _range_bound
|
| 23 |
+
from kornia.constants import pi
|
| 24 |
+
from kornia.core import Tensor
|
| 25 |
+
from kornia.enhance.adjust import adjust_hue
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class RandomHue(IntensityAugmentationBase2D):
|
| 29 |
+
r"""Apply a random transformation to the hue of a tensor image.
|
| 30 |
+
|
| 31 |
+
This implementation aligns PIL. Hence, the output is close to TorchVision.
|
| 32 |
+
|
| 33 |
+
.. image:: _static/img/RandomHue.png
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
hue: the saturation factor to apply.
|
| 37 |
+
same_on_batch: apply the same transformation across the batch.
|
| 38 |
+
p: probability of applying the transformation.
|
| 39 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 40 |
+
to the batch form (False).
|
| 41 |
+
Shape:
|
| 42 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 43 |
+
- Output: :math:`(B, C, H, W)`
|
| 44 |
+
|
| 45 |
+
.. note::
|
| 46 |
+
This function internally uses :func:`kornia.enhance.adjust_hue`
|
| 47 |
+
|
| 48 |
+
Examples:
|
| 49 |
+
>>> rng = torch.manual_seed(0)
|
| 50 |
+
>>> inputs = torch.rand(1, 3, 3, 3)
|
| 51 |
+
>>> aug = RandomHue(hue = (-0.5,0.5),p=1.)
|
| 52 |
+
>>> aug(inputs)
|
| 53 |
+
tensor([[[[0.3993, 0.2823, 0.6816],
|
| 54 |
+
[0.6117, 0.2090, 0.4081],
|
| 55 |
+
[0.4693, 0.5529, 0.9527]],
|
| 56 |
+
<BLANKLINE>
|
| 57 |
+
[[0.1610, 0.5962, 0.4971],
|
| 58 |
+
[0.9152, 0.3971, 0.8742],
|
| 59 |
+
[0.4194, 0.6771, 0.7162]],
|
| 60 |
+
<BLANKLINE>
|
| 61 |
+
[[0.6323, 0.7682, 0.0885],
|
| 62 |
+
[0.0223, 0.1689, 0.2939],
|
| 63 |
+
[0.5185, 0.8964, 0.4556]]]])
|
| 64 |
+
|
| 65 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 66 |
+
|
| 67 |
+
>>> input = torch.rand(1, 3, 32, 32)
|
| 68 |
+
>>> aug = RandomHue((-0.2,0.2), p=1.)
|
| 69 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 70 |
+
tensor(True)
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(
|
| 75 |
+
self, hue: Tuple[float, float] = (0.0, 0.0), same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False
|
| 76 |
+
) -> None:
|
| 77 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 78 |
+
self.hue: Tensor = _range_bound(hue, "hue", bounds=(-0.5, 0.5))
|
| 79 |
+
self._param_generator = rg.PlainUniformGenerator((self.hue, "hue_factor", None, None))
|
| 80 |
+
|
| 81 |
+
def apply_transform(
|
| 82 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 83 |
+
) -> Tensor:
|
| 84 |
+
hue_factor = params["hue_factor"].to(input)
|
| 85 |
+
return adjust_hue(input, hue_factor * 2 * pi)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/invert.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import Tensor
|
| 22 |
+
|
| 23 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 24 |
+
from kornia.enhance import invert
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RandomInvert(IntensityAugmentationBase2D):
|
| 28 |
+
r"""Invert the tensor images values randomly.
|
| 29 |
+
|
| 30 |
+
.. image:: _static/img/RandomInvert.png
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
max_val: The expected maximum value in the input tensor. The shape has to
|
| 34 |
+
according to the input tensor shape, or at least has to work with broadcasting.
|
| 35 |
+
same_on_batch: apply the same transformation across the batch.
|
| 36 |
+
p: probability of applying the transformation.
|
| 37 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 38 |
+
to the batch form (False).
|
| 39 |
+
.. note::
|
| 40 |
+
This function internally uses :func:`kornia.enhance.invert`.
|
| 41 |
+
|
| 42 |
+
Examples:
|
| 43 |
+
>>> rng = torch.manual_seed(0)
|
| 44 |
+
>>> img = torch.rand(1, 1, 5, 5)
|
| 45 |
+
>>> inv = RandomInvert()
|
| 46 |
+
>>> inv(img)
|
| 47 |
+
tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],
|
| 48 |
+
[0.6341, 0.4901, 0.8964, 0.4556, 0.6323],
|
| 49 |
+
[0.3489, 0.4017, 0.0223, 0.1689, 0.2939],
|
| 50 |
+
[0.5185, 0.6977, 0.8000, 0.1610, 0.2823],
|
| 51 |
+
[0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
|
| 52 |
+
|
| 53 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 54 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 55 |
+
>>> aug = RandomInvert(p=1.)
|
| 56 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 57 |
+
tensor(True)
|
| 58 |
+
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
def __init__(
|
| 62 |
+
self,
|
| 63 |
+
max_val: Union[float, Tensor] = 1.0,
|
| 64 |
+
same_on_batch: bool = False,
|
| 65 |
+
p: float = 0.5,
|
| 66 |
+
keepdim: bool = False,
|
| 67 |
+
) -> None:
|
| 68 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 69 |
+
self.flags = {"max_val": max_val}
|
| 70 |
+
|
| 71 |
+
def apply_transform(
|
| 72 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 73 |
+
) -> Tensor:
|
| 74 |
+
return invert(input, torch.as_tensor(flags["max_val"], device=input.device, dtype=input.dtype))
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/jpeg.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 22 |
+
from kornia.core import Tensor
|
| 23 |
+
from kornia.enhance import jpeg_codec_differentiable
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RandomJPEG(IntensityAugmentationBase2D):
|
| 27 |
+
r"""Applies random (differentiable) JPEG coding to a tensor image.
|
| 28 |
+
|
| 29 |
+
.. image:: _static/img/RandomJPEG.png
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
jpeg_quality: The range of compression rates to be applied.
|
| 33 |
+
p: probability of applying the transformation.
|
| 34 |
+
same_on_batch: apply the same transformation across the batch.
|
| 35 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 36 |
+
to the batch form (False).
|
| 37 |
+
|
| 38 |
+
Shape:
|
| 39 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
|
| 40 |
+
- Output: :math:`(B, C, H, W)`
|
| 41 |
+
|
| 42 |
+
.. note::
|
| 43 |
+
This function internally uses :func:`kornia.enhance.jpeg_codec_differentiable`.
|
| 44 |
+
|
| 45 |
+
Examples:
|
| 46 |
+
>>> import torch
|
| 47 |
+
>>> rng = torch.manual_seed(0)
|
| 48 |
+
>>> images = 0.1904 * torch.ones(2, 3, 32, 32)
|
| 49 |
+
>>> aug = RandomJPEG(jpeg_quality=(1.0, 50.0), p=1.)
|
| 50 |
+
>>> images_jpeg = aug(images)
|
| 51 |
+
|
| 52 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 53 |
+
>>> images = 0.1904 * torch.ones(2, 3, 32, 32)
|
| 54 |
+
>>> aug = RandomJPEG(jpeg_quality=20.0, p=1.) # Samples a JPEG quality from the range [30.0, 70.0]
|
| 55 |
+
>>> (aug(images) == aug(images, params=aug._params)).all()
|
| 56 |
+
tensor(True)
|
| 57 |
+
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __init__(
|
| 61 |
+
self,
|
| 62 |
+
jpeg_quality: Union[Tensor, float, Tuple[float, float], List[float]] = 50.0,
|
| 63 |
+
same_on_batch: bool = False,
|
| 64 |
+
p: float = 1.0,
|
| 65 |
+
keepdim: bool = False,
|
| 66 |
+
) -> None:
|
| 67 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 68 |
+
self.jpeg_quality = jpeg_quality
|
| 69 |
+
self._param_generator = rg.JPEGGenerator(jpeg_quality)
|
| 70 |
+
|
| 71 |
+
def apply_transform(
|
| 72 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 73 |
+
) -> Tensor:
|
| 74 |
+
jpeg_output: Tensor = jpeg_codec_differentiable(input, params["jpeg_quality"])
|
| 75 |
+
return jpeg_output
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/linear_illumination.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 21 |
+
from kornia.augmentation.random_generator._2d import LinearCornerIlluminationGenerator, LinearIlluminationGenerator
|
| 22 |
+
from kornia.core import Tensor
|
| 23 |
+
from kornia.core.check import KORNIA_CHECK
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RandomLinearIllumination(IntensityAugmentationBase2D):
|
| 27 |
+
r"""Applies random 2D Linear illumination patterns to a batch of images.
|
| 28 |
+
|
| 29 |
+
.. image:: _static/img/RandomLinearIllumination.png
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
gain: Range for the gain factor (intensity) applied to the generated illumination.
|
| 33 |
+
sign: Range for the sign of the distribution. If only one sign is needed,
|
| 34 |
+
insert only as a tuple or float.
|
| 35 |
+
p: Probability of applying the transformation.
|
| 36 |
+
same_on_batch: If True, apply the same transformation across the entire batch. Default is False.
|
| 37 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 38 |
+
to the batch form (False).
|
| 39 |
+
|
| 40 |
+
Shape:
|
| 41 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
|
| 42 |
+
- Output: :math:`(B, C, H, W)`
|
| 43 |
+
|
| 44 |
+
.. note::
|
| 45 |
+
The generated random numbers are not reproducible across different devices and dtypes. By default,
|
| 46 |
+
the parameters will be generated on CPU. This can be changed by calling
|
| 47 |
+
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
|
| 48 |
+
|
| 49 |
+
Examples:
|
| 50 |
+
>>> rng = torch.manual_seed(1)
|
| 51 |
+
>>> input = torch.ones(1, 3, 3, 3) * 0.5
|
| 52 |
+
>>> aug = RandomLinearIllumination(gain=0.25, p=1.)
|
| 53 |
+
>>> aug(input)
|
| 54 |
+
tensor([[[[0.2500, 0.2500, 0.2500],
|
| 55 |
+
[0.3750, 0.3750, 0.3750],
|
| 56 |
+
[0.5000, 0.5000, 0.5000]],
|
| 57 |
+
<BLANKLINE>
|
| 58 |
+
[[0.2500, 0.2500, 0.2500],
|
| 59 |
+
[0.3750, 0.3750, 0.3750],
|
| 60 |
+
[0.5000, 0.5000, 0.5000]],
|
| 61 |
+
<BLANKLINE>
|
| 62 |
+
[[0.2500, 0.2500, 0.2500],
|
| 63 |
+
[0.3750, 0.3750, 0.3750],
|
| 64 |
+
[0.5000, 0.5000, 0.5000]]]])
|
| 65 |
+
|
| 66 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 67 |
+
>>> input = torch.rand(1, 3, 32, 32)
|
| 68 |
+
>>> aug = RandomLinearIllumination(p=1.)
|
| 69 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 70 |
+
tensor(True)
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(
|
| 75 |
+
self,
|
| 76 |
+
gain: Optional[Union[float, Tuple[float, float]]] = (0.01, 0.2),
|
| 77 |
+
sign: Optional[Union[float, Tuple[float, float]]] = (-1.0, 1.0),
|
| 78 |
+
p: float = 0.5,
|
| 79 |
+
same_on_batch: bool = False,
|
| 80 |
+
keepdim: bool = False,
|
| 81 |
+
) -> None:
|
| 82 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 83 |
+
|
| 84 |
+
# Validation and initialization of amount parameter.
|
| 85 |
+
if isinstance(gain, (tuple, float)):
|
| 86 |
+
if isinstance(gain, float):
|
| 87 |
+
gain = (gain, gain)
|
| 88 |
+
elif len(gain) == 1:
|
| 89 |
+
gain = (gain[0], gain[0])
|
| 90 |
+
elif len(gain) > 2 or len(gain) <= 0:
|
| 91 |
+
raise ValueError(
|
| 92 |
+
"The length of gain must be greater than 0 \
|
| 93 |
+
and less than or equal to 2, and it should be a tuple or a float."
|
| 94 |
+
)
|
| 95 |
+
else:
|
| 96 |
+
raise ValueError("gain must be a tuple or a float")
|
| 97 |
+
KORNIA_CHECK(
|
| 98 |
+
all(0 <= el <= 1 for el in gain),
|
| 99 |
+
"gain values must be between 0 and 1. Recommended values less than 0.2.",
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if isinstance(sign, (tuple, float)):
|
| 103 |
+
if isinstance(sign, float):
|
| 104 |
+
sign = (sign, sign)
|
| 105 |
+
elif len(sign) == 1:
|
| 106 |
+
sign = (sign[0], sign[0])
|
| 107 |
+
elif len(sign) > 2 or len(sign) <= 0:
|
| 108 |
+
raise ValueError(
|
| 109 |
+
"The length of sign must be greater than 0 \
|
| 110 |
+
and less than or equal to 2, and it should be a tuple or a float."
|
| 111 |
+
)
|
| 112 |
+
else:
|
| 113 |
+
raise ValueError("sign must be a tuple or a float")
|
| 114 |
+
KORNIA_CHECK(
|
| 115 |
+
all(-1 <= el <= 1 for el in sign),
|
| 116 |
+
"sign of linear value must be between -1 and 1.",
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# Generator of random parameters and masks.
|
| 120 |
+
self._param_generator = LinearIlluminationGenerator(gain, sign)
|
| 121 |
+
|
| 122 |
+
def apply_transform(
|
| 123 |
+
self,
|
| 124 |
+
input: Tensor,
|
| 125 |
+
params: Dict[str, Tensor],
|
| 126 |
+
flags: Dict[str, Any],
|
| 127 |
+
transform: Optional[Tensor] = None,
|
| 128 |
+
) -> Tensor:
|
| 129 |
+
r"""Apply random gaussian gradient illumination to the input image."""
|
| 130 |
+
return input.add(params["gradient"].to(input)).clamp(0, 1)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class RandomLinearCornerIllumination(IntensityAugmentationBase2D):
|
| 134 |
+
r"""Applies random 2D Linear from corner illumination patterns to a batch of images.
|
| 135 |
+
|
| 136 |
+
.. image:: _static/img/RandomLinearCornerIllumination.png
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
gain: Range for the gain factor (intensity) applied to the generated illumination.
|
| 140 |
+
sign: Range for the sign of the distribution. If only one sign is needed,
|
| 141 |
+
insert only as a tuple or float.
|
| 142 |
+
p: Probability of applying the transformation.
|
| 143 |
+
same_on_batch: If True, apply the same transformation across the entire batch. Default is False.
|
| 144 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 145 |
+
to the batch form (False).
|
| 146 |
+
|
| 147 |
+
Shape:
|
| 148 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
|
| 149 |
+
- Output: :math:`(B, C, H, W)`
|
| 150 |
+
|
| 151 |
+
.. note::
|
| 152 |
+
The generated random numbers are not reproducible across different devices and dtypes. By default,
|
| 153 |
+
the parameters will be generated on CPU. This can be changed by calling
|
| 154 |
+
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
|
| 155 |
+
|
| 156 |
+
Examples:
|
| 157 |
+
>>> rng = torch.manual_seed(1)
|
| 158 |
+
>>> input = torch.ones(1, 3, 3, 3) * 0.5
|
| 159 |
+
>>> aug = RandomLinearCornerIllumination(gain=0.25, p=1.)
|
| 160 |
+
>>> aug(input)
|
| 161 |
+
tensor([[[[0.3750, 0.4375, 0.5000],
|
| 162 |
+
[0.3125, 0.3750, 0.4375],
|
| 163 |
+
[0.2500, 0.3125, 0.3750]],
|
| 164 |
+
<BLANKLINE>
|
| 165 |
+
[[0.3750, 0.4375, 0.5000],
|
| 166 |
+
[0.3125, 0.3750, 0.4375],
|
| 167 |
+
[0.2500, 0.3125, 0.3750]],
|
| 168 |
+
<BLANKLINE>
|
| 169 |
+
[[0.3750, 0.4375, 0.5000],
|
| 170 |
+
[0.3125, 0.3750, 0.4375],
|
| 171 |
+
[0.2500, 0.3125, 0.3750]]]])
|
| 172 |
+
|
| 173 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 174 |
+
>>> input = torch.rand(1, 3, 32, 32)
|
| 175 |
+
>>> aug = RandomLinearCornerIllumination(p=1.)
|
| 176 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 177 |
+
tensor(True)
|
| 178 |
+
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
def __init__(
|
| 182 |
+
self,
|
| 183 |
+
gain: Optional[Union[float, Tuple[float, float]]] = (0.01, 0.2),
|
| 184 |
+
sign: Optional[Union[float, Tuple[float, float]]] = (-1.0, 1.0),
|
| 185 |
+
p: float = 0.5,
|
| 186 |
+
same_on_batch: bool = False,
|
| 187 |
+
keepdim: bool = False,
|
| 188 |
+
) -> None:
|
| 189 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 190 |
+
|
| 191 |
+
# Validation and initialization of amount parameter.
|
| 192 |
+
if isinstance(gain, (tuple, float)):
|
| 193 |
+
if isinstance(gain, float):
|
| 194 |
+
gain = (gain, gain)
|
| 195 |
+
elif len(gain) == 1:
|
| 196 |
+
gain = (gain[0], gain[0])
|
| 197 |
+
elif len(gain) > 2 or len(gain) <= 0:
|
| 198 |
+
raise ValueError(
|
| 199 |
+
"The length of gain must be greater than 0 \
|
| 200 |
+
and less than or equal to 2, and it should be a tuple or a float."
|
| 201 |
+
)
|
| 202 |
+
else:
|
| 203 |
+
raise ValueError("gain must be a tuple or a float")
|
| 204 |
+
KORNIA_CHECK(
|
| 205 |
+
all(0 <= el <= 1 for el in gain),
|
| 206 |
+
"gain values must be between 0 and 1. Recommended values less than 0.2.",
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
if isinstance(sign, (tuple, float)):
|
| 210 |
+
if isinstance(sign, float):
|
| 211 |
+
sign = (sign, sign)
|
| 212 |
+
elif len(sign) == 1:
|
| 213 |
+
sign = (sign[0], sign[0])
|
| 214 |
+
elif len(sign) > 2 or len(sign) <= 0:
|
| 215 |
+
raise ValueError(
|
| 216 |
+
"The length of sign must be greater than 0 \
|
| 217 |
+
and less than or equal to 2, and it should be a tuple or a float."
|
| 218 |
+
)
|
| 219 |
+
else:
|
| 220 |
+
raise ValueError("sign must be a tuple or a float")
|
| 221 |
+
KORNIA_CHECK(
|
| 222 |
+
all(-1 <= el <= 1 for el in sign),
|
| 223 |
+
"sign of linear value must be between -1 and 1.",
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
# Generator of random parameters and masks.
|
| 227 |
+
self._param_generator = LinearCornerIlluminationGenerator(gain, sign)
|
| 228 |
+
|
| 229 |
+
def apply_transform(
|
| 230 |
+
self,
|
| 231 |
+
input: Tensor,
|
| 232 |
+
params: Dict[str, Tensor],
|
| 233 |
+
flags: Dict[str, Any],
|
| 234 |
+
transform: Optional[Tensor] = None,
|
| 235 |
+
) -> Tensor:
|
| 236 |
+
r"""Apply random gaussian gradient illumination to the input image."""
|
| 237 |
+
return input.add(params["gradient"].to(input)).clamp(0, 1)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/median_blur.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from torch import Tensor
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 23 |
+
from kornia.filters import median_blur
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RandomMedianBlur(IntensityAugmentationBase2D):
|
| 27 |
+
"""Add random blur with a median filter to an image tensor.
|
| 28 |
+
|
| 29 |
+
.. image:: _static/img/RandomMedianBlur.png
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
kernel_size: the blurring kernel size.
|
| 33 |
+
same_on_batch: apply the same transformation across the batch.
|
| 34 |
+
p: probability of applying the transformation.
|
| 35 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 36 |
+
to the batch form (False).
|
| 37 |
+
.. note::
|
| 38 |
+
This function internally uses :func:`kornia.filters.median_blur`.
|
| 39 |
+
|
| 40 |
+
Examples:
|
| 41 |
+
>>> img = torch.ones(1, 1, 4, 4)
|
| 42 |
+
>>> out = RandomMedianBlur((3, 3), p = 1)(img)
|
| 43 |
+
>>> out.shape
|
| 44 |
+
torch.Size([1, 1, 4, 4])
|
| 45 |
+
>>> out
|
| 46 |
+
tensor([[[[0., 1., 1., 0.],
|
| 47 |
+
[1., 1., 1., 1.],
|
| 48 |
+
[1., 1., 1., 1.],
|
| 49 |
+
[0., 1., 1., 0.]]]])
|
| 50 |
+
|
| 51 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 52 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 53 |
+
>>> aug = RandomMedianBlur((7, 7), p=1.)
|
| 54 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 55 |
+
tensor(True)
|
| 56 |
+
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self, kernel_size: Tuple[int, int] = (3, 3), same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
|
| 61 |
+
) -> None:
|
| 62 |
+
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
|
| 63 |
+
self.flags = {"kernel_size": kernel_size}
|
| 64 |
+
|
| 65 |
+
def apply_transform(
|
| 66 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 67 |
+
) -> Tensor:
|
| 68 |
+
return median_blur(input, flags["kernel_size"])
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/motion_blur.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, List, Optional, Tuple, Union, cast
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from kornia.augmentation import random_generator as rg
|
| 23 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 24 |
+
from kornia.constants import BorderType, Resample
|
| 25 |
+
from kornia.core import Tensor, tensor
|
| 26 |
+
from kornia.filters import motion_blur
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class RandomMotionBlur(IntensityAugmentationBase2D):
|
| 30 |
+
r"""Perform motion blur on 2D images (4D tensor).
|
| 31 |
+
|
| 32 |
+
.. image:: _static/img/RandomMotionBlur.png
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
p: probability of applying the transformation.
|
| 36 |
+
kernel_size: motion kernel size (odd and positive).
|
| 37 |
+
If int, the kernel will have a fixed size.
|
| 38 |
+
If Tuple[int, int], it will randomly generate the value from the range batch-wisely.
|
| 39 |
+
angle: angle of the motion blur in degrees (anti-clockwise rotation).
|
| 40 |
+
If float, it will generate the value from (-angle, angle).
|
| 41 |
+
direction: forward/backward direction of the motion blur.
|
| 42 |
+
Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
|
| 43 |
+
while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
|
| 44 |
+
uniformly (but still angled) motion blur.
|
| 45 |
+
If float, it will generate the value from (-direction, direction).
|
| 46 |
+
If Tuple[int, int], it will randomly generate the value from the range.
|
| 47 |
+
border_type: the padding mode to be applied before convolving.
|
| 48 |
+
CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3.
|
| 49 |
+
resample: the interpolation mode.
|
| 50 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 51 |
+
to the batch form (False).
|
| 52 |
+
|
| 53 |
+
Shape:
|
| 54 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
|
| 55 |
+
- Output: :math:`(B, C, H, W)`
|
| 56 |
+
|
| 57 |
+
Note:
|
| 58 |
+
Input tensor must be float and normalized into [0, 1] for the best differentiability support.
|
| 59 |
+
Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
|
| 60 |
+
applied transformation will be merged int to the input transformation tensor and returned.
|
| 61 |
+
|
| 62 |
+
Please set ``resample`` to ``'bilinear'`` if more meaningful gradients wanted.
|
| 63 |
+
|
| 64 |
+
.. note::
|
| 65 |
+
This function internally uses :func:`kornia.filters.motion_blur`.
|
| 66 |
+
|
| 67 |
+
Examples:
|
| 68 |
+
>>> rng = torch.manual_seed(0)
|
| 69 |
+
>>> input = torch.ones(1, 1, 5, 5)
|
| 70 |
+
>>> motion_blur = RandomMotionBlur(3, 35., 0.5, p=1.)
|
| 71 |
+
>>> motion_blur(input)
|
| 72 |
+
tensor([[[[0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
|
| 73 |
+
[0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
|
| 74 |
+
[0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
|
| 75 |
+
[0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
|
| 76 |
+
[0.5773, 1.0000, 1.0000, 1.0000, 0.7561]]]])
|
| 77 |
+
|
| 78 |
+
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
|
| 79 |
+
>>> input = torch.randn(1, 3, 32, 32)
|
| 80 |
+
>>> aug = RandomMotionBlur(3, 35., 0.5, p=1.)
|
| 81 |
+
>>> (aug(input) == aug(input, params=aug._params)).all()
|
| 82 |
+
tensor(True)
|
| 83 |
+
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(
|
| 87 |
+
self,
|
| 88 |
+
kernel_size: Union[int, Tuple[int, int]],
|
| 89 |
+
angle: Union[Tensor, float, Tuple[float, float]],
|
| 90 |
+
direction: Union[Tensor, float, Tuple[float, float]],
|
| 91 |
+
border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
|
| 92 |
+
resample: Union[str, int, Resample] = Resample.NEAREST.name,
|
| 93 |
+
same_on_batch: bool = False,
|
| 94 |
+
p: float = 0.5,
|
| 95 |
+
keepdim: bool = False,
|
| 96 |
+
) -> None:
|
| 97 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 98 |
+
self._param_generator = rg.MotionBlurGenerator(kernel_size, angle, direction)
|
| 99 |
+
self.flags = {"border_type": BorderType.get(border_type), "resample": Resample.get(resample)}
|
| 100 |
+
|
| 101 |
+
def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
|
| 102 |
+
params = super().generate_parameters(batch_shape)
|
| 103 |
+
params["idx"] = tensor([0]) if batch_shape[0] == 0 else torch.randint(batch_shape[0], (1,))
|
| 104 |
+
return params
|
| 105 |
+
|
| 106 |
+
def apply_transform(
|
| 107 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 108 |
+
) -> Tensor:
|
| 109 |
+
# sample a kernel size
|
| 110 |
+
kernel_size_list: List[int] = params["ksize_factor"].tolist()
|
| 111 |
+
|
| 112 |
+
# 1. We have to apply the same kernel size to all samples in the batch, thus we take the previously
|
| 113 |
+
# selected random index --- `params["idx"][0]` --- to determine the applied kernel size.
|
| 114 |
+
# 2. The `VideoSequential` flattens the first two dimensions, effectively creating a larger batch.
|
| 115 |
+
# Its method `VideoSequential.__repeat_param_across_channels__` repeats the previously selected index,
|
| 116 |
+
# creating a tensor with equal values. Hence, taking the first one (`params["idx"][0]`) is legit.
|
| 117 |
+
idx: int = cast(int, params["idx"][0])
|
| 118 |
+
return motion_blur(
|
| 119 |
+
input,
|
| 120 |
+
kernel_size=kernel_size_list[idx],
|
| 121 |
+
angle=params["angle_factor"],
|
| 122 |
+
direction=params["direction_factor"],
|
| 123 |
+
border_type=flags["border_type"].name.lower(),
|
| 124 |
+
mode=flags["resample"].name.lower(),
|
| 125 |
+
)
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/normalize.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
from typing import Any, Optional
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from torch import Tensor
|
| 24 |
+
|
| 25 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 26 |
+
from kornia.enhance import normalize
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Normalize(IntensityAugmentationBase2D):
|
| 30 |
+
r"""Normalize tensor images with mean and standard deviation.
|
| 31 |
+
|
| 32 |
+
.. math::
|
| 33 |
+
\text{input[channel] = (input[channel] - mean[channel]) / std[channel]}
|
| 34 |
+
|
| 35 |
+
Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
mean: Mean for each channel.
|
| 39 |
+
std: Standard deviations for each channel.
|
| 40 |
+
p: probability of applying the transformation.
|
| 41 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 42 |
+
to the batch form (False).
|
| 43 |
+
|
| 44 |
+
Return:
|
| 45 |
+
Normalised tensor with same size as input :math:`(*, C, H, W)`.
|
| 46 |
+
|
| 47 |
+
.. note::
|
| 48 |
+
This function internally uses :func:`kornia.enhance.normalize`.
|
| 49 |
+
|
| 50 |
+
Examples:
|
| 51 |
+
>>> norm = Normalize(mean=torch.zeros(4), std=torch.ones(4))
|
| 52 |
+
>>> x = torch.rand(1, 4, 3, 3)
|
| 53 |
+
>>> out = norm(x)
|
| 54 |
+
>>> out.shape
|
| 55 |
+
torch.Size([1, 4, 3, 3])
|
| 56 |
+
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
mean: Tensor | tuple[float, ...] | list[float] | float,
|
| 62 |
+
std: Tensor | tuple[float, ...] | list[float] | float,
|
| 63 |
+
p: float = 1.0,
|
| 64 |
+
keepdim: bool = False,
|
| 65 |
+
) -> None:
|
| 66 |
+
super().__init__(p=p, same_on_batch=True, keepdim=keepdim)
|
| 67 |
+
if isinstance(mean, (int, float)):
|
| 68 |
+
mean = torch.tensor([mean])
|
| 69 |
+
|
| 70 |
+
if isinstance(std, (int, float)):
|
| 71 |
+
std = torch.tensor([std])
|
| 72 |
+
|
| 73 |
+
if isinstance(mean, (tuple, list)):
|
| 74 |
+
mean = torch.tensor(mean)
|
| 75 |
+
|
| 76 |
+
if isinstance(std, (tuple, list)):
|
| 77 |
+
std = torch.tensor(std)
|
| 78 |
+
|
| 79 |
+
self.flags = {"mean": mean, "std": std}
|
| 80 |
+
|
| 81 |
+
def apply_transform(
|
| 82 |
+
self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None
|
| 83 |
+
) -> Tensor:
|
| 84 |
+
return normalize(input, flags["mean"], flags["std"])
|
python_embeded/Lib/site-packages/kornia/augmentation/_2d/intensity/planckian_jitter.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, List, Optional, Union
|
| 19 |
+
|
| 20 |
+
from kornia.augmentation import random_generator as rg
|
| 21 |
+
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
|
| 22 |
+
from kornia.core import Tensor, stack, tensor
|
| 23 |
+
from kornia.core.check import KORNIA_CHECK_SHAPE
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_planckian_coeffs(mode: str) -> Tensor:
|
| 27 |
+
if mode.lower() == "blackbody":
|
| 28 |
+
coefs = tensor(
|
| 29 |
+
[
|
| 30 |
+
[0.6743, 0.4029, 0.0013],
|
| 31 |
+
[0.6281, 0.4241, 0.1665],
|
| 32 |
+
[0.5919, 0.4372, 0.2513],
|
| 33 |
+
[0.5623, 0.4457, 0.3154],
|
| 34 |
+
[0.5376, 0.4515, 0.3672],
|
| 35 |
+
[0.5163, 0.4555, 0.4103],
|
| 36 |
+
[0.4979, 0.4584, 0.4468],
|
| 37 |
+
[0.4816, 0.4604, 0.4782],
|
| 38 |
+
[0.4672, 0.4619, 0.5053],
|
| 39 |
+
[0.4542, 0.4630, 0.5289],
|
| 40 |
+
[0.4426, 0.4638, 0.5497],
|
| 41 |
+
[0.4320, 0.4644, 0.5681],
|
| 42 |
+
[0.4223, 0.4648, 0.5844],
|
| 43 |
+
[0.4135, 0.4651, 0.5990],
|
| 44 |
+
[0.4054, 0.4653, 0.6121],
|
| 45 |
+
[0.3980, 0.4654, 0.6239],
|
| 46 |
+
[0.3911, 0.4655, 0.6346],
|
| 47 |
+
[0.3847, 0.4656, 0.6444],
|
| 48 |
+
[0.3787, 0.4656, 0.6532],
|
| 49 |
+
[0.3732, 0.4656, 0.6613],
|
| 50 |
+
[0.3680, 0.4655, 0.6688],
|
| 51 |
+
[0.3632, 0.4655, 0.6756],
|
| 52 |
+
[0.3586, 0.4655, 0.6820],
|
| 53 |
+
[0.3544, 0.4654, 0.6878],
|
| 54 |
+
[0.3503, 0.4653, 0.6933],
|
| 55 |
+
]
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
elif mode.upper() == "CIED":
|
| 59 |
+
coefs = tensor(
|
| 60 |
+
[
|
| 61 |
+
[0.5829, 0.4421, 0.2288],
|
| 62 |
+
[0.5510, 0.4514, 0.2948],
|
| 63 |
+
[0.5246, 0.4576, 0.3488],
|
| 64 |
+
[0.5021, 0.4618, 0.3941],
|
| 65 |
+
[0.4826, 0.4646, 0.4325],
|
| 66 |
+
[0.4654, 0.4667, 0.4654],
|
| 67 |
+
[0.4502, 0.4681, 0.4938],
|
| 68 |
+
[0.4364, 0.4692, 0.5186],
|
| 69 |
+
[0.4240, 0.4700, 0.5403],
|
| 70 |
+
[0.4127, 0.4705, 0.5594],
|
| 71 |
+
[0.4023, 0.4709, 0.5763],
|
| 72 |
+
[0.3928, 0.4713, 0.5914],
|
| 73 |
+
[0.3839, 0.4715, 0.6049],
|
| 74 |
+
[0.3757, 0.4716, 0.6171],
|
| 75 |
+
[0.3681, 0.4717, 0.6281],
|
| 76 |
+
[0.3609, 0.4718, 0.6380],
|
| 77 |
+
[0.3543, 0.4719, 0.6472],
|
| 78 |
+
[0.3480, 0.4719, 0.6555],
|
| 79 |
+
[0.3421, 0.4719, 0.6631],
|
| 80 |
+
[0.3365, 0.4719, 0.6702],
|
| 81 |
+
[0.3313, 0.4719, 0.6766],
|
| 82 |
+
[0.3263, 0.4719, 0.6826],
|
| 83 |
+
[0.3217, 0.4719, 0.6882],
|
| 84 |
+
]
|
| 85 |
+
)
|
| 86 |
+
else:
|
| 87 |
+
raise RuntimeError(f"Unexpected mode. Gotcha {mode}")
|
| 88 |
+
|
| 89 |
+
return stack((coefs[:, 0] / coefs[:, 1], coefs[:, 2] / coefs[:, 1]), 1)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class RandomPlanckianJitter(IntensityAugmentationBase2D):
|
| 93 |
+
r"""Apply planckian jitter transformation to input tensor.
|
| 94 |
+
|
| 95 |
+
.. image:: _static/img/RandomPlanckianJitter.png
|
| 96 |
+
|
| 97 |
+
This is physics based color augmentation, that creates realistic
|
| 98 |
+
variations in chromaticity, this can simulate the illumination
|
| 99 |
+
changes in the scene.
|
| 100 |
+
|
| 101 |
+
See :cite:`zini2022planckian` for more details.
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
mode: 'blackbody' or 'CIED'.
|
| 105 |
+
select_from: choose a list of jitters to apply from. `blackbody` range [0-24], `CIED` range [0-22]
|
| 106 |
+
same_on_batch: apply the same transformation across the batch.
|
| 107 |
+
p: probability that the random erasing operation will be performed.
|
| 108 |
+
keepdim: whether to keep the output shape the same as input (True) or broadcast it
|
| 109 |
+
to the batch form (False).
|
| 110 |
+
|
| 111 |
+
Shape:
|
| 112 |
+
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
|
| 113 |
+
- Output: :math:`(B, C, H, W)`
|
| 114 |
+
|
| 115 |
+
.. note::
|
| 116 |
+
Input tensor must be float and normalized into [0, 1].
|
| 117 |
+
|
| 118 |
+
Examples:
|
| 119 |
+
To apply planckian jitter based on mode
|
| 120 |
+
|
| 121 |
+
>>> rng = torch.manual_seed(0)
|
| 122 |
+
>>> input = torch.randn(1, 3, 2, 2)
|
| 123 |
+
>>> aug = RandomPlanckianJitter(mode='CIED')
|
| 124 |
+
>>> aug(input)
|
| 125 |
+
tensor([[[[ 1.0000, -0.2389],
|
| 126 |
+
[-1.7740, 0.4628]],
|
| 127 |
+
<BLANKLINE>
|
| 128 |
+
[[-1.0845, -1.3986],
|
| 129 |
+
[ 0.4033, 0.8380]],
|
| 130 |
+
<BLANKLINE>
|
| 131 |
+
[[-0.9228, -0.5175],
|
| 132 |
+
[-0.7654, 0.2335]]]])
|
| 133 |
+
|
| 134 |
+
To apply planckian jitter on image(s) from list of interested jitters
|
| 135 |
+
|
| 136 |
+
>>> rng = torch.manual_seed(0)
|
| 137 |
+
>>> input = torch.randn(2, 3, 2, 2)
|
| 138 |
+
>>> aug = RandomPlanckianJitter(mode='blackbody', select_from=[23, 24, 1, 2])
|
| 139 |
+
>>> aug(input)
|
| 140 |
+
tensor([[[[-1.1258, -1.1524],
|
| 141 |
+
[-0.2506, -0.4339]],
|
| 142 |
+
<BLANKLINE>
|
| 143 |
+
[[ 0.8487, 0.6920],
|
| 144 |
+
[-0.3160, -2.1152]],
|
| 145 |
+
<BLANKLINE>
|
| 146 |
+
[[ 0.4681, -0.1577],
|
| 147 |
+
[ 1.4437, 0.2660]]],
|
| 148 |
+
<BLANKLINE>
|
| 149 |
+
<BLANKLINE>
|
| 150 |
+
[[[ 0.2465, 1.0000],
|
| 151 |
+
[-0.2125, -0.1653]],
|
| 152 |
+
<BLANKLINE>
|
| 153 |
+
[[ 0.9318, 1.0000],
|
| 154 |
+
[ 1.0000, 0.0537]],
|
| 155 |
+
<BLANKLINE>
|
| 156 |
+
[[ 0.2426, -0.1621],
|
| 157 |
+
[-0.3302, -0.9093]]]])
|
| 158 |
+
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
def __init__(
|
| 162 |
+
self,
|
| 163 |
+
mode: str = "blackbody",
|
| 164 |
+
select_from: Optional[Union[int, List[int]]] = None,
|
| 165 |
+
same_on_batch: bool = False,
|
| 166 |
+
p: float = 0.5,
|
| 167 |
+
keepdim: bool = False,
|
| 168 |
+
) -> None:
|
| 169 |
+
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
|
| 170 |
+
|
| 171 |
+
if isinstance(select_from, int):
|
| 172 |
+
select_from = [select_from]
|
| 173 |
+
|
| 174 |
+
_pl = get_planckian_coeffs(mode)
|
| 175 |
+
if select_from is not None:
|
| 176 |
+
_pl = _pl[select_from]
|
| 177 |
+
self.register_buffer("pl", _pl)
|
| 178 |
+
self.pl: Tensor
|
| 179 |
+
|
| 180 |
+
# the range of the sampling parameters
|
| 181 |
+
_param_min: float = 0.0
|
| 182 |
+
_param_max: float = float(self.pl.shape[0])
|
| 183 |
+
|
| 184 |
+
self._param_generator = rg.PlanckianJitterGenerator([_param_min, _param_max])
|
| 185 |
+
|
| 186 |
+
def apply_transform(
|
| 187 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 188 |
+
) -> Tensor:
|
| 189 |
+
list_idx = params["idx"].tolist()
|
| 190 |
+
KORNIA_CHECK_SHAPE(input, ["*", "3", "H", "W"])
|
| 191 |
+
self.pl = self.pl.to(device=input.device)
|
| 192 |
+
coeffs = self.pl[list_idx]
|
| 193 |
+
|
| 194 |
+
r_w = coeffs[:, 0][..., None, None]
|
| 195 |
+
b_w = coeffs[:, 1][..., None, None]
|
| 196 |
+
|
| 197 |
+
r = input[..., 0, :, :] * r_w
|
| 198 |
+
g = input[..., 1, :, :]
|
| 199 |
+
b = input[..., 2, :, :] * b_w
|
| 200 |
+
|
| 201 |
+
output = stack([r, g, b], -3)
|
| 202 |
+
|
| 203 |
+
return output.clamp(max=1.0)
|
python_embeded/Lib/site-packages/kornia/augmentation/_3d/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from kornia.augmentation._3d.geometric import *
|
| 19 |
+
from kornia.augmentation._3d.intensity import *
|
| 20 |
+
from kornia.augmentation._3d.mix import *
|
python_embeded/Lib/site-packages/kornia/augmentation/_3d/base.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LICENSE HEADER MANAGED BY add-license-header
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2018 Kornia Team
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from typing import Any, Dict, Optional
|
| 19 |
+
|
| 20 |
+
from torch import float16, float32, float64
|
| 21 |
+
|
| 22 |
+
import kornia
|
| 23 |
+
from kornia.augmentation.base import _AugmentationBase
|
| 24 |
+
from kornia.augmentation.utils import _transform_input3d, _transform_input3d_by_shape, _validate_input_dtype
|
| 25 |
+
from kornia.core import Tensor
|
| 26 |
+
from kornia.geometry.boxes import Boxes3D
|
| 27 |
+
from kornia.geometry.keypoints import Keypoints3D
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class AugmentationBase3D(_AugmentationBase):
|
| 31 |
+
r"""AugmentationBase3D base class for customized augmentation implementations.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
p: probability for applying an augmentation. This param controls the augmentation probabilities
|
| 35 |
+
element-wise for a batch.
|
| 36 |
+
p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
|
| 37 |
+
probabilities batch-wise.
|
| 38 |
+
same_on_batch: apply the same transformation across the batch.
|
| 39 |
+
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def validate_tensor(self, input: Tensor) -> None:
|
| 43 |
+
"""Check if the input tensor is formatted as expected."""
|
| 44 |
+
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
|
| 45 |
+
if len(input.shape) != 5:
|
| 46 |
+
raise RuntimeError(f"Expect (B, C, D, H, W). Got {input.shape}.")
|
| 47 |
+
|
| 48 |
+
def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor:
|
| 49 |
+
"""Convert any incoming (D, H, W), (C, D, H, W) and (B, C, D, H, W) into (B, C, D, H, W)."""
|
| 50 |
+
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
|
| 51 |
+
if shape is None:
|
| 52 |
+
return _transform_input3d(input)
|
| 53 |
+
else:
|
| 54 |
+
return _transform_input3d_by_shape(input, reference_shape=shape, match_channel=match_channel)
|
| 55 |
+
|
| 56 |
+
def identity_matrix(self, input: Tensor) -> Tensor:
|
| 57 |
+
"""Return 4x4 identity matrix."""
|
| 58 |
+
return kornia.eye_like(4, input)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class RigidAffineAugmentationBase3D(AugmentationBase3D):
|
| 62 |
+
r"""AugmentationBase2D base class for rigid/affine augmentation implementations.
|
| 63 |
+
|
| 64 |
+
RigidAffineAugmentationBase2D enables routined transformation with given transformation matrices
|
| 65 |
+
for different data types like masks, boxes, and keypoints.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
p: probability for applying an augmentation. This param controls the augmentation probabilities
|
| 69 |
+
element-wise for a batch.
|
| 70 |
+
p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
|
| 71 |
+
probabilities batch-wise.
|
| 72 |
+
same_on_batch: apply the same transformation across the batch.
|
| 73 |
+
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch
|
| 74 |
+
form ``False``.
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
_transform_matrix: Optional[Tensor]
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def transform_matrix(self) -> Optional[Tensor]:
|
| 82 |
+
return self._transform_matrix
|
| 83 |
+
|
| 84 |
+
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 85 |
+
raise NotImplementedError
|
| 86 |
+
|
| 87 |
+
def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
|
| 88 |
+
"""Generate transformation matrices with the given input and param settings."""
|
| 89 |
+
batch_prob = params["batch_prob"]
|
| 90 |
+
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
|
| 91 |
+
in_tensor = self.transform_tensor(input)
|
| 92 |
+
if not to_apply.any():
|
| 93 |
+
trans_matrix = self.identity_matrix(in_tensor)
|
| 94 |
+
elif to_apply.all():
|
| 95 |
+
trans_matrix = self.compute_transformation(in_tensor, params=params, flags=flags)
|
| 96 |
+
else:
|
| 97 |
+
trans_matrix = self.identity_matrix(in_tensor)
|
| 98 |
+
trans_matrix = trans_matrix.index_put(
|
| 99 |
+
(to_apply,), self.compute_transformation(in_tensor[to_apply], params=params, flags=flags)
|
| 100 |
+
)
|
| 101 |
+
return trans_matrix
|
| 102 |
+
|
| 103 |
+
def inverse_inputs(
|
| 104 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 105 |
+
) -> Tensor:
|
| 106 |
+
raise NotImplementedError
|
| 107 |
+
|
| 108 |
+
def inverse_masks(
|
| 109 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 110 |
+
) -> Tensor:
|
| 111 |
+
raise NotImplementedError
|
| 112 |
+
|
| 113 |
+
def inverse_boxes(
|
| 114 |
+
self, input: Boxes3D, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 115 |
+
) -> Boxes3D:
|
| 116 |
+
raise NotImplementedError
|
| 117 |
+
|
| 118 |
+
def inverse_keypoints(
|
| 119 |
+
self, input: Keypoints3D, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 120 |
+
) -> Keypoints3D:
|
| 121 |
+
raise NotImplementedError
|
| 122 |
+
|
| 123 |
+
def inverse_classes(
|
| 124 |
+
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
|
| 125 |
+
) -> Tensor:
|
| 126 |
+
raise NotImplementedError
|
| 127 |
+
|
| 128 |
+
def apply_func(
|
| 129 |
+
self, in_tensor: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None
|
| 130 |
+
) -> Tensor:
|
| 131 |
+
if flags is None:
|
| 132 |
+
flags = self.flags
|
| 133 |
+
|
| 134 |
+
trans_matrix = self.generate_transformation_matrix(in_tensor, params, flags)
|
| 135 |
+
output = self.transform_inputs(in_tensor, params, flags, trans_matrix)
|
| 136 |
+
self._transform_matrix = trans_matrix
|
| 137 |
+
|
| 138 |
+
return output
|