Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

addopt ruff formatter (#2638)

João Gustavo A. Amorimbc3ab4defc13
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 8d314c04c..e6875f162 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -24,11 +24,7 @@ repos:
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
-
- - repo: https://github.com/psf/black
- rev: 23.10.1
- hooks:
- - id: black
+ - id: ruff-format
- repo: https://github.com/codespell-project/codespell
rev: v2.2.6
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6a291dde0..0ff31c053 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -288,8 +288,8 @@ test that:
- Typing with [mypy](http://mypy-lang.org) type checks the Python code.
- If the docs can be generated successfully
- [pre-commit ci](https://pre-commit.ci)
- - [ruff](https://pypi.org/project/ruff/) accepts the code style (our guidelines are based on PEP8).
- - [black](https://black.readthedocs.io/en/stable/) checks if the code is well formatted
+ - [ruff](https://pypi.org/project/ruff/) accepts the code style (our guidelines are based on PEP8) and checks if the code
+ is well formatted
- [docformatter](https://pypi.org/project/docformatter/) checks if the code docstrings are well formatted
- and some other checks. Check our [pre-commit config](./.pre-commit-config.yaml)
diff --git a/conftest.py b/conftest.py
index ae3ec004e..58c697f34 100644
--- a/conftest.py
+++ b/conftest.py
@@ -25,7 +25,7 @@ def get_test_devices() -> Dict[str, torch.device]:
import torch_xla.core.xla_model as xm
devices["tpu"] = xm.xla_device()
- if hasattr(torch.backends, 'mps'):
+ if hasattr(torch.backends, "mps"):
if torch.backends.mps.is_available():
devices["mps"] = torch.device("mps")
return devices
@@ -65,10 +65,10 @@ def dtype(dtype_name) -> torch.dtype:
return TEST_DTYPES[dtype_name]
[email protected](scope='session')
[email protected](scope="session")
def torch_optimizer():
- if hasattr(torch, 'compile') and sys.platform == "linux":
- if not (sys.version_info[:2] == (3, 11) and torch_version() in {'2.0.0', '2.0.1'}):
+ if hasattr(torch, "compile") and sys.platform == "linux":
+ if not (sys.version_info[:2] == (3, 11) and torch_version() in {"2.0.0", "2.0.1"}):
# torch compile just have support for python 3.11 after torch 2.1.0
return torch.compile
@@ -78,26 +78,26 @@ def torch_optimizer():
def pytest_generate_tests(metafunc):
device_names = None
dtype_names = None
- if 'device_name' in metafunc.fixturenames:
- raw_value = metafunc.config.getoption('--device')
- if raw_value == 'all':
+ if "device_name" in metafunc.fixturenames:
+ raw_value = metafunc.config.getoption("--device")
+ if raw_value == "all":
device_names = list(TEST_DEVICES.keys())
else:
- device_names = raw_value.split(',')
- if 'dtype_name' in metafunc.fixturenames:
- raw_value = metafunc.config.getoption('--dtype')
- if raw_value == 'all':
+ device_names = raw_value.split(",")
+ if "dtype_name" in metafunc.fixturenames:
+ raw_value = metafunc.config.getoption("--dtype")
+ if raw_value == "all":
dtype_names = list(TEST_DTYPES.keys())
else:
- dtype_names = raw_value.split(',')
+ dtype_names = raw_value.split(",")
if device_names is not None and dtype_names is not None:
# Exclude any blacklisted device/dtype combinations.
params = [combo for combo in product(device_names, dtype_names) if combo not in DEVICE_DTYPE_BLACKLIST]
- metafunc.parametrize('device_name,dtype_name', params)
+ metafunc.parametrize("device_name,dtype_name", params)
elif device_names is not None:
- metafunc.parametrize('device_name', device_names)
+ metafunc.parametrize("device_name", device_names)
elif dtype_names is not None:
- metafunc.parametrize('dtype_name', dtype_names)
+ metafunc.parametrize("dtype_name", dtype_names)
def pytest_collection_modifyitems(config, items):
@@ -112,15 +112,15 @@ def pytest_collection_modifyitems(config, items):
def pytest_addoption(parser):
- parser.addoption('--device', action="store", default="cpu")
- parser.addoption('--dtype', action="store", default="float32")
+ parser.addoption("--device", action="store", default="cpu")
+ parser.addoption("--dtype", action="store", default="float32")
parser.addoption("--runslow", action="store_true", default=False, help="run slow tests")
def _setup_torch_compile():
- if hasattr(torch, 'compile') and sys.platform == "linux":
- print('Setting up torch compile...')
- torch.set_float32_matmul_precision('high')
+ if hasattr(torch, "compile") and sys.platform == "linux":
+ print("Setting up torch compile...")
+ torch.set_float32_matmul_precision("high")
def _dummy_function(x, y):
return (x + y).sum()
@@ -140,7 +140,7 @@ def pytest_sessionstart(session):
try:
_setup_torch_compile()
except RuntimeError as ex:
- if 'not yet supported for torch.compile' not in str(ex):
+ if "not yet supported for torch.compile" not in str(ex):
raise ex
# TODO: cache all torch.load weights/states here to not impact on test suite
@@ -149,9 +149,9 @@ def pytest_report_header(config):
try:
import accelerate
- accelerate_info = f'accelerate-{accelerate.__version__}'
+ accelerate_info = f"accelerate-{accelerate.__version__}"
except ImportError:
- accelerate_info = '`accelerate` not found'
+ accelerate_info = "`accelerate` not found"
import kornia_rs
import onnx
@@ -178,19 +178,19 @@ def add_doctest_deps(doctest_namespace):
# the commit hash for the data version
-sha: str = 'cb8f42bf28b9f347df6afba5558738f62a11f28a'
-sha2: str = 'f7d8da661701424babb64850e03c5e8faec7ea62'
-sha3: str = '8b98f44abbe92b7a84631ed06613b08fee7dae14'
+sha: str = "cb8f42bf28b9f347df6afba5558738f62a11f28a"
+sha2: str = "f7d8da661701424babb64850e03c5e8faec7ea62"
+sha3: str = "8b98f44abbe92b7a84631ed06613b08fee7dae14"
[email protected](scope='session')
[email protected](scope="session")
def data(request):
url = {
- 'loftr_homo': f'https://github.com/kornia/data_test/blob/{sha}/loftr_outdoor_and_homography_data.pt?raw=true',
- 'loftr_fund': f'https://github.com/kornia/data_test/blob/{sha}/loftr_indoor_and_fundamental_data.pt?raw=true',
- 'adalam_idxs': f'https://github.com/kornia/data_test/blob/{sha2}/adalam_test.pt?raw=true',
- 'lightglue_idxs': f'https://github.com/kornia/data_test/blob/{sha2}/adalam_test.pt?raw=true',
- 'disk_outdoor': f'https://github.com/kornia/data_test/blob/{sha3}/knchurch_disk.pt?raw=true',
- 'dexined': 'https://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth',
+ "loftr_homo": f"https://github.com/kornia/data_test/blob/{sha}/loftr_outdoor_and_homography_data.pt?raw=true",
+ "loftr_fund": f"https://github.com/kornia/data_test/blob/{sha}/loftr_indoor_and_fundamental_data.pt?raw=true",
+ "adalam_idxs": f"https://github.com/kornia/data_test/blob/{sha2}/adalam_test.pt?raw=true",
+ "lightglue_idxs": f"https://github.com/kornia/data_test/blob/{sha2}/adalam_test.pt?raw=true",
+ "disk_outdoor": f"https://github.com/kornia/data_test/blob/{sha3}/knchurch_disk.pt?raw=true",
+ "dexined": "https://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",
}
- return torch.hub.load_state_dict_from_url(url[request.param], map_location=torch.device('cpu'))
+ return torch.hub.load_state_dict_from_url(url[request.param], map_location=torch.device("cpu"))
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index 75b6bf225..f57db28fd 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -21,14 +21,14 @@ mpl.use("Agg")
def download_tutorials_examples(download_infos: dict[str, str], directory: Path):
- URL_BASE = 'https://raw.githubusercontent.com/kornia/tutorials/master/'
+ URL_BASE = "https://raw.githubusercontent.com/kornia/tutorials/master/"
for filename, path in download_infos.items():
url = URL_BASE + path
# perform request
response = requests.get(url, timeout=60).content
path = directory / filename
- with open(path, 'wb') as fp:
+ with open(path, "wb") as fp:
fp.write(response)
@@ -53,7 +53,7 @@ def transparent_pad(src: Tensor, shape: tuple[int, int]) -> Tensor:
"""Apply a transparent pad to src (centerized) to match with shape (h, w)"""
w_pad = abs(int(src.shape[-1] - shape[-1]) // 2)
h_pad = abs(int(src.shape[-2] - shape[-2]) // 2)
- return torch.nn.functional.pad(K.color.rgb_to_rgba(src, 1.0), (w_pad, w_pad, h_pad, h_pad), 'constant', 0.0)
+ return torch.nn.functional.pad(K.color.rgb_to_rgba(src, 1.0), (w_pad, w_pad, h_pad, h_pad), "constant", 0.0)
def draw_bbox_kpts(imgs, bboxes, keypoints):
@@ -80,9 +80,9 @@ def draw_bbox_kpts(imgs, bboxes, keypoints):
def main():
# Download the tutorial examples for the main docs
URLS_TUTORIALS_EXAMPLES = {
- 'image_classifier.py': 'scripts/training/image_classifier/main.py',
- 'object_detection.py': 'scripts/training/object_detection/main.py',
- 'semantic_segmentation.py': 'scripts/training/semantic_segmentation/main.py',
+ "image_classifier.py": "scripts/training/image_classifier/main.py",
+ "object_detection.py": "scripts/training/object_detection/main.py",
+ "semantic_segmentation.py": "scripts/training/semantic_segmentation/main.py",
}
OUTPUT_PATH_SCRIPTS = Path(__file__).absolute().parent / "source/_static/scripts/"
@@ -98,7 +98,7 @@ def main():
BASE_IMAGE_URL4: str = "https://raw.githubusercontent.com/kornia/data/main/baby_giraffe.png" # morphology
BASE_IMAGE_URL5: str = "https://raw.githubusercontent.com/kornia/data/main/persistencia_memoria.jpg" # filters
BASE_IMAGE_URL6: str = "https://raw.githubusercontent.com/kornia/data/main/delorean.png" # geometry
- hash1 = '8b98f44abbe92b7a84631ed06613b08fee7dae14'
+ hash1 = "8b98f44abbe92b7a84631ed06613b08fee7dae14"
BASE_IMAGEOUTDOOR_URL7: str = f"https://github.com/kornia/data_test/raw/{hash1}/knchurch_disk.pt" # image matching
BASE_IMAGEOUTDOOR_URL8: str = ( # Response functions
"https://github.com/kornia/data/raw/main/kornia_banner_pixie.png"
@@ -243,14 +243,14 @@ def main():
# Containers
aug_container_list = {
- 'AugmentationSequential': (
+ "AugmentationSequential": (
{
- 'args': (
+ "args": (
K.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
K.augmentation.RandomAffine(360, [0.1, 0.1], [0.7, 1.2], [30.0, 50.0], p=1.0),
K.augmentation.RandomPerspective(0.5, p=1.0),
),
- 'data_keys': ["input", "bbox_xywh", "keypoints"],
+ "data_keys": ["input", "bbox_xywh", "keypoints"],
},
(
torch.tensor([[[125, 5, 115, 80]]], dtype=torch.float32), # bbox
@@ -259,17 +259,17 @@ def main():
2,
2023,
),
- 'PatchSequential': (
+ "PatchSequential": (
{
- 'args': (
+ "args": (
K.augmentation.ColorJitter(0.2, 0.1, 0.1, 0.1, p=1),
K.augmentation.RandomAffine(10, [0.1, 0.2], [0.7, 1.2], [0.0, 15.0], p=1),
K.augmentation.RandomPerspective(0.3, p=1),
K.augmentation.RandomSolarize(0.01, 0.05, p=0.6),
),
- 'grid_size': (2, 2),
- 'same_on_batch': False,
- 'patchwise_apply': False,
+ "grid_size": (2, 2),
+ "same_on_batch": False,
+ "patchwise_apply": False,
},
(),
2,
@@ -279,12 +279,12 @@ def main():
for aug_name, (args, labels, num_samples, seed) in aug_container_list.items():
img_in = img1.repeat(num_samples, 1, 1, 1)
cls = getattr(mod, aug_name)
- tfms = args.pop('args')
+ tfms = args.pop("args")
augs = cls(*tfms, **args)
# set seed
torch.manual_seed(seed)
- if aug_name == 'PatchSequential':
+ if aug_name == "PatchSequential":
out = augs(img_in)
inp = img_in
else:
@@ -503,8 +503,8 @@ def main():
"remap": (
(
*(K.utils.create_meshgrid(h, w, normalized_coordinates=True) - 0.25).unbind(-1),
- 'bilinear',
- 'zeros',
+ "bilinear",
+ "zeros",
True,
True,
),
@@ -565,17 +565,17 @@ def main():
print(f"Generated image example for {fn_name}. {sig}")
# Image Matching and local features
- img_matching_data = torch.hub.load_state_dict_from_url(BASE_IMAGEOUTDOOR_URL7, map_location=torch.device('cpu'))
- img_outdoor = img_matching_data['img2']
+ img_matching_data = torch.hub.load_state_dict_from_url(BASE_IMAGEOUTDOOR_URL7, map_location=torch.device("cpu"))
+ img_outdoor = img_matching_data["img2"]
print("Generating local feature detections ")
- disk = K.feature.DISK.from_pretrained('depth')
+ disk = K.feature.DISK.from_pretrained("depth")
with torch.no_grad():
disk_feat = disk(img_outdoor)[0]
xy = disk_feat.keypoints.detach().cpu().numpy()
cur_fname = str(OUTPUT_PATH / "disk_outdoor_depth.jpg")
plt.figure()
plt.imshow(K.tensor_to_image(img_outdoor))
- plt.scatter(xy[:, 0], xy[:, 1], 3, color='lime')
+ plt.scatter(xy[:, 0], xy[:, 1], 3, color="lime")
plt.title('DISK("depth") keypoints')
plt.savefig(cur_fname)
plt.close()
@@ -583,8 +583,8 @@ def main():
kah = K.feature.KeyNetAffNetHardNet(512).eval()
with torch.no_grad():
lafs, resps, descs = kah(K.color.rgb_to_grayscale(img_outdoor))
- fig1, ax = visualize_LAF(img_outdoor, lafs, color='lime', return_fig_ax=True, draw_ori=False)
- ax.set_title('KeyNetAffNet 512 LAFs')
+ fig1, ax = visualize_LAF(img_outdoor, lafs, color="lime", return_fig_ax=True, draw_ori=False)
+ ax.set_title("KeyNetAffNet 512 LAFs")
cur_fname = str(OUTPUT_PATH / "keynet_affnet.jpg")
fig1.savefig(cur_fname)
plt.close()
@@ -596,8 +596,8 @@ def main():
cur_fname = str(OUTPUT_PATH / "keynet.jpg")
plt.figure()
plt.imshow(K.tensor_to_image(img_outdoor))
- plt.scatter(xy[:, 0], xy[:, 1], 3, color='lime')
- plt.title('KeyNet 512 keypoints')
+ plt.scatter(xy[:, 0], xy[:, 1], 3, color="lime")
+ plt.title("KeyNet 512 keypoints")
plt.savefig(cur_fname)
plt.close()
@@ -609,11 +609,11 @@ def main():
# import function and apply
# import pdb;pdb.set_trace()
img_in = K.color.rgb_to_grayscale(img_kornia)
- if fn_name == 'KeyNet':
+ if fn_name == "KeyNet":
fn = K.feature.KeyNet(True)
out = fn(img_in)
- elif fn_name == 'DISK':
- fn = K.feature.DISK.from_pretrained('depth')
+ elif fn_name == "DISK":
+ fn = K.feature.DISK.from_pretrained("depth")
h, w = img_outdoor.shape[2:]
pd_h = 32 - h % 32 if h % 32 > 0 else 0
pd_w = 32 - w % 32 if w % 32 > 0 else 0
diff --git a/docs/source/_static/image_registration.py b/docs/source/_static/image_registration.py
index 02e826c61..faa45f34a 100644
--- a/docs/source/_static/image_registration.py
+++ b/docs/source/_static/image_registration.py
@@ -18,13 +18,13 @@ def load_timg(file_name):
return K.color.bgr_to_rgb(tensor)
-registrator = KG.ImageRegistrator('similarity')
+registrator = KG.ImageRegistrator("similarity")
-img1 = K.resize(load_timg('/Users/oldufo/datasets/stewart/MR-CT/CT.png'), (400, 600))
-img2 = K.resize(load_timg('/Users/oldufo/datasets/stewart/MR-CT/MR.png'), (400, 600))
+img1 = K.resize(load_timg("/Users/oldufo/datasets/stewart/MR-CT/CT.png"), (400, 600))
+img2 = K.resize(load_timg("/Users/oldufo/datasets/stewart/MR-CT/MR.png"), (400, 600))
model, intermediate = registrator.register(img1, img2, output_intermediate_models=True)
-video_writer = imageio.get_writer('medical_registration.gif', fps=2)
+video_writer = imageio.get_writer("medical_registration.gif", fps=2)
timg_dst_first = img1.clone()
timg_dst_first[0, 0, :, :] = img2[0, 0, :, :]
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 5fcb607a1..464363925 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -30,55 +30,55 @@ sys.path.append(current_path)
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
- 'sphinx.ext.autodoc',
- 'sphinx.ext.autosummary',
- 'sphinx.ext.doctest',
- 'sphinx.ext.intersphinx',
- 'sphinx.ext.mathjax',
- 'sphinx.ext.napoleon',
- 'sphinx_autodoc_typehints',
- 'sphinx_autodoc_defaultargs',
- 'sphinx_copybutton',
- 'sphinx.ext.viewcode',
- 'sphinx.ext.githubpages',
- 'sphinxcontrib.bibtex',
+ "sphinx.ext.autodoc",
+ "sphinx.ext.autosummary",
+ "sphinx.ext.doctest",
+ "sphinx.ext.intersphinx",
+ "sphinx.ext.mathjax",
+ "sphinx.ext.napoleon",
+ "sphinx_autodoc_typehints",
+ "sphinx_autodoc_defaultargs",
+ "sphinx_copybutton",
+ "sphinx.ext.viewcode",
+ "sphinx.ext.githubpages",
+ "sphinxcontrib.bibtex",
"sphinxcontrib.gtagjs",
- 'sphinxcontrib.youtube',
- 'sphinx_design',
+ "sphinxcontrib.youtube",
+ "sphinx_design",
]
# substitutes the default values
-docstring_default_arg_substitution = 'Default: '
+docstring_default_arg_substitution = "Default: "
autodoc_preserve_defaults = True
-bibtex_bibfiles = ['references.bib']
+bibtex_bibfiles = ["references.bib"]
napoleon_use_ivar = True
# Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates']
+templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
-source_suffix = ['.rst', '.ipynb']
+source_suffix = [".rst", ".ipynb"]
# The master toctree document.
-master_doc = 'index'
+master_doc = "index"
# General information about the project.
-project = 'Kornia'
-author = f'{project} developers'
-copyright = f'2019, {author}'
+project = "Kornia"
+author = f"{project} developers"
+copyright = f"2019, {author}"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
# version = 'master (' + kornia.__version__ + ' )'
-version = ''
+version = ""
-if 'READTHEDOCS' not in os.environ:
+if "READTHEDOCS" not in os.environ:
# if developing locally, use kornia.__version__ as version
from kornia import __version__
@@ -92,33 +92,33 @@ release = version
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
-language = 'en'
+language = "en"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
-exclude_patterns = ['_build', '.ipynb_checkpoints']
+exclude_patterns = ["_build", ".ipynb_checkpoints"]
# The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'friendly'
+pygments_style = "friendly"
pygments_dark_style = "monokai"
-html_theme = 'furo'
+html_theme = "furo"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# TODO(jian): make to work with https://docs.kornia.org
-html_baseurl = 'https://kornia.readthedocs.io'
+html_baseurl = "https://kornia.readthedocs.io"
# Changing sidebar title to Kornia
html_title = "Kornia"
html_theme_options = {
# 'analytics_id': 'G-RKS4WFXVHJ', # Unsupported by furo theme
- 'light_logo': 'img/kornia_logo_only_light.svg',
- 'dark_logo': 'img/kornia_logo_only_dark.svg',
+ "light_logo": "img/kornia_logo_only_light.svg",
+ "dark_logo": "img/kornia_logo_only_dark.svg",
"sidebar_hide_name": True,
"navigation_with_keys": True,
"light_css_variables": {
@@ -147,18 +147,18 @@ html_theme_options = {
# html_logo = '_static/img/kornia_logo.svg'
# html_logo = '_static/img/kornia_logo_only.png'
-html_favicon = '_static/img/kornia_logo_favicon.png'
+html_favicon = "_static/img/kornia_logo_favicon.png"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
-html_static_path = ['_static']
-html_extra_path = ['_extra']
+html_static_path = ["_static"]
+html_extra_path = ["_extra"]
# Output file base name for HTML help builder.
-htmlhelp_basename = 'Kornia'
-html_css_files = ['css/main.css']
-html_js_files = ['js/custom.js']
+htmlhelp_basename = "Kornia"
+html_css_files = ["css/main.css"]
+html_js_files = ["js/custom.js"]
# -- Options for LaTeX output ---------------------------------------------
@@ -181,14 +181,14 @@ latex_elements = {
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
-latex_documents = [(master_doc, 'kornia.tex', 'Kornia', 'manual')]
+latex_documents = [(master_doc, "kornia.tex", "Kornia", "manual")]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
-man_pages = [(master_doc, 'Kornia', 'Kornia Documentation', [author], 1)]
+man_pages = [(master_doc, "Kornia", "Kornia Documentation", [author], 1)]
# -- Options for Texinfo output -------------------------------------------
@@ -199,19 +199,19 @@ man_pages = [(master_doc, 'Kornia', 'Kornia Documentation', [author], 1)]
texinfo_documents = [
(
master_doc,
- 'kornia',
- 'Kornia Documentation',
+ "kornia",
+ "Kornia Documentation",
author,
- 'Kornia',
- 'Differentiable Computer Vision in Pytorch.',
- 'Miscellaneous',
+ "Kornia",
+ "Differentiable Computer Vision in Pytorch.",
+ "Miscellaneous",
)
]
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
- 'python': ('https://docs.python.org/3/', None),
- 'numpy': ('http://numpy.org/doc/stable/', None),
- 'torch': ('http://pytorch.org/docs/stable/', None),
+ "python": ("https://docs.python.org/3/", None),
+ "numpy": ("http://numpy.org/doc/stable/", None),
+ "torch": ("http://pytorch.org/docs/stable/", None),
}
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index f131d6556..e84b18962 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -70,7 +70,7 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):
def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
"""Generate transformation matrices with the given input and param settings."""
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
in_tensor = self.transform_tensor(input)
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index 101e69af4..b6bee1598 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -110,7 +110,7 @@ class RandomAffine(GeometricAugmentationBase2D):
) -> Tensor:
_, _, height, width = input.shape
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return warp_affine(
input,
@@ -129,7 +129,7 @@ class RandomAffine(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 5843d1ce1..8f25db7a3 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -131,7 +131,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
) -> Tensor:
in_tensor = self.transform_tensor(input)
output = in_tensor.clone()
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
params, flags = self._process_kwargs_to_params_and_flags(
@@ -141,7 +141,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
size: Optional[Tuple[int, int]] = None
if "forward_input_shape" in params:
# Majorly for cropping functions
- _size = params['forward_input_shape'].tolist()
+ _size = params["forward_input_shape"].tolist()
size = (_size[-2], _size[-1])
# if no augmentation needed
@@ -185,7 +185,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
**kwargs: Any,
) -> Boxes:
output = input.clone()
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
if transform is None:
@@ -223,7 +223,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
transform: the inverse transformation matrix
"""
output = input.clone()
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
if transform is None:
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index 6789bebb9..266c251cc 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -102,7 +102,7 @@ class CenterCrop(GeometricAugmentationBase2D):
) -> Tensor:
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return crop_by_transform_mat(
input, transform[:, :2, :], self.size, flags["resample"].name.lower(), "zeros", flags["align_corners"]
@@ -125,7 +125,7 @@ class CenterCrop(GeometricAugmentationBase2D):
if size is None:
size = self.size
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return crop_by_transform_mat(
input,
transform[:, :2, :],
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 7efa6a86b..ed8e56c78 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -180,16 +180,16 @@ class RandomCrop(GeometricAugmentationBase2D):
flags = self.flags if flags is None else flags
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
# Fit the arg to F.pad
- if flags['padding_mode'] == "constant":
+ if flags["padding_mode"] == "constant":
padding_mode = "zeros"
- elif flags['padding_mode'] == "replicate":
+ elif flags["padding_mode"] == "replicate":
padding_mode = "border"
- elif flags['padding_mode'] == "reflect":
+ elif flags["padding_mode"] == "reflect":
padding_mode = "reflection"
else:
- padding_mode = flags['padding_mode']
+ padding_mode = flags["padding_mode"]
return crop_by_transform_mat(
input,
@@ -217,16 +217,16 @@ class RandomCrop(GeometricAugmentationBase2D):
if size is None:
raise RuntimeError("`size` has to be a tuple. Got None.")
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
# Fit the arg to F.pad
- if flags['padding_mode'] == "constant":
+ if flags["padding_mode"] == "constant":
padding_mode = "zeros"
- elif flags['padding_mode'] == "replicate":
+ elif flags["padding_mode"] == "replicate":
padding_mode = "border"
- elif flags['padding_mode'] == "reflect":
+ elif flags["padding_mode"] == "reflect":
padding_mode = "reflection"
else:
- padding_mode = flags['padding_mode']
+ padding_mode = flags["padding_mode"]
return crop_by_transform_mat(
input,
transform[:, :2, :],
diff --git a/kornia/augmentation/_2d/geometric/horizontal_flip.py b/kornia/augmentation/_2d/geometric/horizontal_flip.py
index 4c1637848..5e1e3d34c 100644
--- a/kornia/augmentation/_2d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_2d/geometric/horizontal_flip.py
@@ -72,7 +72,7 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index 67050c1b7..4e22be0f4 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -78,7 +78,7 @@ class RandomPerspective(GeometricAugmentationBase2D):
) -> Tensor:
_, _, height, width = input.shape
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return warp_perspective(
input, transform, (height, width), mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
@@ -92,7 +92,7 @@ class RandomPerspective(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index 282639482..51b4d9796 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -84,10 +84,10 @@ class Resize(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
if not isinstance(size, tuple):
- raise TypeError(f'Expected the size be a tuple. Gotcha {type(size)}')
+ raise TypeError(f"Expected the size be a tuple. Gotcha {type(size)}")
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return crop_by_transform_mat(
input, transform[:, :2, :], size, flags["resample"].name.lower(), "zeros", flags["align_corners"]
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index 34663b8b6..9623b36ee 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -94,7 +94,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
) -> Tensor:
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return crop_by_transform_mat(
input,
@@ -126,10 +126,10 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
)
if not isinstance(size, tuple):
- raise TypeError(f'Expected the size be a tuple. Gotcha {type(size)}')
+ raise TypeError(f"Expected the size be a tuple. Gotcha {type(size)}")
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return crop_by_transform_mat(
input,
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index 53be6fe1a..f2372b848 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -91,7 +91,7 @@ class RandomRotation(GeometricAugmentationBase2D):
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return affine(input, transform[..., :2, :3], flags["resample"].name.lower(), "zeros", flags["align_corners"])
@@ -103,7 +103,7 @@ class RandomRotation(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
diff --git a/kornia/augmentation/_2d/geometric/shear.py b/kornia/augmentation/_2d/geometric/shear.py
index 802442c70..449fa9808 100644
--- a/kornia/augmentation/_2d/geometric/shear.py
+++ b/kornia/augmentation/_2d/geometric/shear.py
@@ -87,7 +87,7 @@ class RandomShear(GeometricAugmentationBase2D):
) -> Tensor:
_, _, height, width = input.shape
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return warp_affine(
input,
@@ -106,7 +106,7 @@ class RandomShear(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
diff --git a/kornia/augmentation/_2d/geometric/translate.py b/kornia/augmentation/_2d/geometric/translate.py
index 13f91defe..496358463 100644
--- a/kornia/augmentation/_2d/geometric/translate.py
+++ b/kornia/augmentation/_2d/geometric/translate.py
@@ -83,7 +83,7 @@ class RandomTranslate(GeometricAugmentationBase2D):
) -> Tensor:
_, _, height, width = input.shape
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return warp_affine(
input,
@@ -102,7 +102,7 @@ class RandomTranslate(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
diff --git a/kornia/augmentation/_2d/geometric/vertical_flip.py b/kornia/augmentation/_2d/geometric/vertical_flip.py
index ef59b5b3b..ae9d14b83 100644
--- a/kornia/augmentation/_2d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_2d/geometric/vertical_flip.py
@@ -64,7 +64,7 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ raise TypeError(f"Expected the `transform` be a Tensor. Got {type(transform)}.")
return self.apply_transform(
input,
params=self._params,
diff --git a/kornia/augmentation/_2d/intensity/brightness.py b/kornia/augmentation/_2d/intensity/brightness.py
index 844d24673..a4486b8be 100644
--- a/kornia/augmentation/_2d/intensity/brightness.py
+++ b/kornia/augmentation/_2d/intensity/brightness.py
@@ -63,7 +63,7 @@ class RandomBrightness(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.brightness: Tensor = _range_bound(brightness, 'brightness', center=1.0, bounds=(0.0, 2.0))
+ self.brightness: Tensor = _range_bound(brightness, "brightness", center=1.0, bounds=(0.0, 2.0))
self._param_generator = rg.PlainUniformGenerator((self.brightness, "brightness_factor", None, None))
self.clip_output = clip_output
diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.py
index 532ed176d..995a7346a 100644
--- a/kornia/augmentation/_2d/intensity/contrast.py
+++ b/kornia/augmentation/_2d/intensity/contrast.py
@@ -62,7 +62,7 @@ class RandomContrast(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.contrast: Tensor = _range_bound(contrast, 'contrast', center=1.0)
+ self.contrast: Tensor = _range_bound(contrast, "contrast", center=1.0)
self._param_generator = rg.PlainUniformGenerator((self.contrast, "contrast_factor", None, None))
self.clip_output = clip_output
diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.py
index 4f57618ce..b2989def5 100644
--- a/kornia/augmentation/_2d/intensity/hue.py
+++ b/kornia/augmentation/_2d/intensity/hue.py
@@ -57,7 +57,7 @@ class RandomHue(IntensityAugmentationBase2D):
self, hue: Tuple[float, float] = (0.0, 0.0), same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.hue: Tensor = _range_bound(hue, 'hue', bounds=(-0.5, 0.5))
+ self.hue: Tensor = _range_bound(hue, "hue", bounds=(-0.5, 0.5))
self._param_generator = rg.PlainUniformGenerator((self.hue, "hue_factor", None, None))
def apply_transform(
diff --git a/kornia/augmentation/_2d/intensity/planckian_jitter.py b/kornia/augmentation/_2d/intensity/planckian_jitter.py
index 6d8ff3c2d..1da4d9fc1 100644
--- a/kornia/augmentation/_2d/intensity/planckian_jitter.py
+++ b/kornia/augmentation/_2d/intensity/planckian_jitter.py
@@ -8,7 +8,7 @@ from kornia.utils import get_cuda_or_mps_device_if_available
def get_planckian_coeffs(mode: str) -> Tensor:
default_device = get_cuda_or_mps_device_if_available()
- if mode.lower() == 'blackbody':
+ if mode.lower() == "blackbody":
coefs = tensor(
[
[0.6743, 0.4029, 0.0013],
@@ -40,7 +40,7 @@ def get_planckian_coeffs(mode: str) -> Tensor:
device=default_device,
)
- elif mode.upper() == 'CIED':
+ elif mode.upper() == "CIED":
coefs = tensor(
[
[0.5829, 0.4421, 0.2288],
@@ -70,7 +70,7 @@ def get_planckian_coeffs(mode: str) -> Tensor:
device=default_device,
)
else:
- raise RuntimeError(f'Unexpected mode. Gotcha {mode}')
+ raise RuntimeError(f"Unexpected mode. Gotcha {mode}")
return stack((coefs[:, 0] / coefs[:, 1], coefs[:, 2] / coefs[:, 1]), 1)
@@ -172,7 +172,7 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
- list_idx = params['idx'].tolist()
+ list_idx = params["idx"].tolist()
self.pl = self.pl.to(device=input.device)
diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.py
index 83a1791db..d09810614 100644
--- a/kornia/augmentation/_2d/intensity/random_rain.py
+++ b/kornia/augmentation/_2d/intensity/random_rain.py
@@ -53,24 +53,24 @@ class RandomRain(IntensityAugmentationBase2D):
KORNIA_CHECK(image.shape[1] in {3, 1}, "Number of color channels should be 1 or 3.")
KORNIA_CHECK(
bool(
- torch.all(params['drop_height_factor'] <= image.shape[2])
- and torch.all(params['drop_height_factor'] > 0)
+ torch.all(params["drop_height_factor"] <= image.shape[2])
+ and torch.all(params["drop_height_factor"] > 0)
),
"Height of drop should be greater than zero and less than image height.",
)
KORNIA_CHECK(
- bool(torch.all(torch.abs(params['drop_width_factor']) <= image.shape[3])),
+ bool(torch.all(torch.abs(params["drop_width_factor"]) <= image.shape[3])),
"Width of drop should be less than image width.",
)
modeified_img = image.clone()
for i in range(image.shape[0]):
- number_of_drops: int = int(params['number_of_drops_factor'][i])
+ number_of_drops: int = int(params["number_of_drops_factor"][i])
# We generate tensor with maximum number of drops, and then remove unnecessary drops.
- coordinates_of_drops: Tensor = params['coordinates_factor'][i][:number_of_drops]
- height_of_drop: int = int(params['drop_height_factor'][i])
- width_of_drop: int = int(params['drop_width_factor'][i])
+ coordinates_of_drops: Tensor = params["coordinates_factor"][i][:number_of_drops]
+ height_of_drop: int = int(params["drop_height_factor"][i])
+ width_of_drop: int = int(params["drop_width_factor"][i])
# Generate start coordinates for each drop
random_y_coords = coordinates_of_drops[:, 0] * (image.shape[2] - height_of_drop - 1)
diff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
index dbf8a5ad6..59e9082c9 100644
--- a/kornia/augmentation/_2d/intensity/random_rgb_shift.py
+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
@@ -92,4 +92,4 @@ class RandomRGBShift(IntensityAugmentationBase2D):
def apply_transform(
self, inp: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
- return shift_rgb(inp, params['r_shift'], params['g_shift'], params['b_shift'])
+ return shift_rgb(inp, params["r_shift"], params["g_shift"], params["b_shift"])
diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.py
index c1b7e5f9c..94f7f7cff 100644
--- a/kornia/augmentation/_2d/intensity/saturation.py
+++ b/kornia/augmentation/_2d/intensity/saturation.py
@@ -60,7 +60,7 @@ class RandomSaturation(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.saturation: Tensor = _range_bound(saturation, 'saturation', center=1.0)
+ self.saturation: Tensor = _range_bound(saturation, "saturation", center=1.0)
self._param_generator = rg.PlainUniformGenerator((self.saturation, "saturation_factor", None, None))
def apply_transform(
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index c6b4933af..ff30c2cf2 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -52,7 +52,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
return input
def transform_input(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
ori_shape = input.shape
in_tensor = self.transform_tensor(input)
@@ -67,7 +67,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
return output
def transform_mask(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output = input
if sum(to_apply) != len(to_apply):
@@ -82,7 +82,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
if not (len(input.shape) == 4 and input.shape[2:] == torch.Size([4, 2])):
raise RuntimeError(f"Only BxNx4x2 tensor is supported. Got {input.shape}.")
input = Boxes(input, False, mode="vertices_plus")
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output = input
if sum(to_apply) != len(to_apply):
@@ -92,7 +92,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
return output
def transform_keypoint(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output = input
if sum(to_apply) != len(to_apply):
@@ -102,7 +102,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
return output
def transform_class(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output = input
if sum(to_apply) != len(to_apply):
diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.py
index 8cc3423af..37c815e8a 100644
--- a/kornia/augmentation/_2d/mix/jigsaw.py
+++ b/kornia/augmentation/_2d/mix/jigsaw.py
@@ -55,7 +55,7 @@ class RandomJigsaw(MixAugmentationBaseV2):
self, input: Tensor, params: Dict[str, Tensor], maybe_flags: Optional[Dict[str, Any]] = None
) -> Tensor:
# different from the Base class routine. This function will not refer to any non-transformation images.
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
input = input[to_apply].clone()
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index 4f687f3af..acbc1ca59 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -103,13 +103,13 @@ class RandomMosaic(MixAugmentationBaseV2):
idx = torch.arange(0, input.data.shape[0], device=input.device, dtype=torch.long)[to_apply]
maybe_out_boxes: Optional[Boxes] = None
- for i in range(flags['mosaic_grid'][0]):
- for j in range(flags['mosaic_grid'][1]):
+ for i in range(flags["mosaic_grid"][0]):
+ for j in range(flags["mosaic_grid"][1]):
_offset = offset.clone()
_offset[idx, 0] = batch_shapes[:, -2] * i - src_box[:, 0, 0]
_offset[idx, 1] = batch_shapes[:, -1] * j - src_box[:, 0, 1]
_box = input.clone()
- _idx = i * flags['mosaic_grid'][1] + j
+ _idx = i * flags["mosaic_grid"][1] + j
_box._data[params["permutation"][:, 0]] = _box._data[params["permutation"][:, _idx]]
_box.translate(_offset, inplace=True)
# zero-out unrelated batch elements.
@@ -133,10 +133,10 @@ class RandomMosaic(MixAugmentationBaseV2):
@torch.no_grad()
def _compose_images(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
out = []
- for i in range(flags['mosaic_grid'][0]):
+ for i in range(flags["mosaic_grid"][0]):
out_row = []
- for j in range(flags['mosaic_grid'][1]):
- img_idx = flags['mosaic_grid'][1] * i + j
+ for j in range(flags["mosaic_grid"][1]):
+ img_idx = flags["mosaic_grid"][1] * i + j
image = input[params["permutation"][:, img_idx]]
out_row.append(image)
out.append(concatenate(out_row, -2))
@@ -156,17 +156,17 @@ class RandomMosaic(MixAugmentationBaseV2):
flags = self.flags if flags is None else flags
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the transform to be a Tensor. Gotcha {type(transform)}')
+ raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}")
# Fit the arg to F.pad
- if flags['padding_mode'] == "constant":
+ if flags["padding_mode"] == "constant":
padding_mode = "zeros"
- elif flags['padding_mode'] == "replicate":
+ elif flags["padding_mode"] == "replicate":
padding_mode = "border"
- elif flags['padding_mode'] == "reflect":
+ elif flags["padding_mode"] == "reflect":
padding_mode = "reflection"
else:
- padding_mode = flags['padding_mode']
+ padding_mode = flags["padding_mode"]
return crop_by_transform_mat(
input,
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index bc76a64c7..cf76f878a 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -64,7 +64,7 @@ class RigidAffineAugmentationBase3D(AugmentationBase3D):
def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
"""Generate transformation matrices with the given input and param settings."""
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
in_tensor = self.transform_tensor(input)
if not to_apply.any():
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
index fc9ff204e..d0e62bbfc 100644
--- a/kornia/augmentation/_3d/geometric/affine.py
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -143,7 +143,7 @@ class RandomAffine3D(GeometricAugmentationBase3D):
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the transform to be a Tensor. Gotcha {type(transform)}')
+ raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}")
return warp_affine3d(
input,
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index ac9400b13..f02a75c81 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -125,7 +125,7 @@ class RandomCrop3D(GeometricAugmentationBase3D):
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the transform to be a Tensor. Gotcha {type(transform)}')
+ raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}")
return crop_by_transform_mat3d(
input, transform, flags["size"], mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.py
index 5fbf965b9..7404852cf 100644
--- a/kornia/augmentation/_3d/geometric/perspective.py
+++ b/kornia/augmentation/_3d/geometric/perspective.py
@@ -83,7 +83,7 @@ class RandomPerspective3D(GeometricAugmentationBase3D):
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the transform to be a Tensor. Gotcha {type(transform)}')
+ raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}")
return warp_perspective3d(
input,
diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.py
index 9b8fe703a..16218cae9 100644
--- a/kornia/augmentation/_3d/geometric/rotation.py
+++ b/kornia/augmentation/_3d/geometric/rotation.py
@@ -108,6 +108,6 @@ class RandomRotation3D(GeometricAugmentationBase3D):
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the transform to be a Tensor. Gotcha {type(transform)}')
+ raise TypeError(f"Expected the transform to be a Tensor. Gotcha {type(transform)}")
return affine3d(input, transform[..., :3, :4], flags["resample"].name.lower(), "zeros", flags["align_corners"])
diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.py
index 29ea4d061..e27a43472 100644
--- a/kornia/augmentation/auto/operations/base.py
+++ b/kornia/augmentation/auto/operations/base.py
@@ -8,7 +8,7 @@ from torch.distributions import Bernoulli, RelaxedBernoulli
from kornia.augmentation.base import _AugmentationBase
from kornia.core import Module, Tensor
-T = TypeVar('T', bound='OperationBase')
+T = TypeVar("T", bound="OperationBase")
class OperationBase(Module):
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 0c90949e7..39136cbeb 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -28,7 +28,7 @@ def _apply_transform_unimplemented(self: Module, *input: Any) -> Tensor:
Should be overridden by all subclasses.
"""
- raise NotImplementedError(f"Module [{type(self).__name__}] is missing the required \"apply_tranform\" function")
+ raise NotImplementedError(f'Module [{type(self).__name__}] is missing the required "apply_tranform" function')
class _BasicAugmentationBase(Module):
@@ -69,7 +69,7 @@ class _BasicAugmentationBase(Module):
self._p_batch_gen = Bernoulli(self.p_batch)
self._param_generator: Optional[RandomGeneratorBase] = None
self.flags: Dict[str, Any] = {}
- self.set_rng_device_and_dtype(torch.device('cpu'), torch.get_default_dtype())
+ self.set_rng_device_and_dtype(torch.device("cpu"), torch.get_default_dtype())
apply_transform: Callable[..., Tensor] = _apply_transform_unimplemented
@@ -171,11 +171,11 @@ class _BasicAugmentationBase(Module):
_params = self.generate_parameters(torch.Size((int(to_apply.sum().item()), *batch_shape[1:])))
if _params is None:
_params = {}
- _params['batch_prob'] = batch_prob
+ _params["batch_prob"] = batch_prob
# Added another input_size parameter for geometric transformations
# This might be needed for correctly inversing.
input_size = tensor(batch_shape, dtype=torch.long)
- _params.update({'forward_input_shape': input_size})
+ _params.update({"forward_input_shape": input_size})
return _params
def apply_func(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
@@ -202,8 +202,8 @@ class _BasicAugmentationBase(Module):
if params is None:
params = self.forward_parameters(batch_shape)
- if 'batch_prob' not in params:
- params['batch_prob'] = tensor([True] * batch_shape[0])
+ if "batch_prob" not in params:
+ params["batch_prob"] = tensor([True] * batch_shape[0])
params, flags = self._process_kwargs_to_params_and_flags(params, self.flags, **kwargs)
@@ -253,7 +253,7 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
ori_shape = input.shape
in_tensor = self.transform_tensor(input)
@@ -291,7 +291,7 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
ori_shape = input.shape
in_tensor = self.transform_tensor(input)
@@ -323,7 +323,7 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output: Boxes
if to_apply.bool().all():
@@ -357,7 +357,7 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
if to_apply.all():
output = self.apply_transform_keypoint(input, params, flags, transform=transform)
@@ -386,7 +386,7 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- batch_prob = params['batch_prob']
+ batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
if to_apply.all():
output = self.apply_transform_class(input, params, flags, transform=transform)
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index d41828af1..3f465b4d1 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -139,7 +139,7 @@ class ImageSequential(ImageSequentialBase):
if isinstance(self.random_apply, tuple):
num_samples = int(torch.randint(*self.random_apply, (1,)).item())
else:
- raise TypeError(f'random apply should be a tuple. Gotcha {type(self.random_apply)}')
+ raise TypeError(f"random apply should be a tuple. Gotcha {type(self.random_apply)}")
multinomial_weights = self.random_apply_weights.clone()
# Mix augmentation can only be applied once per forward
@@ -298,12 +298,12 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size) -> torch.Siz
if isinstance(param.data, list):
for p in param.data:
batch_shape = _get_new_batch_shape(p, batch_shape)
- elif 'output_size' in param.data:
- if not (param.data['batch_prob'] > 0.5)[0]:
+ elif "output_size" in param.data:
+ if not (param.data["batch_prob"] > 0.5)[0]:
# Augmentations that change the image size must be applied equally to all elements in batch.
# If the augmentation is not applied, return the same batch shape.
return batch_shape
new_batch_shape = list(batch_shape)
- new_batch_shape[-2:] = param.data['output_size'][0]
+ new_batch_shape[-2:] = param.data["output_size"][0]
batch_shape = torch.Size(new_batch_shape)
return batch_shape
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 4bc93fadb..c75293b86 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -14,7 +14,7 @@ from .params import ParamItem
DataType = Union[Tensor, List[Tensor], Boxes, Keypoints]
-T = TypeVar('T')
+T = TypeVar("T")
class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
@@ -25,7 +25,7 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
if isinstance(param, ParamItem) and isinstance(param.data, dict):
_params = param.data
else:
- raise TypeError(f'Expected param (ParamItem.data) be a dictionary. Gotcha {param}.')
+ raise TypeError(f"Expected param (ParamItem.data) be a dictionary. Gotcha {param}.")
return _params
@classmethod
@@ -33,7 +33,7 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
if isinstance(param, ParamItem) and isinstance(param.data, list):
_params = param.data
else:
- raise TypeError(f'Expected param (ParamItem.data) be a list. Gotcha {param}.')
+ raise TypeError(f"Expected param (ParamItem.data) be a list. Gotcha {param}.")
return _params
@classmethod
@@ -110,7 +110,10 @@ class AugmentationSequentialOps:
param = ParamItem(
name=param.name,
data=module.params_from_input(
- *arg, data_keys=_data_keys, params=param.data, extra_args=extra_args # type: ignore
+ *arg, # type: ignore[arg-type]
+ data_keys=_data_keys,
+ params=param.data, # type: ignore[arg-type]
+ extra_args=extra_args,
),
)
@@ -142,10 +145,10 @@ class AugmentationSequentialOps:
return outputs
-P = ParamSpec('P')
+P = ParamSpec("P")
-def make_input_only_sequential(module: 'K.container.ImageSequentialBase') -> Callable[P, Tensor]:
+def make_input_only_sequential(module: "K.container.ImageSequentialBase") -> Callable[P, Tensor]:
"""Disable all other additional inputs (e.g. ) for ImageSequential."""
def f(*args: P.args, **kwargs: P.kwargs) -> Tensor:
@@ -154,7 +157,7 @@ def make_input_only_sequential(module: 'K.container.ImageSequentialBase') -> Cal
return f
-def get_geometric_only_param(module: 'K.container.ImageSequentialBase', param: List[ParamItem]) -> List[ParamItem]:
+def get_geometric_only_param(module: "K.container.ImageSequentialBase", param: List[ParamItem]) -> List[ParamItem]:
named_modules = module.get_forward_sequence(param)
res: List[ParamItem] = []
@@ -357,7 +360,11 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
raise ValueError(f"No valid transformation matrix found in {module.__class__}.")
transform = module.compute_inverse_transformation(module.transform_matrix)
_input = module.inverse_boxes(
- _input, param.data, module.flags, transform=transform, **extra_args # type: ignore
+ _input,
+ param.data, # type: ignore[arg-type]
+ module.flags,
+ transform=transform,
+ **extra_args,
)
elif isinstance(module, (K.GeometricAugmentationBase3D,)):
diff --git a/kornia/augmentation/container/params.py b/kornia/augmentation/container/params.py
index 93ae7d778..b5af83f3e 100644
--- a/kornia/augmentation/container/params.py
+++ b/kornia/augmentation/container/params.py
@@ -7,7 +7,7 @@ __all__ = ["ParamItem", "PatchParamItem"]
class ParamItem(NamedTuple):
name: str
- data: Optional[Union[Dict[str, Tensor], List['ParamItem']]]
+ data: Optional[Union[Dict[str, Tensor], List["ParamItem"]]]
class PatchParamItem(NamedTuple):
diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.py
index abcf5e496..8c93e4baf 100644
--- a/kornia/augmentation/random_generator/_2d/affine.py
+++ b/kornia/augmentation/random_generator/_2d/affine.py
@@ -62,25 +62,25 @@ class AffineGenerator(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- _degrees = _range_bound(self.degrees, 'degrees', 0, (-360, 360)).to(device=device, dtype=dtype)
+ _degrees = _range_bound(self.degrees, "degrees", 0, (-360, 360)).to(device=device, dtype=dtype)
_translate = (
self.translate
if self.translate is None
- else _range_bound(self.translate, 'translate', bounds=(0, 1), check='singular').to(
+ else _range_bound(self.translate, "translate", bounds=(0, 1), check="singular").to(
device=device, dtype=dtype
)
)
_scale: Optional[Tensor] = None
if self.scale is not None:
if len(self.scale) == 2:
- _scale = _range_bound(self.scale[:2], 'scale', bounds=(0, float('inf')), check='singular').to(
+ _scale = _range_bound(self.scale[:2], "scale", bounds=(0, float("inf")), check="singular").to(
device=device, dtype=dtype
)
elif len(self.scale) == 4:
_scale = concatenate(
[
- _range_bound(self.scale[:2], 'scale_x', bounds=(0, float('inf')), check='singular'),
- _range_bound(self.scale[-2:], 'scale_y', bounds=(0, float('inf')), check='singular'),
+ _range_bound(self.scale[:2], "scale_x", bounds=(0, float("inf")), check="singular"),
+ _range_bound(self.scale[-2:], "scale_y", bounds=(0, float("inf")), check="singular"),
]
).to(device=device, dtype=dtype)
else:
@@ -93,11 +93,11 @@ class AffineGenerator(RandomGeneratorBase):
else:
_shear = stack(
[
- _range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360)),
+ _range_bound(shear if shear.dim() == 0 else shear[:2], "shear-x", 0, (-360, 360)),
(
tensor([0, 0], device=device, dtype=dtype)
if shear.dim() == 0 or len(shear) == 2
- else _range_bound(shear[2:], 'shear-y', 0, (-360, 360))
+ else _range_bound(shear[2:], "shear-y", 0, (-360, 360))
),
]
)
diff --git a/kornia/augmentation/random_generator/_2d/color_jiggle.py b/kornia/augmentation/random_generator/_2d/color_jiggle.py
index 2cef2f9ca..34382fd12 100644
--- a/kornia/augmentation/random_generator/_2d/color_jiggle.py
+++ b/kornia/augmentation/random_generator/_2d/color_jiggle.py
@@ -53,15 +53,15 @@ class ColorJiggleGenerator(RandomGeneratorBase):
return f"brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation}, hue={self.hue}"
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- brightness = _range_bound(self.brightness, 'brightness', center=1.0, bounds=(0, 2), device=device, dtype=dtype)
- contrast: Tensor = _range_bound(self.contrast, 'contrast', center=1.0, device=device, dtype=dtype)
- saturation: Tensor = _range_bound(self.saturation, 'saturation', center=1.0, device=device, dtype=dtype)
- hue: Tensor = _range_bound(self.hue, 'hue', bounds=(-0.5, 0.5), device=device, dtype=dtype)
+ brightness = _range_bound(self.brightness, "brightness", center=1.0, bounds=(0, 2), device=device, dtype=dtype)
+ contrast: Tensor = _range_bound(self.contrast, "contrast", center=1.0, device=device, dtype=dtype)
+ saturation: Tensor = _range_bound(self.saturation, "saturation", center=1.0, device=device, dtype=dtype)
+ hue: Tensor = _range_bound(self.hue, "hue", bounds=(-0.5, 0.5), device=device, dtype=dtype)
_joint_range_check(brightness, "brightness", (0, 2))
- _joint_range_check(contrast, "contrast", (0, float('inf')))
+ _joint_range_check(contrast, "contrast", (0, float("inf")))
_joint_range_check(hue, "hue", (-0.5, 0.5))
- _joint_range_check(saturation, "saturation", (0, float('inf')))
+ _joint_range_check(saturation, "saturation", (0, float("inf")))
self.brightness_sampler = UniformDistribution(brightness[0], brightness[1], validate_args=False)
self.contrast_sampler = UniformDistribution(contrast[0], contrast[1], validate_args=False)
diff --git a/kornia/augmentation/random_generator/_2d/color_jitter.py b/kornia/augmentation/random_generator/_2d/color_jitter.py
index f02523174..174393309 100644
--- a/kornia/augmentation/random_generator/_2d/color_jitter.py
+++ b/kornia/augmentation/random_generator/_2d/color_jitter.py
@@ -57,15 +57,15 @@ class ColorJitterGenerator(RandomGeneratorBase):
return f"brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation}, hue={self.hue}"
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- brightness: Tensor = _range_bound(self.brightness, 'brightness', center=1.0, device=device, dtype=dtype)
- contrast: Tensor = _range_bound(self.contrast, 'contrast', center=1.0, device=device, dtype=dtype)
- saturation: Tensor = _range_bound(self.saturation, 'saturation', center=1.0, device=device, dtype=dtype)
- hue: Tensor = _range_bound(self.hue, 'hue', bounds=(-0.5, 0.5), device=device, dtype=dtype)
+ brightness: Tensor = _range_bound(self.brightness, "brightness", center=1.0, device=device, dtype=dtype)
+ contrast: Tensor = _range_bound(self.contrast, "contrast", center=1.0, device=device, dtype=dtype)
+ saturation: Tensor = _range_bound(self.saturation, "saturation", center=1.0, device=device, dtype=dtype)
+ hue: Tensor = _range_bound(self.hue, "hue", bounds=(-0.5, 0.5), device=device, dtype=dtype)
- _joint_range_check(brightness, "brightness", (0, float('inf')))
- _joint_range_check(contrast, "contrast", (0, float('inf')))
+ _joint_range_check(brightness, "brightness", (0, float("inf")))
+ _joint_range_check(contrast, "contrast", (0, float("inf")))
_joint_range_check(hue, "hue", (-0.5, 0.5))
- _joint_range_check(saturation, "saturation", (0, float('inf')))
+ _joint_range_check(saturation, "saturation", (0, float("inf")))
self.brightness_sampler = UniformDistribution(brightness[0], brightness[1], validate_args=False)
self.contrast_sampler = UniformDistribution(contrast[0], contrast[1], validate_args=False)
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index 9a6b0f904..3b65c22cf 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -252,7 +252,7 @@ class ResizedCropGenerator(CropGenerator):
def center_crop_generator(
- batch_size: int, height: int, width: int, size: Tuple[int, int], device: Device = torch.device('cpu')
+ batch_size: int, height: int, width: int, size: Tuple[int, int], device: Device = torch.device("cpu")
) -> Dict[str, Tensor]:
r"""Get parameters for ```center_crop``` transformation for center crop transform.
diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.py
index ddf12a182..803e4c74d 100644
--- a/kornia/augmentation/random_generator/_2d/cutmix.py
+++ b/kornia/augmentation/random_generator/_2d/cutmix.py
@@ -64,7 +64,7 @@ class CutmixGenerator(RandomGeneratorBase):
else:
self._cut_size = as_tensor(self.cut_size, device=device, dtype=dtype)
- _joint_range_check(self._cut_size, 'cut_size', bounds=(0, 1))
+ _joint_range_check(self._cut_size, "cut_size", bounds=(0, 1))
self.beta_sampler = Beta(self._beta, self._beta)
self.prob_sampler = Bernoulli(tensor(float(self.p), device=device, dtype=dtype))
diff --git a/kornia/augmentation/random_generator/_2d/gaussian_blur.py b/kornia/augmentation/random_generator/_2d/gaussian_blur.py
index 7c08fb674..dc76330a9 100644
--- a/kornia/augmentation/random_generator/_2d/gaussian_blur.py
+++ b/kornia/augmentation/random_generator/_2d/gaussian_blur.py
@@ -43,7 +43,7 @@ class RandomGaussianBlurGenerator(RandomGeneratorBase):
else:
sigma = self.sigma.to(device=device, dtype=dtype)
- _joint_range_check(sigma, "sigma", (0, float('inf')))
+ _joint_range_check(sigma, "sigma", (0, float("inf")))
self.sigma_sampler = UniformDistribution(sigma[0], sigma[1], validate_args=False)
diff --git a/kornia/augmentation/random_generator/_2d/mixup.py b/kornia/augmentation/random_generator/_2d/mixup.py
index 0e13a6665..e6a51544c 100644
--- a/kornia/augmentation/random_generator/_2d/mixup.py
+++ b/kornia/augmentation/random_generator/_2d/mixup.py
@@ -43,7 +43,7 @@ class MixupGenerator(RandomGeneratorBase):
else:
lambda_val = torch.as_tensor(self.lambda_val, device=device, dtype=dtype)
- _joint_range_check(lambda_val, 'lambda_val', bounds=(0, 1))
+ _joint_range_check(lambda_val, "lambda_val", bounds=(0, 1))
self.lambda_sampler = UniformDistribution(lambda_val[0], lambda_val[1], validate_args=False)
self.prob_sampler = Bernoulli(torch.tensor(float(self.p), device=device, dtype=dtype))
diff --git a/kornia/augmentation/random_generator/_2d/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.py
index fa16c2681..9090d6e33 100644
--- a/kornia/augmentation/random_generator/_2d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py
@@ -54,8 +54,8 @@ class MotionBlurGenerator(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- angle = _range_bound(self.angle, 'angle', center=0.0, bounds=(-360, 360)).to(device=device, dtype=dtype)
- direction = _range_bound(self.direction, 'direction', center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)
+ angle = _range_bound(self.angle, "angle", center=0.0, bounds=(-360, 360)).to(device=device, dtype=dtype)
+ direction = _range_bound(self.direction, "direction", center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)
if isinstance(self.kernel_size, int):
if not (self.kernel_size >= 3 and self.kernel_size % 2 == 1):
raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {self.kernel_size}.")
diff --git a/kornia/augmentation/random_generator/_2d/planckian_jitter.py b/kornia/augmentation/random_generator/_2d/planckian_jitter.py
index 728551ad0..c95b89327 100644
--- a/kornia/augmentation/random_generator/_2d/planckian_jitter.py
+++ b/kornia/augmentation/random_generator/_2d/planckian_jitter.py
@@ -16,9 +16,9 @@ class PlanckianJitterGenerator(RandomGeneratorBase):
self.domain = domain
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- idx_range = _range_bound(self.domain, 'idx_range', device=device, dtype=dtype)
+ idx_range = _range_bound(self.domain, "idx_range", device=device, dtype=dtype)
- _joint_range_check(idx_range, 'idx_range', (0, self.domain[1]))
+ _joint_range_check(idx_range, "idx_range", (0, self.domain[1]))
self.pl_idx_dist = UniformDistribution(idx_range[0], idx_range[1], validate_args=False)
def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
diff --git a/kornia/augmentation/random_generator/_2d/posterize.py b/kornia/augmentation/random_generator/_2d/posterize.py
index 8f26c0880..63529d295 100644
--- a/kornia/augmentation/random_generator/_2d/posterize.py
+++ b/kornia/augmentation/random_generator/_2d/posterize.py
@@ -43,7 +43,7 @@ class PosterizeGenerator(RandomGeneratorBase):
bits[1] = 8
elif not (len(bits.size()) == 1 and bits.size(0) == 2):
raise ValueError(f"'bits' shall be either a scalar or a length 2 tensor. Got {bits}.")
- _joint_range_check(bits, 'bits', (0, 8))
+ _joint_range_check(bits, "bits", (0, 8))
self.bit_sampler = UniformDistribution(bits[0], bits[1], validate_args=False)
def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
diff --git a/kornia/augmentation/random_generator/_2d/probability.py b/kornia/augmentation/random_generator/_2d/probability.py
index e342049e6..a0277ba89 100644
--- a/kornia/augmentation/random_generator/_2d/probability.py
+++ b/kornia/augmentation/random_generator/_2d/probability.py
@@ -48,7 +48,7 @@ def random_prob_generator(
batch_size: int,
p: float = 0.5,
same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
+ device: torch.device = torch.device("cpu"),
dtype: torch.dtype = torch.float32,
) -> Tensor:
r"""Generate random probabilities for a batch of inputs.
diff --git a/kornia/augmentation/random_generator/_2d/random_rain.py b/kornia/augmentation/random_generator/_2d/random_rain.py
index dde27bcae..50332f380 100644
--- a/kornia/augmentation/random_generator/_2d/random_rain.py
+++ b/kornia/augmentation/random_generator/_2d/random_rain.py
@@ -24,24 +24,24 @@ class RainGenerator(RandomGeneratorBase):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
number_of_drops = _range_bound(
self.number_of_drops,
- 'number_of_drops',
+ "number_of_drops",
center=self.number_of_drops[0] / 2 + self.number_of_drops[1] / 2,
bounds=(self.number_of_drops[0], self.number_of_drops[1] + 1),
).to(device)
drop_height = _range_bound(
self.drop_height,
- 'drop_height',
+ "drop_height",
center=self.drop_height[0] / 2 + self.drop_height[1] / 2,
bounds=(self.drop_height[0], self.drop_height[1] + 1),
).to(device)
drop_width = _range_bound(
self.drop_width,
- 'drop_width',
+ "drop_width",
center=self.drop_width[0] / 2 + self.drop_width[1] / 2,
bounds=(self.drop_width[0], self.drop_width[1] + 1),
).to(device)
- drop_coordinates = _range_bound((0, 1), 'drops_coordinate', center=0.5, bounds=(0, 1)).to(
+ drop_coordinates = _range_bound((0, 1), "drops_coordinate", center=0.5, bounds=(0, 1)).to(
device=device, dtype=dtype
)
self.number_of_drops_sampler = UniformDistribution(number_of_drops[0], number_of_drops[1], validate_args=False)
@@ -69,8 +69,8 @@ class RainGenerator(RandomGeneratorBase):
same_on_batch=same_on_batch,
).to(device=_device)
return {
- 'number_of_drops_factor': number_of_drops_factor,
- 'coordinates_factor': coordinates_factor,
- 'drop_height_factor': drop_height_factor,
- 'drop_width_factor': drop_width_factor,
+ "number_of_drops_factor": number_of_drops_factor,
+ "coordinates_factor": coordinates_factor,
+ "drop_height_factor": drop_height_factor,
+ "drop_width_factor": drop_width_factor,
}
diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
index 16c91b62f..8c74dc70c 100644
--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py
+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
@@ -53,8 +53,8 @@ class RectangleEraseGenerator(RandomGeneratorBase):
if not (isinstance(self.value, (int, float)) and self.value >= 0 and self.value <= 1):
raise AssertionError(f"'value' must be a number between 0 - 1. Got {self.value}.")
- _joint_range_check(scale, 'scale', bounds=(0, float('inf')))
- _joint_range_check(ratio, 'ratio', bounds=(0, float('inf')))
+ _joint_range_check(scale, "scale", bounds=(0, float("inf")))
+ _joint_range_check(ratio, "ratio", bounds=(0, float("inf")))
self.scale_sampler = UniformDistribution(scale[0], scale[1], validate_args=False)
diff --git a/kornia/augmentation/random_generator/_2d/shear.py b/kornia/augmentation/random_generator/_2d/shear.py
index be2fe7b16..a26144d28 100644
--- a/kornia/augmentation/random_generator/_2d/shear.py
+++ b/kornia/augmentation/random_generator/_2d/shear.py
@@ -48,11 +48,11 @@ class ShearGenerator(RandomGeneratorBase):
else:
_shear = stack(
[
- _range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360)),
+ _range_bound(shear if shear.dim() == 0 else shear[:2], "shear-x", 0, (-360, 360)),
(
tensor([0, 0], device=device, dtype=dtype)
if shear.dim() == 0 or len(shear) == 2
- else _range_bound(shear[2:], 'shear-y', 0, (-360, 360))
+ else _range_bound(shear[2:], "shear-y", 0, (-360, 360))
),
]
)
diff --git a/kornia/augmentation/random_generator/_2d/translate.py b/kornia/augmentation/random_generator/_2d/translate.py
index 08a6f03d1..0cee8306f 100644
--- a/kornia/augmentation/random_generator/_2d/translate.py
+++ b/kornia/augmentation/random_generator/_2d/translate.py
@@ -47,7 +47,7 @@ class TranslateGenerator(RandomGeneratorBase):
self.translate_y_sampler = None
if self.translate_x is not None:
- _translate_x = _range_bound(self.translate_x, 'translate_x', bounds=(-1, 1), check='joint').to(
+ _translate_x = _range_bound(self.translate_x, "translate_x", bounds=(-1, 1), check="joint").to(
device=device, dtype=dtype
)
@@ -56,7 +56,7 @@ class TranslateGenerator(RandomGeneratorBase):
)
if self.translate_y is not None:
- _translate_y = _range_bound(self.translate_y, 'translate_y', bounds=(-1, 1), check='joint').to(
+ _translate_y = _range_bound(self.translate_y, "translate_y", bounds=(-1, 1), check="joint").to(
device=device, dtype=dtype
)
diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.py
index 757652471..f8a87acee 100644
--- a/kornia/augmentation/random_generator/_3d/affine.py
+++ b/kornia/augmentation/random_generator/_3d/affine.py
@@ -113,7 +113,7 @@ class AffineGenerator3D(RandomGeneratorBase):
self._translate: Optional[torch.Tensor] = None
if self.translate is not None:
self._translate = torch.as_tensor(self.translate, device=device, dtype=dtype)
- _singular_range_check(self._translate, 'translate', bounds=(0, 1), mode='3d')
+ _singular_range_check(self._translate, "translate", bounds=(0, 1), mode="3d")
# check scale range
self._scale: Optional[torch.Tensor] = None
@@ -125,9 +125,9 @@ class AffineGenerator3D(RandomGeneratorBase):
raise ValueError(f"'scale' shall be either shape (2) or (3, 2). Got {self.scale}.")
else:
self._scale = _scale
- _singular_range_check(self._scale[0], 'scale-x', bounds=(0, float('inf')), mode='2d')
- _singular_range_check(self._scale[1], 'scale-y', bounds=(0, float('inf')), mode='2d')
- _singular_range_check(self._scale[2], 'scale-z', bounds=(0, float('inf')), mode='2d')
+ _singular_range_check(self._scale[0], "scale-x", bounds=(0, float("inf")), mode="2d")
+ _singular_range_check(self._scale[1], "scale-y", bounds=(0, float("inf")), mode="2d")
+ _singular_range_check(self._scale[2], "scale-z", bounds=(0, float("inf")), mode="2d")
self.scale_1_sampler = UniformDistribution(self._scale[0, 0], self._scale[0, 1], validate_args=False)
self.scale_2_sampler = UniformDistribution(self._scale[1, 0], self._scale[1, 1], validate_args=False)
self.scale_3_sampler = UniformDistribution(self._scale[2, 0], self._scale[2, 1], validate_args=False)
@@ -210,14 +210,14 @@ class AffineGenerator3D(RandomGeneratorBase):
sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
return {
- 'translations': torch.as_tensor(translations, device=_device, dtype=_dtype),
- 'center': torch.as_tensor(center, device=_device, dtype=_dtype),
- 'scale': torch.as_tensor(scale, device=_device, dtype=_dtype),
- 'angles': torch.as_tensor(angles, device=_device, dtype=_dtype),
- 'sxy': torch.as_tensor(sxy, device=_device, dtype=_dtype),
- 'sxz': torch.as_tensor(sxz, device=_device, dtype=_dtype),
- 'syx': torch.as_tensor(syx, device=_device, dtype=_dtype),
- 'syz': torch.as_tensor(syz, device=_device, dtype=_dtype),
- 'szx': torch.as_tensor(szx, device=_device, dtype=_dtype),
- 'szy': torch.as_tensor(szy, device=_device, dtype=_dtype),
+ "translations": torch.as_tensor(translations, device=_device, dtype=_dtype),
+ "center": torch.as_tensor(center, device=_device, dtype=_dtype),
+ "scale": torch.as_tensor(scale, device=_device, dtype=_dtype),
+ "angles": torch.as_tensor(angles, device=_device, dtype=_dtype),
+ "sxy": torch.as_tensor(sxy, device=_device, dtype=_dtype),
+ "sxz": torch.as_tensor(sxz, device=_device, dtype=_dtype),
+ "syx": torch.as_tensor(syx, device=_device, dtype=_dtype),
+ "syz": torch.as_tensor(syz, device=_device, dtype=_dtype),
+ "szx": torch.as_tensor(szx, device=_device, dtype=_dtype),
+ "szy": torch.as_tensor(szy, device=_device, dtype=_dtype),
}
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index 4eeb6c41c..5e493a65b 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -142,7 +142,7 @@ def center_crop_generator3d(
height: int,
width: int,
size: Tuple[int, int, int],
- device: Device = torch.device('cpu'),
+ device: Device = torch.device("cpu"),
) -> Dict[str, Tensor]:
r"""Get parameters for ```center_crop3d``` transformation for center crop transform.
diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.py
index a78a23de6..7edb94fbf 100644
--- a/kornia/augmentation/random_generator/_3d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py
@@ -58,7 +58,7 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
angle: Tensor = _tuple_range_reader(self.angle, 3, device=device, dtype=dtype)
- direction = _range_bound(self.direction, 'direction', center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)
+ direction = _range_bound(self.direction, "direction", center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)
if isinstance(self.kernel_size, int):
if not (self.kernel_size >= 3 and self.kernel_size % 2 == 1):
raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {self.kernel_size}.")
@@ -92,7 +92,7 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1
return {
- 'ksize_factor': ksize_factor.to(device=_device, dtype=torch.int32),
- 'angle_factor': angle_factor.to(device=_device, dtype=_dtype),
- 'direction_factor': direction_factor.to(device=_device, dtype=_dtype),
+ "ksize_factor": ksize_factor.to(device=_device, dtype=torch.int32),
+ "angle_factor": angle_factor.to(device=_device, dtype=_dtype),
+ "direction_factor": direction_factor.to(device=_device, dtype=_dtype),
}
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index 3cffbd77e..f3b41336a 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -6,7 +6,7 @@ from torch.distributions import Distribution, Uniform
from kornia.augmentation.utils.helpers import MultiprocessWrapper
from kornia.core import Device, Module, Tensor
-T = TypeVar('T')
+T = TypeVar("T")
class _PostInitInjectionMetaClass(type):
@@ -31,7 +31,7 @@ class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass):
self.set_rng_device_and_dtype()
def set_rng_device_and_dtype(
- self, device: torch.device = torch.device('cpu'), dtype: torch.dtype = torch.float32
+ self, device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.float32
) -> None:
"""Change the random generation device and dtype.
@@ -44,7 +44,7 @@ class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass):
self.dtype = dtype
# TODO: refine the logic with module.to()
- def to(self, *args: Any, **kwargs: Any) -> 'RandomGeneratorBase':
+ def to(self, *args: Any, **kwargs: Any) -> "RandomGeneratorBase":
device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
self.set_rng_device_and_dtype(device=device, dtype=dtype)
return self
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 136cc532e..c2352958b 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -25,7 +25,7 @@ def _validate_input(f: Callable[..., Any]) -> Callable[..., Any]:
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
- _validate_shape(input.shape, required_shapes=('BCHW',))
+ _validate_shape(input.shape, required_shapes=("BCHW",))
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
return f(input, *args, **kwargs)
@@ -50,7 +50,7 @@ def _validate_input3d(f: Callable[..., Any]) -> Callable[..., Any]:
input_shape = len(input.shape)
if input_shape != 5:
- raise AssertionError(f'Expect input of 5 dimensions, got {input_shape} instead')
+ raise AssertionError(f"Expect input of 5 dimensions, got {input_shape} instead")
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
return f(input, *args, **kwargs)
@@ -153,7 +153,7 @@ def _transform_output_shape(output: Tensor, shape: Tuple[int, ...]) -> Tensor:
for dim in range(len(out_tensor.shape) - len(shape)):
if out_tensor.shape[0] != 1:
- raise AssertionError(f'Dimension {dim} of input is expected to be 1, got {out_tensor.shape[0]}')
+ raise AssertionError(f"Dimension {dim} of input is expected to be 1, got {out_tensor.shape[0]}")
out_tensor = out_tensor.squeeze(0)
return out_tensor
@@ -295,7 +295,7 @@ def deepcopy_dict(params: Dict[str, Any]) -> Dict[str, Any]:
def override_parameters(
params: Dict[str, Any],
params_override: Optional[Dict[str, Any]] = None,
- if_none_exist: str = 'ignore',
+ if_none_exist: str = "ignore",
in_place: bool = False,
) -> Dict[str, Any]:
"""Override params dict w.r.t params_override.
@@ -314,9 +314,9 @@ def override_parameters(
for k, v in params_override.items():
if k in params_override:
out[k] = v
- elif if_none_exist == 'ignore':
+ elif if_none_exist == "ignore":
pass
- elif if_none_exist == 'raise':
+ elif if_none_exist == "raise":
raise RuntimeError(f"Param `{k}` not existed in `{params_override}`.")
else:
raise ValueError(f"`{if_none_exist}` is not a valid option.")
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 78e825141..ec32af77a 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -17,9 +17,9 @@ def _range_bound(
factor: Union[Tensor, float, Tuple[float, float], List[float]],
name: str,
center: Optional[float] = 0.0,
- bounds: Optional[Tuple[float, float]] = (0, float('inf')),
- check: Optional[str] = 'joint',
- device: torch.device = torch.device('cpu'),
+ bounds: Optional[Tuple[float, float]] = (0, float("inf")),
+ check: Optional[str] = "joint",
+ device: torch.device = torch.device("cpu"),
dtype: torch.dtype = torch.get_default_dtype(),
) -> Tensor:
r"""Check inputs and compute the corresponding factor bounds."""
@@ -41,9 +41,9 @@ def _range_bound(
factor_bound = as_tensor(factor, device=device, dtype=dtype)
if check is not None:
- if check == 'joint':
+ if check == "joint":
_joint_range_check(factor_bound, name, bounds)
- elif check == 'singular':
+ elif check == "singular":
_singular_range_check(factor_bound, name, bounds)
else:
raise NotImplementedError(f"methods '{check}' not implemented.")
@@ -54,7 +54,7 @@ def _range_bound(
def _joint_range_check(ranged_factor: Tensor, name: str, bounds: Optional[Tuple[float, float]] = None) -> None:
"""Check if bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1]"""
if bounds is None:
- bounds = (float('-inf'), float('inf'))
+ bounds = (float("-inf"), float("inf"))
if ranged_factor.dim() == 1 and len(ranged_factor) == 2:
if not bounds[0] <= ranged_factor[0] or not bounds[1] >= ranged_factor[1]:
raise ValueError(f"{name} out of bounds. Expected inside {bounds}, got {ranged_factor}.")
@@ -70,12 +70,12 @@ def _singular_range_check(
name: str,
bounds: Optional[Tuple[float, float]] = None,
skip_none: bool = False,
- mode: str = '2d',
+ mode: str = "2d",
) -> None:
"""Check if bounds[0] <= ranged_factor[0] <= bounds[1] and bounds[0] <= ranged_factor[1] <= bounds[1]"""
- if mode == '2d':
+ if mode == "2d":
dim_size = 2
- elif mode == '3d':
+ elif mode == "3d":
dim_size = 3
else:
raise ValueError(f"'mode' shall be either 2d or 3d. Got {mode}")
@@ -83,7 +83,7 @@ def _singular_range_check(
if skip_none and ranged_factor is None:
return
if bounds is None:
- bounds = (float('-inf'), float('inf'))
+ bounds = (float("-inf"), float("inf"))
if ranged_factor.dim() == 1 and len(ranged_factor) == dim_size:
for f in ranged_factor:
if not bounds[0] <= f <= bounds[1]:
diff --git a/kornia/color/colormap.py b/kornia/color/colormap.py
index 676ac30cb..16b29a306 100644
--- a/kornia/color/colormap.py
+++ b/kornia/color/colormap.py
@@ -18,6 +18,7 @@ def _list_color_to_tensor(
class ColorMap(ABC):
r"""Abstract class to represents a color map."""
+
colors: Tensor
def __init__(
@@ -33,7 +34,7 @@ class ColorMap(ABC):
self.colors = interpolate(
_list_color_to_tensor(base_colormap, dtype=self._dtype, device=self._device)[None, ...],
size=num_colors,
- mode='linear',
+ mode="linear",
)[0, ...]
def __len__(self) -> int:
diff --git a/kornia/color/raw.py b/kornia/color/raw.py
index 534d65eaf..7785cf926 100644
--- a/kornia/color/raw.py
+++ b/kornia/color/raw.py
@@ -120,17 +120,17 @@ def raw_to_rgb(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
# evenly spaced between them while the B/R samples will be missing in the corners were they are assumed to exist
# Further we need to do align_corners to start the interpolation from the middle of the samples in the corners, that
# way we get to keep the known blue samples across the whole image
- rpadded = torch.nn.functional.pad(r, list(rpad), 'replicate')
- bpadded = torch.nn.functional.pad(b, list(bpad), 'replicate')
+ rpadded = torch.nn.functional.pad(r, list(rpad), "replicate")
+ bpadded = torch.nn.functional.pad(b, list(bpad), "replicate")
# use explicit padding instead of conv2d padding to be able to use reflect which mirror the correct colors
# for a 2x2 bayer filter
- gpadded = torch.nn.functional.pad(image, [1, 1, 1, 1], 'reflect')
+ gpadded = torch.nn.functional.pad(image, [1, 1, 1, 1], "reflect")
r_up = torch.nn.functional.interpolate(
- rpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1), mode='bilinear', align_corners=True
+ rpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1), mode="bilinear", align_corners=True
)
b_up = torch.nn.functional.interpolate(
- bpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1), mode='bilinear', align_corners=True
+ bpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1), mode="bilinear", align_corners=True
)
# remove the extra padding
diff --git a/kornia/color/sepia.py b/kornia/color/sepia.py
index 59dc2ad6e..ad9967f61 100644
--- a/kornia/color/sepia.py
+++ b/kornia/color/sepia.py
@@ -73,7 +73,7 @@ class Sepia(Module):
super().__init__()
def __repr__(self) -> str:
- return self.__class__.__name__ + f'(rescale={self.rescale}, eps={self.eps})'
+ return self.__class__.__name__ + f"(rescale={self.rescale}, eps={self.eps})"
def forward(self, input: Tensor) -> Tensor:
return sepia_from_rgb(input, rescale=self.rescale, eps=self.eps)
diff --git a/kornia/constants.py b/kornia/constants.py
index d46853074..24d0f644b 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -5,12 +5,12 @@ import torch
from kornia.core import Tensor
-__all__ = ['pi', 'DType', 'Resample', 'BorderType', 'SamplePadding', 'TKEnum']
+__all__ = ["pi", "DType", "Resample", "BorderType", "SamplePadding", "TKEnum"]
pi = torch.tensor(3.14159265358979323846)
-T = TypeVar('T', bound=Enum)
+T = TypeVar("T", bound=Enum)
TKEnum = Union[str, int, T]
@@ -28,7 +28,7 @@ class _KORNIA_EnumMeta(EnumMeta):
return any(val == other for val in self)
def __repr__(self) -> str:
- return ' | '.join(f"{self.__name__}.{val.name}" for val in self)
+ return " | ".join(f"{self.__name__}.{val.name}" for val in self)
def _get(cls: Type[T], value: TKEnum[T]) -> T:
@@ -42,7 +42,7 @@ def _get(cls: Type[T], value: TKEnum[T]) -> T:
return value
raise TypeError(
- f'The `.get` method from `{cls}` expects a value with type `str`, `int` or `{cls}`. Gotcha {type(value)}'
+ f"The `.get` method from `{cls}` expects a value with type `str`, `int` or `{cls}`. Gotcha {type(value)}"
)
@@ -52,7 +52,7 @@ class Resample(Enum, metaclass=_KORNIA_EnumMeta):
BICUBIC = 2
@classmethod
- def get(cls, value: TKEnum['Resample']) -> 'Resample':
+ def get(cls, value: TKEnum["Resample"]) -> "Resample":
return _get(cls, value)
@@ -63,7 +63,7 @@ class BorderType(Enum, metaclass=_KORNIA_EnumMeta):
CIRCULAR = 3
@classmethod
- def get(cls, value: TKEnum['BorderType']) -> 'BorderType':
+ def get(cls, value: TKEnum["BorderType"]) -> "BorderType":
return _get(cls, value)
@@ -73,7 +73,7 @@ class SamplePadding(Enum, metaclass=_KORNIA_EnumMeta):
REFLECTION = 2
@classmethod
- def get(cls, value: TKEnum['SamplePadding']) -> 'SamplePadding':
+ def get(cls, value: TKEnum["SamplePadding"]) -> "SamplePadding":
return _get(cls, value)
@@ -84,7 +84,7 @@ class DType(Enum, metaclass=_KORNIA_EnumMeta):
FLOAT64 = 3
@classmethod
- def get(cls, value: Union[str, int, torch.dtype, Tensor, 'DType']) -> 'DType':
+ def get(cls, value: Union[str, int, torch.dtype, Tensor, "DType"]) -> "DType":
if isinstance(value, torch.dtype):
return cls[str(value).upper()[6:]]
@@ -103,7 +103,7 @@ class DType(Enum, metaclass=_KORNIA_EnumMeta):
raise TypeError(f"Invalid identifier {value} with type {type(value)}.")
@classmethod
- def to_torch(cls, value: TKEnum['DType']) -> torch.dtype:
+ def to_torch(cls, value: TKEnum["DType"]) -> torch.dtype:
data = cls.get(value=value)
if data == DType.INT64:
@@ -133,5 +133,5 @@ class DataKey(Enum, metaclass=_KORNIA_EnumMeta):
CLASS = 6
@classmethod
- def get(cls, value: TKEnum['DataKey']) -> 'DataKey':
+ def get(cls, value: TKEnum["DataKey"]) -> "DataKey":
return _get(cls, value)
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index b16b2a20f..1d384f546 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -1,94 +1,94 @@
-import math
-
-import torch
-from torch import nn
-
-from kornia.filters import filter2d
-from kornia.utils import create_meshgrid
-
-
-def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.35) -> torch.Tensor:
- r"""Approximates the Manhattan distance transform of images using cascaded convolution operations.
-
- The value at each pixel in the output represents the distance to the nearest non-zero pixel in the image image.
- It uses the method described in :cite:`pham2021dtlayer`.
- The transformation is applied independently across the channel dimension of the images.
-
- Args:
- image: Image with shape :math:`(B,C,H,W)`.
- kernel_size: size of the convolution kernel.
- h: value that influence the approximation of the min function.
-
- Returns:
- tensor with shape :math:`(B,C,H,W)`.
-
- Example:
- >>> tensor = torch.zeros(1, 1, 5, 5)
- >>> tensor[:,:, 1, 2] = 1
- >>> dt = kornia.contrib.distance_transform(tensor)
- """
- if not isinstance(image, torch.Tensor):
- raise TypeError(f"image type is not a torch.Tensor. Got {type(image)}")
-
- if not len(image.shape) == 4:
- raise ValueError(f"Invalid image shape, we expect BxCxHxW. Got: {image.shape}")
-
- if kernel_size % 2 == 0:
- raise ValueError("Kernel size must be an odd number.")
-
- # n_iters is set such that the DT will be able to propagate from any corner of the image to its far,
- # diagonally opposite corner
- n_iters: int = math.ceil(max(image.shape[2], image.shape[3]) / math.floor(kernel_size / 2))
- grid = create_meshgrid(
- kernel_size, kernel_size, normalized_coordinates=False, device=image.device, dtype=image.dtype
- )
-
- grid -= math.floor(kernel_size / 2)
- kernel = torch.hypot(grid[0, :, :, 0], grid[0, :, :, 1])
- kernel = torch.exp(kernel / -h).unsqueeze(0)
-
- out = torch.zeros_like(image)
-
- # It is possible to avoid cloning the image if boundary = image, but this would require modifying the image tensor.
- boundary = image.clone()
- signal_ones = torch.ones_like(boundary)
-
- for i in range(n_iters):
- cdt = filter2d(boundary, kernel, border_type='replicate')
- cdt = -h * torch.log(cdt)
-
- # We are calculating log(0) above.
- cdt = torch.nan_to_num(cdt, posinf=0.0)
-
- mask = torch.where(cdt > 0, 1.0, 0.0)
- if mask.sum() == 0:
- break
-
- offset: int = i * kernel_size // 2
- out += (offset + cdt) * mask
- boundary = torch.where(mask == 1, signal_ones, boundary)
-
- return out
-
-
-class DistanceTransform(nn.Module):
- r"""Module that approximates the Manhattan (city block) distance transform of images using convolutions.
-
- Args:
- kernel_size: size of the convolution kernel.
- h: value that influence the approximation of the min function.
- """
-
- def __init__(self, kernel_size: int = 3, h: float = 0.35) -> None:
- super().__init__()
- self.kernel_size = kernel_size
- self.h = h
-
- def forward(self, image: torch.Tensor) -> torch.Tensor:
- # If images have multiple channels, view the channels in the batch dimension to match kernel shape.
- if image.shape[1] > 1:
- image_in = image.view(-1, 1, image.shape[-2], image.shape[-1])
- else:
- image_in = image
-
- return distance_transform(image_in, self.kernel_size, self.h).view_as(image)
+import math
+
+import torch
+from torch import nn
+
+from kornia.filters import filter2d
+from kornia.utils import create_meshgrid
+
+
+def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.35) -> torch.Tensor:
+ r"""Approximates the Manhattan distance transform of images using cascaded convolution operations.
+
+ The value at each pixel in the output represents the distance to the nearest non-zero pixel in the image image.
+ It uses the method described in :cite:`pham2021dtlayer`.
+ The transformation is applied independently across the channel dimension of the images.
+
+ Args:
+ image: Image with shape :math:`(B,C,H,W)`.
+ kernel_size: size of the convolution kernel.
+ h: value that influence the approximation of the min function.
+
+ Returns:
+ tensor with shape :math:`(B,C,H,W)`.
+
+ Example:
+ >>> tensor = torch.zeros(1, 1, 5, 5)
+ >>> tensor[:,:, 1, 2] = 1
+ >>> dt = kornia.contrib.distance_transform(tensor)
+ """
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"image type is not a torch.Tensor. Got {type(image)}")
+
+ if not len(image.shape) == 4:
+ raise ValueError(f"Invalid image shape, we expect BxCxHxW. Got: {image.shape}")
+
+ if kernel_size % 2 == 0:
+ raise ValueError("Kernel size must be an odd number.")
+
+ # n_iters is set such that the DT will be able to propagate from any corner of the image to its far,
+ # diagonally opposite corner
+ n_iters: int = math.ceil(max(image.shape[2], image.shape[3]) / math.floor(kernel_size / 2))
+ grid = create_meshgrid(
+ kernel_size, kernel_size, normalized_coordinates=False, device=image.device, dtype=image.dtype
+ )
+
+ grid -= math.floor(kernel_size / 2)
+ kernel = torch.hypot(grid[0, :, :, 0], grid[0, :, :, 1])
+ kernel = torch.exp(kernel / -h).unsqueeze(0)
+
+ out = torch.zeros_like(image)
+
+ # It is possible to avoid cloning the image if boundary = image, but this would require modifying the image tensor.
+ boundary = image.clone()
+ signal_ones = torch.ones_like(boundary)
+
+ for i in range(n_iters):
+ cdt = filter2d(boundary, kernel, border_type="replicate")
+ cdt = -h * torch.log(cdt)
+
+ # We are calculating log(0) above.
+ cdt = torch.nan_to_num(cdt, posinf=0.0)
+
+ mask = torch.where(cdt > 0, 1.0, 0.0)
+ if mask.sum() == 0:
+ break
+
+ offset: int = i * kernel_size // 2
+ out += (offset + cdt) * mask
+ boundary = torch.where(mask == 1, signal_ones, boundary)
+
+ return out
+
+
+class DistanceTransform(nn.Module):
+ r"""Module that approximates the Manhattan (city block) distance transform of images using convolutions.
+
+ Args:
+ kernel_size: size of the convolution kernel.
+ h: value that influence the approximation of the min function.
+ """
+
+ def __init__(self, kernel_size: int = 3, h: float = 0.35) -> None:
+ super().__init__()
+ self.kernel_size = kernel_size
+ self.h = h
+
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
+ # If images have multiple channels, view the channels in the batch dimension to match kernel shape.
+ if image.shape[1] > 1:
+ image_in = image.view(-1, 1, image.shape[-2], image.shape[-1])
+ else:
+ image_in = image
+
+ return distance_transform(image_in, self.kernel_size, self.h).view_as(image)
diff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.py
index 104cbf47e..233e24b85 100644
--- a/kornia/contrib/face_detection.py
+++ b/kornia/contrib/face_detection.py
@@ -21,6 +21,7 @@ class FaceKeypoint(Enum):
The left/right convention is based on the screen viewer.
"""
+
EYE_LEFT = 0
EYE_RIGHT = 1
NOSE = 2
@@ -154,24 +155,24 @@ class FaceDetector(nn.Module):
self.nms_threshold = nms_threshold
self.keep_top_k = keep_top_k
self.config = {
- 'name': 'YuFaceDetectNet',
- 'min_sizes': [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]],
- 'steps': [8, 16, 32, 64],
- 'variance': [0.1, 0.2],
- 'clip': False,
+ "name": "YuFaceDetectNet",
+ "min_sizes": [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]],
+ "steps": [8, 16, 32, 64],
+ "variance": [0.1, 0.2],
+ "clip": False,
}
self.min_sizes = [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]]
self.steps = [8, 16, 32, 64]
self.variance = [0.1, 0.2]
self.clip = False
- self.model = YuFaceDetectNet('test', pretrained=True)
+ self.model = YuFaceDetectNet("test", pretrained=True)
self.nms = nms_kornia
def preprocess(self, image: torch.Tensor) -> torch.Tensor:
return image
def postprocess(self, data: Dict[str, torch.Tensor], height: int, width: int) -> List[torch.Tensor]:
- loc, conf, iou = data['loc'], data['conf'], data['iou']
+ loc, conf, iou = data["loc"], data["conf"], data["iou"]
scale = torch.tensor(
[width, height, width, height, width, height, width, height, width, height, width, height, width, height],
@@ -274,7 +275,7 @@ class YuFaceDetectNet(nn.Module):
Conv4layerBlock(64, 3 * (14 + 2 + 1), False),
)
- if self.phase == 'train':
+ if self.phase == "train":
for m in self.modules():
if isinstance(m, nn.Conv2d):
if m.bias is not None:
@@ -374,7 +375,7 @@ class _PriorBox:
self.clip = clip
self.image_size = image_size
- self.device: torch.device = torch.device('cpu')
+ self.device: torch.device = torch.device("cpu")
self.dtype: torch.dtype = torch.float32
for i in range(4):
@@ -389,7 +390,7 @@ class _PriorBox:
self.feature_maps = [self.feature_map_3th, self.feature_map_4th, self.feature_map_5th, self.feature_map_6th]
- def to(self, device: torch.device, dtype: torch.dtype) -> '_PriorBox':
+ def to(self, device: torch.device, dtype: torch.dtype) -> "_PriorBox":
self.device = device
self.dtype = dtype
return self
diff --git a/kornia/contrib/image_prompter.py b/kornia/contrib/image_prompter.py
index 678fd8cd4..f52200f50 100644
--- a/kornia/contrib/image_prompter.py
+++ b/kornia/contrib/image_prompter.py
@@ -54,7 +54,7 @@ class ImagePrompter:
def __init__(
self,
config: SamConfig = SamConfig(
- model_type='vit_h', checkpoint='https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth'
+ model_type="vit_h", checkpoint="https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth"
),
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
@@ -123,13 +123,13 @@ class ImagePrompter:
pixel values with the mean and std defined in its initialization. Expected to be into a float32
dtype. Shape :math:`(3, H, W)`.
"""
- KORNIA_CHECK_SHAPE(image, ['3', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(image, ["3", "H", "W"])
self.reset_image()
self._original_image_size = (image.shape[-2], image.shape[-1])
- image = self.transforms(image, data_keys=['input'])
+ image = self.transforms(image, data_keys=["input"])
self._tfs_params = self.transforms._params
self._input_image_size = (image.shape[-2], image.shape[-1])
@@ -142,9 +142,9 @@ class ImagePrompter:
def _valid_keypoints(self, keypoints: Keypoints | Tensor, labels: Tensor) -> Keypoints:
"""Validate the keypoints shape and ensure to be a Keypoints."""
- KORNIA_CHECK_SHAPE(keypoints.data, ['K', 'N', '2'])
- KORNIA_CHECK_SHAPE(labels.data, ['K', 'N'])
- KORNIA_CHECK(keypoints.shape[0] == labels.shape[0], 'The keypoints and labels should have the same batch size')
+ KORNIA_CHECK_SHAPE(keypoints.data, ["K", "N", "2"])
+ KORNIA_CHECK_SHAPE(labels.data, ["K", "N"])
+ KORNIA_CHECK(keypoints.shape[0] == labels.shape[0], "The keypoints and labels should have the same batch size")
if isinstance(keypoints, Tensor):
keypoints = Keypoints.from_tensor(keypoints)
@@ -154,19 +154,19 @@ class ImagePrompter:
def _valid_boxes(self, boxes: Boxes | Tensor) -> Boxes:
"""Validate the boxes shape and ensure to be a Boxes into xyxy mode."""
if isinstance(boxes, Tensor):
- KORNIA_CHECK_SHAPE(boxes.data, ['K', '4'])
- boxes = Boxes(boxes, mode='xyxy')
+ KORNIA_CHECK_SHAPE(boxes.data, ["K", "4"])
+ boxes = Boxes(boxes, mode="xyxy")
- if boxes.mode == 'xyxy':
+ if boxes.mode == "xyxy":
boxes_xyxy = boxes
else:
- boxes_xyxy = Boxes(boxes.to_tensor(mode='xyxy'), mode='xyxy')
+ boxes_xyxy = Boxes(boxes.to_tensor(mode="xyxy"), mode="xyxy")
return boxes_xyxy
def _valid_masks(self, masks: Tensor) -> Tensor:
"""Validate the input masks shape."""
- KORNIA_CHECK_SHAPE(masks, ['K', '1', '256', '256'])
+ KORNIA_CHECK_SHAPE(masks, ["K", "1", "256", "256"])
return masks
def _transform_prompts(
@@ -188,12 +188,12 @@ class ImagePrompter:
if isinstance(keypoints, (Keypoints, Tensor)) and isinstance(keypoints_labels, Tensor):
keypoints = self._valid_keypoints(keypoints, keypoints_labels)
- data_keys.append('keypoints')
+ data_keys.append("keypoints")
to_transform.append(keypoints)
if isinstance(boxes, (Boxes, Tensor)):
self._valid_boxes(boxes)
- data_keys.append('bbox_xyxy')
+ data_keys.append("bbox_xyxy")
to_transform.append(boxes)
if isinstance(masks, Tensor):
@@ -201,15 +201,15 @@ class ImagePrompter:
data = self._transform_prompts(*to_transform, data_keys=data_keys)
- if 'keypoints' in data and isinstance(data['keypoints'], Keypoints):
- kpts_tensor = data['keypoints'].to_tensor()
+ if "keypoints" in data and isinstance(data["keypoints"], Keypoints):
+ kpts_tensor = data["keypoints"].to_tensor()
if KORNIA_CHECK_IS_TENSOR(kpts_tensor) and KORNIA_CHECK_IS_TENSOR(keypoints_labels):
points = (kpts_tensor[None, ...], keypoints_labels)
else:
points = None
- if 'bbox_xyxy' in data and isinstance(data['bbox_xyxy'], Boxes):
- _bbox = data['bbox_xyxy'].to_tensor(mode='xyxy')
+ if "bbox_xyxy" in data and isinstance(data["bbox_xyxy"], Boxes):
+ _bbox = data["bbox_xyxy"].to_tensor(mode="xyxy")
if KORNIA_CHECK_IS_TENSOR(_bbox):
bbox = _bbox
else:
@@ -249,7 +249,7 @@ class ImagePrompter:
A prediction with the logits and scores (IoU of each predicted mask)
"""
- KORNIA_CHECK(self.is_image_set, 'An image must be set with `self.set_image(...)` before `predict` be called!')
+ KORNIA_CHECK(self.is_image_set, "An image must be set with `self.set_image(...)` before `predict` be called!")
prompts = self.preprocess_prompts(keypoints, keypoints_labels, boxes, masks)
@@ -285,7 +285,7 @@ class ImagePrompter:
self._input_image_size = None
self._input_encoder_size = None
- if hasattr(self, 'image_embeddings'):
+ if hasattr(self, "image_embeddings"):
del self.image_embeddings
self.image_embeddings = None
@@ -296,7 +296,7 @@ class ImagePrompter:
*,
fullgraph: bool = False,
dynamic: bool = False,
- backend: str = 'inductor',
+ backend: str = "inductor",
mode: Optional[str] = None,
options: dict[Any, Any] = {},
disable: bool = False,
diff --git a/kornia/contrib/image_stitching.py b/kornia/contrib/image_stitching.py
index ab9a5ac31..edfa2dbbd 100644
--- a/kornia/contrib/image_stitching.py
+++ b/kornia/contrib/image_stitching.py
@@ -33,15 +33,15 @@ class ImageStitcher(Module):
plt.imshow(K.tensor_to_image(out))
"""
- def __init__(self, matcher: Module, estimator: str = 'ransac', blending_method: str = "naive") -> None:
+ def __init__(self, matcher: Module, estimator: str = "ransac", blending_method: str = "naive") -> None:
super().__init__()
self.matcher = matcher
self.estimator = estimator
self.blending_method = blending_method
- if estimator not in ['ransac', 'vanilla']:
+ if estimator not in ["ransac", "vanilla"]:
raise NotImplementedError(f"Unsupported estimator {estimator}. Use `ransac` or `vanilla` instead.")
if estimator == "ransac":
- self.ransac = RANSAC('homography')
+ self.ransac = RANSAC("homography")
def _estimate_homography(self, keypoints1: Tensor, keypoints2: Tensor) -> Tensor:
"""Estimate homography by the matched keypoints.
@@ -63,7 +63,7 @@ class ImageStitcher(Module):
def estimate_transform(self, *args: Tensor, **kwargs: Tensor) -> Tensor:
"""Compute the corresponding homography."""
- kp1, kp2, idx = kwargs['keypoints0'], kwargs['keypoints1'], kwargs['batch_indexes']
+ kp1, kp2, idx = kwargs["keypoints0"], kwargs["keypoints1"], kwargs["batch_indexes"]
homos = [self._estimate_homography(kp1[idx == i], kp2[idx == i]) for i in range(len(idx.unique()))]
if len(homos) == 0:
@@ -124,7 +124,7 @@ class ImageStitcher(Module):
if mask_right is None:
mask_right = torch.ones_like(images_right)
# 'nearest' to ensure no floating points in the mask
- src_mask = warp_perspective(mask_right, homo, out_shape, mode='nearest')
+ src_mask = warp_perspective(mask_right, homo, out_shape, mode="nearest")
dst_mask = concatenate([mask_left, zeros_like(mask_right)], -1)
return self.blend_image(src_img, dst_img, src_mask), (dst_mask + src_mask).bool().to(src_mask.dtype)
diff --git a/kornia/contrib/models/base.py b/kornia/contrib/models/base.py
index 9a62c3cff..366466340 100644
--- a/kornia/contrib/models/base.py
+++ b/kornia/contrib/models/base.py
@@ -8,7 +8,7 @@ import torch
from kornia.core import Module
-ModelConfig = TypeVar('ModelConfig')
+ModelConfig = TypeVar("ModelConfig")
class ModelBase(ABC, Module, Generic[ModelConfig]):
@@ -45,7 +45,7 @@ class ModelBase(ABC, Module, Generic[ModelConfig]):
*,
fullgraph: bool = False,
dynamic: bool = False,
- backend: str = 'inductor',
+ backend: str = "inductor",
mode: Optional[str] = None,
options: dict[Any, Any] = {},
disable: bool = False,
diff --git a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
index 1ff571eeb..6cf2fce06 100644
--- a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
+++ b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
@@ -57,7 +57,7 @@ def _deformable_attention_kernel(
sampling_grid_l_ = sampling_grids[:, :, :, level].permute(0, 2, 1, 3, 4).flatten(0, 1)
# N_*M_, D_, Lq_, P_
sampling_value_l_ = torch.nn.functional.grid_sample(
- value_l_, sampling_grid_l_, mode='bilinear', padding_mode='zeros', align_corners=False
+ value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False
)
sampling_value_list.append(sampling_value_l_)
diff --git a/kornia/contrib/models/sam/model.py b/kornia/contrib/models/sam/model.py
index acb670124..b6c225500 100644
--- a/kornia/contrib/models/sam/model.py
+++ b/kornia/contrib/models/sam/model.py
@@ -105,10 +105,10 @@ class Sam(ModelBase[SamConfig]):
model_type = SamModelType(model_type)
elif isinstance(model_type, str):
_map_sam_type = {
- 'vit_h': SamModelType.vit_h,
- 'vit_l': SamModelType.vit_l,
- 'vit_b': SamModelType.vit_b,
- 'mobile_sam': SamModelType.mobile_sam,
+ "vit_h": SamModelType.vit_h,
+ "vit_l": SamModelType.vit_l,
+ "vit_b": SamModelType.vit_b,
+ "mobile_sam": SamModelType.mobile_sam,
}
model_type = _map_sam_type[model_type]
@@ -173,7 +173,7 @@ class Sam(ModelBase[SamConfig]):
)
else:
- raise NotImplementedError('Unexpected config. The model_type should be provide or the encoder configs.')
+ raise NotImplementedError("Unexpected config. The model_type should be provide or the encoder configs.")
checkpoint = config.checkpoint
if config.pretrained:
@@ -236,10 +236,10 @@ class Sam(ModelBase[SamConfig]):
- scores: The model's predictions of mask quality (iou prediction), in shape BxC.
"""
- KORNIA_CHECK_SHAPE(images, ['B', '3', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(images, ["B", "3", "H", "W"])
KORNIA_CHECK(
images.shape[0] == len(batched_prompts),
- 'The number of images (`B`) should match with the length of prompts!',
+ "The number of images (`B`) should match with the length of prompts!",
)
image_embeddings = self.image_encoder(images)
diff --git a/kornia/contrib/models/structures.py b/kornia/contrib/models/structures.py
index e7665c569..e03c7c9f2 100644
--- a/kornia/contrib/models/structures.py
+++ b/kornia/contrib/models/structures.py
@@ -60,10 +60,10 @@ class SegmentationResults:
x = self.logits
if isinstance(image_size_encoder, tuple):
- x = resize(x, size=image_size_encoder, interpolation='bilinear', align_corners=False, antialias=False)
+ x = resize(x, size=image_size_encoder, interpolation="bilinear", align_corners=False, antialias=False)
x = x[..., : input_size[0], : input_size[1]]
- x = resize(x, size=original_size, interpolation='bilinear', align_corners=False, antialias=False)
+ x = resize(x, size=original_size, interpolation="bilinear", align_corners=False, antialias=False)
self._original_res_logits = x
return self._original_res_logits
@@ -95,7 +95,7 @@ class Prompts:
def __post_init__(self) -> None:
if isinstance(self.keypoints, Tensor) and isinstance(self.boxes, Tensor):
- KORNIA_CHECK(self.keypoints.shape[0] == self.boxes.shape[0], 'The prompts should have the same batch size!')
+ KORNIA_CHECK(self.keypoints.shape[0] == self.boxes.shape[0], "The prompts should have the same batch size!")
@property
def keypoints(self) -> Optional[Tensor]:
diff --git a/kornia/contrib/models/tiny_vit.py b/kornia/contrib/models/tiny_vit.py
index d2d51a078..6c493ed9b 100644
--- a/kornia/contrib/models/tiny_vit.py
+++ b/kornia/contrib/models/tiny_vit.py
@@ -169,7 +169,7 @@ class Attention(Module):
indices, attn_offset_size = self.build_attention_bias(resolution)
self.attention_biases = nn.Parameter(torch.zeros(num_heads, attn_offset_size))
- self.register_buffer('attention_bias_idxs', indices, persistent=False)
+ self.register_buffer("attention_bias_idxs", indices, persistent=False)
self.attention_bias_idxs: Tensor
self.ab: Optional[Tensor] = None
@@ -470,7 +470,7 @@ def _load_pretrained(model: TinyViT, url: str) -> TinyViT:
S1 = int(L1**0.5)
S2 = int(L2**0.5)
attention_biases = state_dict[k].view(1, n_heads1, S1, S1)
- attention_biases = F.interpolate(attention_biases, size=(S2, S2), mode='bicubic')
+ attention_biases = F.interpolate(attention_biases, size=(S2, S2), mode="bicubic")
state_dict[k] = attention_biases.view(n_heads2, L2)
if state_dict["head.weight"].shape[0] != model.head.out_features:
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index 70e6ddb2a..ad1849378 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -165,7 +165,7 @@ class ObjectDetector(Module):
*,
fullgraph: bool = False,
dynamic: bool = False,
- backend: str = 'inductor',
+ backend: str = "inductor",
mode: Optional[str] = None,
options: Optional[dict[str, str | int | bool]] = None,
disable: bool = False,
diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.py
index c2c5f142c..11fb0eedf 100644
--- a/kornia/contrib/visual_prompter.py
+++ b/kornia/contrib/visual_prompter.py
@@ -52,7 +52,7 @@ class VisualPrompter:
def __init__(
self,
- config: SamConfig = SamConfig(model_type='vit_h', pretrained=True),
+ config: SamConfig = SamConfig(model_type="vit_h", pretrained=True),
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> None:
@@ -116,13 +116,13 @@ class VisualPrompter:
pixel values with the mean and std defined in its initialization. Expected to be into a float32
dtype. Shape :math:`(3, H, W)`.
"""
- KORNIA_CHECK_SHAPE(image, ['3', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(image, ["3", "H", "W"])
self.reset_image()
self._original_image_size = (image.shape[-2], image.shape[-1])
- image = self.transforms(image, data_keys=['input'])
+ image = self.transforms(image, data_keys=["input"])
self._tfs_params = self.transforms._params
self._input_image_size = (image.shape[-2], image.shape[-1])
@@ -135,9 +135,9 @@ class VisualPrompter:
def _valid_keypoints(self, keypoints: Keypoints | Tensor, labels: Tensor) -> Keypoints:
"""Validate the keypoints shape and ensure to be a Keypoints."""
- KORNIA_CHECK_SHAPE(keypoints.data, ['K', 'N', '2'])
- KORNIA_CHECK_SHAPE(labels.data, ['K', 'N'])
- KORNIA_CHECK(keypoints.shape[0] == labels.shape[0], 'The keypoints and labels should have the same batch size')
+ KORNIA_CHECK_SHAPE(keypoints.data, ["K", "N", "2"])
+ KORNIA_CHECK_SHAPE(labels.data, ["K", "N"])
+ KORNIA_CHECK(keypoints.shape[0] == labels.shape[0], "The keypoints and labels should have the same batch size")
if isinstance(keypoints, Tensor):
keypoints = Keypoints.from_tensor(keypoints)
@@ -147,19 +147,19 @@ class VisualPrompter:
def _valid_boxes(self, boxes: Boxes | Tensor) -> Boxes:
"""Validate the boxes shape and ensure to be a Boxes into xyxy mode."""
if isinstance(boxes, Tensor):
- KORNIA_CHECK_SHAPE(boxes.data, ['K', '4'])
- boxes = Boxes(boxes, mode='xyxy')
+ KORNIA_CHECK_SHAPE(boxes.data, ["K", "4"])
+ boxes = Boxes(boxes, mode="xyxy")
- if boxes.mode == 'xyxy':
+ if boxes.mode == "xyxy":
boxes_xyxy = boxes
else:
- boxes_xyxy = Boxes(boxes.to_tensor(mode='xyxy'), mode='xyxy')
+ boxes_xyxy = Boxes(boxes.to_tensor(mode="xyxy"), mode="xyxy")
return boxes_xyxy
def _valid_masks(self, masks: Tensor) -> Tensor:
"""Validate the input masks shape."""
- KORNIA_CHECK_SHAPE(masks, ['K', '1', '256', '256'])
+ KORNIA_CHECK_SHAPE(masks, ["K", "1", "256", "256"])
return masks
def _transform_prompts(
@@ -185,12 +185,12 @@ class VisualPrompter:
if isinstance(keypoints, (Keypoints, Tensor)) and isinstance(keypoints_labels, Tensor):
keypoints = self._valid_keypoints(keypoints, keypoints_labels)
- data_keys.append('keypoints')
+ data_keys.append("keypoints")
to_transform.append(keypoints)
if isinstance(boxes, (Boxes, Tensor)):
self._valid_boxes(boxes)
- data_keys.append('bbox_xyxy')
+ data_keys.append("bbox_xyxy")
to_transform.append(boxes)
if isinstance(masks, Tensor):
@@ -198,15 +198,15 @@ class VisualPrompter:
data = self._transform_prompts(*to_transform, data_keys=data_keys)
- if 'keypoints' in data and isinstance(data['keypoints'], Keypoints):
- kpts_tensor = data['keypoints'].to_tensor()
+ if "keypoints" in data and isinstance(data["keypoints"], Keypoints):
+ kpts_tensor = data["keypoints"].to_tensor()
if KORNIA_CHECK_IS_TENSOR(kpts_tensor) and KORNIA_CHECK_IS_TENSOR(keypoints_labels):
points = (kpts_tensor, keypoints_labels)
else:
points = None
- if 'bbox_xyxy' in data and isinstance(data['bbox_xyxy'], Boxes):
- _bbox = data['bbox_xyxy'].to_tensor(mode='xyxy')
+ if "bbox_xyxy" in data and isinstance(data["bbox_xyxy"], Boxes):
+ _bbox = data["bbox_xyxy"].to_tensor(mode="xyxy")
if KORNIA_CHECK_IS_TENSOR(_bbox):
bbox = _bbox
else:
@@ -246,7 +246,7 @@ class VisualPrompter:
A prediction with the logits and scores (IoU of each predicted mask)
"""
- KORNIA_CHECK(self.is_image_set, 'An image must be set with `self.set_image(...)` before `predict` be called!')
+ KORNIA_CHECK(self.is_image_set, "An image must be set with `self.set_image(...)` before `predict` be called!")
prompts = self.preprocess_prompts(keypoints, keypoints_labels, boxes, masks)
@@ -282,7 +282,7 @@ class VisualPrompter:
self._input_image_size = None
self._input_encoder_size = None
- if hasattr(self, 'image_embeddings'):
+ if hasattr(self, "image_embeddings"):
del self.image_embeddings
self.image_embeddings = None
@@ -293,7 +293,7 @@ class VisualPrompter:
*,
fullgraph: bool = False,
dynamic: bool = False,
- backend: str = 'inductor',
+ backend: str = "inductor",
mode: Optional[str] = None,
options: dict[Any, Any] = {},
disable: bool = False,
diff --git a/kornia/contrib/vit.py b/kornia/contrib/vit.py
index 69bc06375..d145dab23 100644
--- a/kornia/contrib/vit.py
+++ b/kornia/contrib/vit.py
@@ -69,12 +69,12 @@ class MultiHeadAttention(Module):
q, k, v = qkv[0], qkv[1], qkv[2]
# sum up over the last axis
- att = torch.einsum('bhqd, bhkd -> bhqk', q, k) * self.scale
+ att = torch.einsum("bhqd, bhkd -> bhqk", q, k) * self.scale
att = att.softmax(dim=-1)
att = self.att_drop(att)
# sum up over the third axis
- out = torch.einsum('bhal, bhlv -> bhav ', att, v)
+ out = torch.einsum("bhal, bhlv -> bhav ", att, v)
out = out.permute(0, 2, 1, 3).contiguous().view(B, N, -1)
out = self.projection(out)
out = self.projection_drop(out)
diff --git a/kornia/contrib/vit_mobile.py b/kornia/contrib/vit_mobile.py
index 1e990526a..4c639a345 100644
--- a/kornia/contrib/vit_mobile.py
+++ b/kornia/contrib/vit_mobile.py
@@ -233,18 +233,18 @@ class MobileViT(Module):
"""
def __init__(
- self, mode: str = 'xxs', in_channels: int = 3, patch_size: Tuple[int, int] = (2, 2), dropout: float = 0.0
+ self, mode: str = "xxs", in_channels: int = 3, patch_size: Tuple[int, int] = (2, 2), dropout: float = 0.0
) -> None:
super().__init__()
- if mode == 'xxs':
+ if mode == "xxs":
expansion = 2
dims = [64, 80, 96]
channels = [16, 16, 24, 24, 48, 48, 64, 64, 80, 80, 320]
- elif mode == 'xs':
+ elif mode == "xs":
expansion = 4
dims = [96, 120, 144]
channels = [16, 32, 48, 48, 64, 64, 80, 80, 96, 96, 384]
- elif mode == 's':
+ elif mode == "s":
expansion = 4
dims = [144, 192, 240]
channels = [16, 32, 64, 64, 96, 96, 128, 128, 160, 160, 640]
diff --git a/kornia/core/check.py b/kornia/core/check.py
index 7ead855f5..cf2148fd6 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -51,10 +51,10 @@ def KORNIA_CHECK_SHAPE(x: Tensor, shape: list[str], raises: bool = True) -> bool
>>> KORNIA_CHECK_SHAPE(x, ["2", "3", "H", "W"]) # explicit
True
"""
- if '*' == shape[0]:
+ if "*" == shape[0]:
shape_to_check = shape[1:]
x_shape_to_check = x.shape[-len(shape) + 1 :]
- elif '*' == shape[-1]:
+ elif "*" == shape[-1]:
shape_to_check = shape[:-1]
x_shape_to_check = x.shape[: len(shape) - 1]
else:
@@ -116,7 +116,7 @@ def KORNIA_UNWRAP(maybe_obj: object, typ: Any) -> Any:
return cast(typ, maybe_obj)
-T = TypeVar('T', bound=type)
+T = TypeVar("T", bound=type)
# TODO: fix mypy typeguard issue
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 7e73637b8..a89f0c1b5 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -865,8 +865,8 @@ def _blend_one(input1: Tensor, input2: Tensor, factor: Tensor) -> Tensor:
def _build_lut(histo: Tensor, step: Tensor) -> Tensor:
# Compute the cumulative sum, shifting by step // 2
# and then normalization by step.
- step_trunc = torch.div(step, 2, rounding_mode='trunc')
- lut = torch.div(torch.cumsum(histo, 0) + step_trunc, step, rounding_mode='trunc')
+ step_trunc = torch.div(step, 2, rounding_mode="trunc")
+ lut = torch.div(torch.cumsum(histo, 0) + step_trunc, step, rounding_mode="trunc")
# Shift lut, prepending with 0.
lut = torch.cat([torch.zeros(1, device=lut.device, dtype=lut.dtype), lut[:-1]])
# Clip the counts to be in range. This is done
@@ -902,7 +902,7 @@ def _scale_channel(im: Tensor) -> Tensor:
histo = _torch_histc_cast(im, bins=256, min=0, max=255)
# For the purposes of computing the step, filter out the nonzeros.
nonzero_histo = torch.reshape(histo[histo != 0], [-1])
- step = torch.div(torch.sum(nonzero_histo) - nonzero_histo[-1], 255, rounding_mode='trunc')
+ step = torch.div(torch.sum(nonzero_histo) - nonzero_histo[-1], 255, rounding_mode="trunc")
# If step is zero, return the original image. Otherwise, build
# lut from the full histogram and step and then index from it.
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index f537867ff..957d45c01 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -46,10 +46,10 @@ def _compute_tiles(
# add the padding in the last coluns and rows
if pad_vert > batch.shape[-2] or pad_horz > batch.shape[-1]:
- raise ValueError('Cannot compute tiles on the image according to the given grid size')
+ raise ValueError("Cannot compute tiles on the image according to the given grid size")
if pad_vert > 0 or pad_horz > 0:
- batch = F.pad(batch, [0, pad_horz, 0, pad_vert], mode='reflect') # B x C x H' x W'
+ batch = F.pad(batch, [0, pad_horz, 0, pad_vert], mode="reflect") # B x C x H' x W'
# compute tiles
c: int = batch.shape[-3]
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.py
index 4684a60e6..bad4e426c 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -196,7 +196,7 @@ def image_histogram2d(
raise ValueError(f"Bins' centers must be a torch.Tensor of the shape (n_bins,). Got {centers.shape}.")
if not isinstance(min, float):
- raise TypeError(f'Type of lower end of the range is not a float. Got {type(min)}.')
+ raise TypeError(f"Type of lower end of the range is not a float. Got {type(min)}.")
if not isinstance(max, float):
raise TypeError(f"Type of upper end of the range is not a float. Got {type(min)}.")
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index 7551884f5..4066af524 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -84,7 +84,7 @@ class ZCAWhitening(Module):
self.transform_matrix: Tensor
self.transform_inv: Optional[Tensor]
- def fit(self, x: Tensor) -> 'ZCAWhitening':
+ def fit(self, x: Tensor) -> "ZCAWhitening":
r"""Fit ZCA whitening matrices to the data.
Args:
@@ -148,7 +148,7 @@ class ZCAWhitening(Module):
raise RuntimeError("Did not compute inverse ZCA. Please set compute_inv to True")
if self.transform_inv is None:
- raise TypeError('The transform inverse should be a Tensor. Gotcha None.')
+ raise TypeError("The transform inverse should be a Tensor. Gotcha None.")
mean_inv: Tensor = -self.mean_vector.mm(self.transform_matrix)
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index 8b0f0f2af..b85806b36 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -26,7 +26,7 @@ def get_adalam_default_config() -> AdalamConfig:
detected_scale_rate_threshold=5,
refit=True,
force_seed_mnn=True,
- device=torch.device('cpu'),
+ device=torch.device("cpu"),
)
@@ -65,7 +65,7 @@ def match_adalam(
KORNIA_CHECK_LAF(lafs2)
config_ = get_adalam_default_config()
if config is None:
- config_['device'] = desc1.device
+ config_["device"] = desc1.device
else:
config_ = get_adalam_default_config()
for key, val in config.items():
@@ -225,29 +225,29 @@ class AdalamFilter:
A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.
"""
if s1 is None or s2 is None:
- if self.config['scale_rate_threshold'] is not None:
+ if self.config["scale_rate_threshold"] is not None:
raise AttributeError(
"Current configuration considers keypoint scales for filtering, but scales have not been provided.\n" # noqa: E501
"Please either provide scales or set 'scale_rate_threshold' to None to disable scale filtering"
)
if o1 is None or o2 is None:
- if self.config['orientation_difference_threshold'] is not None:
+ if self.config["orientation_difference_threshold"] is not None:
raise AttributeError(
"Current configuration considers keypoint orientations for filtering, but orientations have not been provided.\n" # noqa: E501
"Please either provide orientations or set 'orientation_difference_threshold' to None to disable orientations filtering" # noqa: E501
)
- _k1 = as_tensor(k1, device=self.config['device'], dtype=torch.float32)
- _k2 = as_tensor(k2, device=self.config['device'], dtype=torch.float32)
- _d1 = as_tensor(d1, device=self.config['device'], dtype=torch.float32)
- _d2 = as_tensor(d2, device=self.config['device'], dtype=torch.float32)
+ _k1 = as_tensor(k1, device=self.config["device"], dtype=torch.float32)
+ _k2 = as_tensor(k2, device=self.config["device"], dtype=torch.float32)
+ _d1 = as_tensor(d1, device=self.config["device"], dtype=torch.float32)
+ _d2 = as_tensor(d2, device=self.config["device"], dtype=torch.float32)
if o1 is not None:
- _o1 = as_tensor(o1, device=self.config['device'], dtype=torch.float32)
- _o2 = as_tensor(o2, device=self.config['device'], dtype=torch.float32)
+ _o1 = as_tensor(o1, device=self.config["device"], dtype=torch.float32)
+ _o2 = as_tensor(o2, device=self.config["device"], dtype=torch.float32)
else:
_o1, _o2 = o1, o2
if s1 is not None:
- _s1 = as_tensor(s1, device=self.config['device'], dtype=torch.float32)
- _s2 = as_tensor(s2, device=self.config['device'], dtype=torch.float32)
+ _s1 = as_tensor(s1, device=self.config["device"], dtype=torch.float32)
+ _s2 = as_tensor(s2, device=self.config["device"], dtype=torch.float32)
else:
_s1, _s2 = s1, s2
@@ -263,9 +263,9 @@ class AdalamFilter:
putative_matches = nn12[:, 0]
scores = dd12[:, 0] / dd12[:, 1].clamp_min_(1e-3)
- if self.config['force_seed_mnn']:
+ if self.config["force_seed_mnn"]:
dd21, nn21 = torch.min(distmat, dim=0) # (n2,)
- mnn = nn21[putative_matches] == torch.arange(_k1.shape[0], device=self.config['device'])
+ mnn = nn21[putative_matches] == torch.arange(_k1.shape[0], device=self.config["device"])
else:
mnn = None
diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.py
index b26a648e8..05e81f31d 100644
--- a/kornia/feature/adalam/core.py
+++ b/kornia/feature/adalam/core.py
@@ -86,9 +86,7 @@ def select_seeds(
im1scorescomp = scores1.unsqueeze(1) > scores1.unsqueeze(0) # (n1, n1)
# find out who scores higher than all of its neighbors: seed points
if mnn is not None:
- im1bs = (
- (~torch.any(im1neighmap & im1scorescomp & mnn.unsqueeze(0), dim=1)) & mnn & (scores1 < 0.8**2)
- ) # (n1,)
+ im1bs = (~torch.any(im1neighmap & im1scorescomp & mnn.unsqueeze(0), dim=1)) & mnn & (scores1 < 0.8**2) # (n1,)
else:
im1bs = (~torch.any(im1neighmap & im1scorescomp, dim=1)) & (scores1 < 0.8**2)
@@ -290,14 +288,14 @@ def adalam_core(
idxs: A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.
dists: inverse confidence ratio.
"""
- AREA_RATIO = config['area_ratio']
- SEARCH_EXP = config['search_expansion']
- RANSAC_ITERS = config['ransac_iters']
- MIN_INLIERS = config['min_inliers']
- MIN_CONF = config['min_confidence']
- ORIENTATION_THR = config['orientation_difference_threshold']
- SCALE_RATE_THR = config['scale_rate_threshold']
- REFIT = config['refit']
+ AREA_RATIO = config["area_ratio"]
+ SEARCH_EXP = config["search_expansion"]
+ RANSAC_ITERS = config["ransac_iters"]
+ MIN_INLIERS = config["min_inliers"]
+ MIN_CONF = config["min_confidence"]
+ ORIENTATION_THR = config["orientation_difference_threshold"]
+ SCALE_RATE_THR = config["scale_rate_threshold"]
+ REFIT = config["refit"]
if isinstance(im1shape, tuple):
_im1shape = tensor(im1shape, device=k1.device, dtype=k1.dtype)
diff --git a/kornia/feature/adalam/ransac.py b/kornia/feature/adalam/ransac.py
index 30298a40c..e1a99f7c3 100644
--- a/kornia/feature/adalam/ransac.py
+++ b/kornia/feature/adalam/ransac.py
@@ -63,7 +63,7 @@ def confidence_based_inlier_selection(
balanced_rdims, weights_cumsums = group_sum_and_cumsum(inlier_weights, end_rans_indexing, ransidx)
if not isinstance(weights_cumsums, Tensor):
- raise TypeError('Expected the `weights_cumsums` to be a Tensor!')
+ raise TypeError("Expected the `weights_cumsums` to be a Tensor!")
progressive_inl_rates = weights_cumsums.float() / (balanced_rdims.repeat_interleave(rdims, dim=1)).float()
@@ -107,9 +107,9 @@ def sample_padded_inliers(
def ransac(
xsamples: Tensor, ysamples: Tensor, rdims: Tensor, config: Dict[str, Any], iters: int = 128, refit: bool = True
) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
- DET_THR = config['detected_scale_rate_threshold']
- MIN_CONFIDENCE = config['min_confidence']
- dv: torch.device = config['device']
+ DET_THR = config["detected_scale_rate_threshold"]
+ MIN_CONFIDENCE = config["min_confidence"]
+ dv: torch.device = config["device"]
numransacs = rdims.shape[0]
ransidx = torch.arange(numransacs, device=dv).repeat_interleave(rdims)
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 4bb63242a..b89debb10 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -37,7 +37,7 @@ class PatchAffineShapeEstimator(nn.Module):
def __init__(self, patch_size: int = 19, eps: float = 1e-10) -> None:
super().__init__()
self.patch_size: int = patch_size
- self.gradient: nn.Module = SpatialGradient('sobel', 1)
+ self.gradient: nn.Module = SpatialGradient("sobel", 1)
self.eps: float = eps
sigma: float = float(self.patch_size) / math.sqrt(2.0)
self.weighting: torch.Tensor = get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True)
@@ -113,10 +113,10 @@ class LAFAffineShapeEstimator(nn.Module):
def __repr__(self) -> str:
return (
- f'{self.__class__.__name__}'
- f'(patch_size={self.patch_size}, '
- f'affine_shape_detector={self.affine_shape_detector}, '
- f'preserve_orientation={self.preserve_orientation})'
+ f"{self.__class__.__name__}"
+ f"(patch_size={self.patch_size}, "
+ f"affine_shape_detector={self.affine_shape_detector}, "
+ f"preserve_orientation={self.preserve_orientation})"
)
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
@@ -189,8 +189,8 @@ class LAFAffNetShapeEstimator(nn.Module):
self.patch_size = 32
# use torch.hub to load pretrained model
if pretrained:
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['affnet'], map_location=map_location_to_cpu)
- self.load_state_dict(pretrained_dict['state_dict'], strict=False)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls["affnet"], map_location=map_location_to_cpu)
+ self.load_state_dict(pretrained_dict["state_dict"], strict=False)
self.preserve_orientation = preserve_orientation
if preserve_orientation:
warnings.warn(
diff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.py
index bb52313ce..bf68671b6 100644
--- a/kornia/feature/defmo.py
+++ b/kornia/feature/defmo.py
@@ -134,7 +134,7 @@ class ResNet(Module):
for m in self.modules():
if isinstance(m, nn.Conv2d):
- nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
@@ -288,11 +288,11 @@ class DeFMO(Module):
# use torch.hub to load pretrained model
if pretrained:
pretrained_dict = torch.hub.load_state_dict_from_url(
- urls['defmo_encoder'], map_location=map_location_to_cpu
+ urls["defmo_encoder"], map_location=map_location_to_cpu
)
self.encoder.load_state_dict(pretrained_dict, strict=True)
pretrained_dict_ren = torch.hub.load_state_dict_from_url(
- urls['defmo_rendering'], map_location=map_location_to_cpu
+ urls["defmo_rendering"], map_location=map_location_to_cpu
)
self.rendering.load_state_dict(pretrained_dict_ren, strict=True)
self.eval()
diff --git a/kornia/feature/disk/_unets/blocks.py b/kornia/feature/disk/_unets/blocks.py
index 5452331d1..ffb3a4186 100644
--- a/kornia/feature/disk/_unets/blocks.py
+++ b/kornia/feature/disk/_unets/blocks.py
@@ -11,7 +11,7 @@ from kornia.core import Module, Tensor
class TrivialUpsample(Module):
def forward(self, x: Tensor) -> Tensor:
- return F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)
+ return F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False)
class TrivialDownsample(Module):
@@ -32,7 +32,7 @@ class Conv(nn.Sequential):
nonl = nn.PReLU(in_)
dropout = nn.Sequential()
- conv = nn.Conv2d(in_, out_, size, padding='same', bias=True)
+ conv = nn.Conv2d(in_, out_, size, padding="same", bias=True)
super().__init__(norm, nonl, dropout, conv)
diff --git a/kornia/feature/disk/detector.py b/kornia/feature/disk/detector.py
index 1a9792cc8..b21d6eb1a 100644
--- a/kornia/feature/disk/detector.py
+++ b/kornia/feature/disk/detector.py
@@ -12,7 +12,7 @@ from .structs import Keypoints
def nms(signal: Tensor, window_size: int = 5, cutoff: float = 0.0) -> Tensor:
if window_size % 2 != 1:
- raise ValueError(f'window_size has to be odd, got {window_size}')
+ raise ValueError(f"window_size has to be odd, got {window_size}")
_, ixs = F.max_pool2d(signal, kernel_size=window_size, stride=1, padding=window_size // 2, return_indices=True)
diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.py
index 607035233..da05fe1a3 100644
--- a/kornia/feature/disk/disk.py
+++ b/kornia/feature/disk/disk.py
@@ -56,7 +56,7 @@ class DISK(Module):
if unet_output.shape[1] != self.desc_dim + 1:
raise ValueError(
- f'U-Net output has {unet_output.shape[1]} channels, but expected self.desc_dim={self.desc_dim} + 1.'
+ f"U-Net output has {unet_output.shape[1]} channels, but expected self.desc_dim={self.desc_dim} + 1."
)
descriptors = unet_output[:, : self.desc_dim]
@@ -106,7 +106,7 @@ class DISK(Module):
return features
@classmethod
- def from_pretrained(cls, checkpoint: str = 'depth', device: torch.device = torch.device('cpu')) -> DISK:
+ def from_pretrained(cls, checkpoint: str = "depth", device: torch.device = torch.device("cpu")) -> DISK:
r"""Loads a pretrained model.
Depth model was trained using depth map supervision and is slightly more precise but biased to detect keypoints
@@ -122,16 +122,16 @@ class DISK(Module):
The pretrained model.
"""
urls = {
- 'depth': 'https://raw.githubusercontent.com/cvlab-epfl/disk/master/depth-save.pth',
- 'epipolar': 'https://raw.githubusercontent.com/cvlab-epfl/disk/master/epipolar-save.pth',
+ "depth": "https://raw.githubusercontent.com/cvlab-epfl/disk/master/depth-save.pth",
+ "epipolar": "https://raw.githubusercontent.com/cvlab-epfl/disk/master/epipolar-save.pth",
}
if checkpoint not in urls:
- raise ValueError(f'Unknown pretrained model: {checkpoint}')
+ raise ValueError(f"Unknown pretrained model: {checkpoint}")
pretrained_dict = torch.hub.load_state_dict_from_url(urls[checkpoint], map_location=device)
model: DISK = cls().to(device)
- model.load_state_dict(pretrained_dict['extractor'])
+ model.load_state_dict(pretrained_dict["extractor"])
model.eval()
return model
diff --git a/kornia/feature/disk/structs.py b/kornia/feature/disk/structs.py
index 8f625e89a..59983ebe7 100644
--- a/kornia/feature/disk/structs.py
+++ b/kornia/feature/disk/structs.py
@@ -20,6 +20,7 @@ class DISKFeatures:
the log-probability of keeping a keypoint after it has been proposed (see the paper
section *Method → Feature distribution* for details).
"""
+
keypoints: Tensor
descriptors: Tensor
detection_scores: Tensor
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 1fd9c6d7b..8f86bc15f 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -37,6 +37,7 @@ class HardNet(nn.Module):
>>> hardnet = HardNet()
>>> descs = hardnet(input) # 16x128
"""
+
patch_size = 32
def __init__(self, pretrained: bool = False) -> None:
@@ -67,8 +68,8 @@ class HardNet(nn.Module):
# use torch.hub to load pretrained model
if pretrained:
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty_aug'], map_location=map_location_to_cpu)
- self.load_state_dict(pretrained_dict['state_dict'], strict=True)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls["liberty_aug"], map_location=map_location_to_cpu)
+ self.load_state_dict(pretrained_dict["state_dict"], strict=True)
self.eval()
@staticmethod
@@ -113,6 +114,7 @@ class HardNet8(nn.Module):
>>> hardnet = HardNet8()
>>> descs = hardnet(input) # 16x128
"""
+
patch_size = 32
def __init__(self, pretrained: bool = False) -> None:
@@ -144,12 +146,12 @@ class HardNet8(nn.Module):
nn.BatchNorm2d(512, affine=False),
)
self.features.apply(self.weights_init)
- self.register_buffer('components', torch.ones(512, 128, dtype=torch.float))
- self.register_buffer('mean', torch.zeros(512, dtype=torch.float))
+ self.register_buffer("components", torch.ones(512, 128, dtype=torch.float))
+ self.register_buffer("mean", torch.zeros(512, dtype=torch.float))
# use torch.hub to load pretrained model
if pretrained:
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['hardnet8v2'], map_location=map_location_to_cpu)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls["hardnet8v2"], map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.py
index 4d0aa9fc8..2c5fefa0e 100644
--- a/kornia/feature/hynet.py
+++ b/kornia/feature/hynet.py
@@ -7,15 +7,9 @@ from kornia.core import Module, Parameter, Tensor, tensor, zeros
from kornia.utils.helpers import map_location_to_cpu
urls: Dict[str, str] = {}
-urls[
- "liberty"
-] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_LIB.pth" # pylint: disable
-urls[
- "notredame"
-] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_ND.pth" # pylint: disable
-urls[
- "yosemite"
-] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_YOS.pth" # pylint: disable
+urls["liberty"] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_LIB.pth" # pylint: disable
+urls["notredame"] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_ND.pth" # pylint: disable
+urls["yosemite"] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_YOS.pth" # pylint: disable
class FilterResponseNorm2d(Module):
@@ -63,7 +57,7 @@ class FilterResponseNorm2d(Module):
if is_eps_leanable:
self.eps = Parameter(tensor(1), requires_grad=True)
else:
- self.register_buffer('eps', tensor([eps]))
+ self.register_buffer("eps", tensor([eps]))
self.reset_parameters()
def reset_parameters(self) -> None:
@@ -73,7 +67,7 @@ class FilterResponseNorm2d(Module):
nn.init.constant_(self.eps, self.init_eps)
def extra_repr(self) -> str:
- return 'num_features={num_features}, eps={init_eps}'.format(**self.__dict__)
+ return "num_features={num_features}, eps={init_eps}".format(**self.__dict__)
def forward(self, x: Tensor) -> Tensor:
# Compute the mean norm of activations per channel.
@@ -120,7 +114,7 @@ class TLU(Module):
nn.init.constant_(self.tau, -1)
def extra_repr(self) -> str:
- return 'num_features={num_features}'.format(**self.__dict__)
+ return "num_features={num_features}".format(**self.__dict__)
def forward(self, x: Tensor) -> Tensor:
return torch.max(x, self.tau)
@@ -153,6 +147,7 @@ class HyNet(Module):
>>> hynet = HyNet()
>>> descs = hynet(input) # 16x128
"""
+
patch_size = 32
def __init__(
@@ -214,7 +209,7 @@ class HyNet(Module):
self.desc_norm = nn.LocalResponseNorm(2 * self.dim_desc, 2.0 * self.dim_desc, 0.5, 0.0)
# use torch.hub to load pretrained model
if pretrained:
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty'], map_location=map_location_to_cpu)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls["liberty"], map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index bbcb50d6f..31d641b0e 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -154,7 +154,7 @@ class SIFTFeature(LocalFeature):
num_features: int = 8000,
upright: bool = False,
rootsift: bool = True,
- device: Device = torch.device('cpu'),
+ device: Device = torch.device("cpu"),
config: Detector_config = get_default_detector_config(),
) -> None:
patch_size: int = 41
@@ -183,7 +183,7 @@ class SIFTFeatureScaleSpace(LocalFeature):
num_features: int = 8000,
upright: bool = False,
rootsift: bool = True,
- device: Device = torch.device('cpu'),
+ device: Device = torch.device("cpu"),
) -> None:
patch_size: int = 41
detector = ScaleSpaceDetector(
@@ -209,7 +209,7 @@ class GFTTAffNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: Device = torch.device('cpu'),
+ device: Device = torch.device("cpu"),
config: Detector_config = get_default_detector_config(),
) -> None:
detector = MultiResolutionDetector(
@@ -230,7 +230,7 @@ class HesAffNetHardNet(LocalFeature):
self,
num_features: int = 2048,
upright: bool = False,
- device: Device = torch.device('cpu'),
+ device: Device = torch.device("cpu"),
config: Detector_config = get_default_detector_config(),
) -> None:
detector = MultiResolutionDetector(
@@ -251,7 +251,7 @@ class KeyNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: Device = torch.device('cpu'),
+ device: Device = torch.device("cpu"),
scale_laf: float = 1.0,
) -> None:
ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True))
@@ -270,7 +270,7 @@ class KeyNetAffNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: Device = torch.device('cpu'),
+ device: Device = torch.device("cpu"),
scale_laf: float = 1.0,
) -> None:
ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True))
@@ -314,12 +314,12 @@ class LocalFeatureMatcher(Module):
def no_match_output(self, device: Device, dtype: torch.dtype) -> Dict[str, Tensor]:
return {
- 'keypoints0': torch.empty(0, 2, device=device, dtype=dtype),
- 'keypoints1': torch.empty(0, 2, device=device, dtype=dtype),
- 'lafs0': torch.empty(0, 0, 2, 3, device=device, dtype=dtype),
- 'lafs1': torch.empty(0, 0, 2, 3, device=device, dtype=dtype),
- 'confidence': torch.empty(0, device=device, dtype=dtype),
- 'batch_indexes': torch.empty(0, device=device, dtype=torch.long),
+ "keypoints0": torch.empty(0, 2, device=device, dtype=dtype),
+ "keypoints1": torch.empty(0, 2, device=device, dtype=dtype),
+ "lafs0": torch.empty(0, 0, 2, 3, device=device, dtype=dtype),
+ "lafs1": torch.empty(0, 0, 2, 3, device=device, dtype=dtype),
+ "confidence": torch.empty(0, device=device, dtype=dtype),
+ "batch_indexes": torch.empty(0, device=device, dtype=torch.long),
}
def forward(self, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
@@ -341,20 +341,20 @@ class LocalFeatureMatcher(Module):
- ``lafs1``, matching LAFs from image1 :math:`(1, NC, 2, 3)`.
- ``batch_indexes``, batch indexes for the keypoints and lafs :math:`(NC)`.
"""
- num_image_pairs: int = data['image0'].shape[0]
+ num_image_pairs: int = data["image0"].shape[0]
- if ('lafs0' not in data.keys()) or ('descriptors0' not in data.keys()):
+ if ("lafs0" not in data.keys()) or ("descriptors0" not in data.keys()):
# One can supply pre-extracted local features
- feats_dict0: Dict[str, Tensor] = self.extract_features(data['image0'])
- lafs0, descs0 = feats_dict0['lafs'], feats_dict0['descriptors']
+ feats_dict0: Dict[str, Tensor] = self.extract_features(data["image0"])
+ lafs0, descs0 = feats_dict0["lafs"], feats_dict0["descriptors"]
else:
- lafs0, descs0 = data['lafs0'], data['descriptors0']
+ lafs0, descs0 = data["lafs0"], data["descriptors0"]
- if ('lafs1' not in data.keys()) or ('descriptors1' not in data.keys()):
- feats_dict1: Dict[str, Tensor] = self.extract_features(data['image1'])
- lafs1, descs1 = feats_dict1['lafs'], feats_dict1['descriptors']
+ if ("lafs1" not in data.keys()) or ("descriptors1" not in data.keys()):
+ feats_dict1: Dict[str, Tensor] = self.extract_features(data["image1"])
+ lafs1, descs1 = feats_dict1["lafs"], feats_dict1["descriptors"]
else:
- lafs1, descs1 = data['lafs1'], data['descriptors1']
+ lafs1, descs1 = data["lafs1"], data["descriptors1"]
keypoints0: Tensor = get_laf_center(lafs0)
keypoints1: Tensor = get_laf_center(lafs1)
@@ -385,15 +385,15 @@ class LocalFeatureMatcher(Module):
out_batch_indexes.append(batch_idxs)
if len(out_batch_indexes) == 0:
- return self.no_match_output(data['image0'].device, data['image0'].dtype)
+ return self.no_match_output(data["image0"].device, data["image0"].dtype)
return {
- 'keypoints0': concatenate(out_keypoints0, dim=0).view(-1, 2),
- 'keypoints1': concatenate(out_keypoints1, dim=0).view(-1, 2),
- 'lafs0': concatenate(out_lafs0, dim=0).view(1, -1, 2, 3),
- 'lafs1': concatenate(out_lafs1, dim=0).view(1, -1, 2, 3),
- 'confidence': concatenate(out_confidence, dim=0).view(-1),
- 'batch_indexes': concatenate(out_batch_indexes, dim=0).view(-1),
+ "keypoints0": concatenate(out_keypoints0, dim=0).view(-1, 2),
+ "keypoints1": concatenate(out_keypoints1, dim=0).view(-1, 2),
+ "lafs0": concatenate(out_lafs0, dim=0).view(1, -1, 2, 3),
+ "lafs1": concatenate(out_lafs1, dim=0).view(1, -1, 2, 3),
+ "confidence": concatenate(out_confidence, dim=0).view(-1),
+ "batch_indexes": concatenate(out_batch_indexes, dim=0).view(-1),
}
@@ -408,9 +408,9 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
params: LightGlue params.
"""
- known_modes: ClassVar[List[str]] = ['superpoint', 'disk']
+ known_modes: ClassVar[List[str]] = ["superpoint", "disk"]
- def __init__(self, feature_name: str = 'disk', params: Dict = {}) -> None: # type: ignore
+ def __init__(self, feature_name: str = "disk", params: Dict = {}) -> None: # type: ignore
feature_name_: str = feature_name.lower()
super().__init__(feature_name_)
self.feature_name = feature_name_
@@ -465,7 +465,7 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
},
}
pred = self.matcher(input_dict)
- matches0, mscores0 = pred['matches0'], pred['matching_scores0']
+ matches0, mscores0 = pred["matches0"], pred["matching_scores0"]
valid = matches0 > -1
matches = torch.stack([torch.where(valid)[1], matches0[valid]], -1)
return mscores0[valid].reshape(-1, 1), matches
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index 25aab03e1..2fae653bd 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -22,11 +22,11 @@ class KeyNet_conf(TypedDict):
keynet_default_config: KeyNet_conf = {
# Key.Net Model
- 'num_filters': 8,
- 'num_levels': 3,
- 'kernel_size': 5,
+ "num_filters": 8,
+ "num_levels": 3,
+ "kernel_size": 5,
# Extraction Parameters
- 'Detector_conf': get_default_detector_config(),
+ "Detector_conf": get_default_detector_config(),
}
KeyNet_URL = "https://github.com/axelBarroso/Key.Net-Pytorch/raw/main/model/weights/keynet_pytorch.pth"
@@ -55,7 +55,7 @@ class _HandcraftedBlock(Module):
def __init__(self) -> None:
super().__init__()
- self.spatial_gradient = SpatialGradient('sobel', 1)
+ self.spatial_gradient = SpatialGradient("sobel", 1)
def forward(self, x: Tensor) -> Tensor:
sobel = self.spatial_gradient(x)
@@ -131,9 +131,9 @@ class KeyNet(Module):
def __init__(self, pretrained: bool = False, keynet_conf: KeyNet_conf = keynet_default_config) -> None:
super().__init__()
- num_filters = keynet_conf['num_filters']
- self.num_levels = keynet_conf['num_levels']
- kernel_size = keynet_conf['kernel_size']
+ num_filters = keynet_conf["num_filters"]
+ self.num_levels = keynet_conf["num_levels"]
+ kernel_size = keynet_conf["kernel_size"]
padding = kernel_size // 2
self.feature_extractor = _FeatureExtractor()
@@ -146,7 +146,7 @@ class KeyNet(Module):
# use torch.hub to load pretrained model
if pretrained:
pretrained_dict = torch.hub.load_state_dict_from_url(KeyNet_URL, map_location=map_location_to_cpu)
- self.load_state_dict(pretrained_dict['state_dict'], strict=True)
+ self.load_state_dict(pretrained_dict["state_dict"], strict=True)
self.eval()
def forward(self, x: Tensor) -> Tensor:
@@ -158,7 +158,7 @@ class KeyNet(Module):
for i in range(1, self.num_levels):
x = pyrdown(x, factor=1.2)
feats_i = self.feature_extractor(x)
- feats_i = F.interpolate(feats_i, size=(shape_im[2], shape_im[3]), mode='bilinear')
+ feats_i = F.interpolate(feats_i, size=(shape_im[2], shape_im[3]), mode="bilinear")
feats.append(feats_i)
scores = self.last_conv(concatenate(feats, 1))
return scores
@@ -192,4 +192,4 @@ class KeyNetDetector(MultiResolutionDetector):
aff_module: Optional[Module] = None,
) -> None:
model = KeyNet(pretrained, keynet_conf)
- super().__init__(model, num_features, keynet_conf['Detector_conf'], ori_module, aff_module)
+ super().__init__(model, num_features, keynet_conf["Detector_conf"], ori_module, aff_module)
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 12626321f..d2023cc80 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -17,7 +17,7 @@ try:
except ModuleNotFoundError:
FlashCrossAttention = None
-if FlashCrossAttention or hasattr(F, 'scaled_dot_product_attention'):
+if FlashCrossAttention or hasattr(F, "scaled_dot_product_attention"):
FLASH_AVAILABLE = True
else:
FLASH_AVAILABLE = False
@@ -83,7 +83,7 @@ class Attention(Module):
super().__init__()
if allow_flash and not FLASH_AVAILABLE:
warnings.warn(
- 'FlashAttention is not available. For optimal speed, consider installing torch >= 2.0 or flash-attn.',
+ "FlashAttention is not available. For optimal speed, consider installing torch >= 2.0 or flash-attn.",
stacklevel=2,
)
self.enable_flash = allow_flash and FLASH_AVAILABLE
@@ -91,7 +91,7 @@ class Attention(Module):
self.flash_ = FlashCrossAttention()
def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
- if self.enable_flash and q.device.type == 'cuda':
+ if self.enable_flash and q.device.type == "cuda":
if FlashCrossAttention:
q, k, v = (x.transpose(-2, -3) for x in [q, k, v])
m = self.flash_(q.half(), stack([k, v], 2).half())
@@ -101,12 +101,12 @@ class Attention(Module):
return F.scaled_dot_product_attention(
q.half().contiguous(), k.half().contiguous(), v.half().contiguous()
).to(q.dtype)
- elif hasattr(F, 'scaled_dot_product_attention'):
+ elif hasattr(F, "scaled_dot_product_attention"):
return F.scaled_dot_product_attention(q.contiguous(), k.contiguous(), v.contiguous()).to(q.dtype)
else:
s = q.shape[-1] ** -0.5
- attn = softmax(einsum('...id,...jd->...ij', q, k) * s, -1)
- return einsum('...ij,...jd->...id', attn, v)
+ attn = softmax(einsum("...id,...jd->...ij", q, k) * s, -1)
+ return einsum("...ij,...jd->...id", attn, v)
class Transformer(Module):
@@ -177,11 +177,11 @@ class CrossTransformer(Module):
m1 = self.flash(qk1, qk0, v0)
else:
qk0, qk1 = qk0 * self.scale**0.5, qk1 * self.scale**0.5
- sim = einsum('b h i d, b h j d -> b h i j', qk0, qk1)
+ sim = einsum("b h i d, b h j d -> b h i j", qk0, qk1)
attn01 = softmax(sim, dim=-1)
attn10 = softmax(sim.transpose(-2, -1).contiguous(), dim=-1)
- m0 = einsum('bhij, bhjd -> bhid', attn01, v1)
- m1 = einsum('bhji, bhjd -> bhid', attn10.transpose(-2, -1), v0)
+ m0 = einsum("bhij, bhjd -> bhid", attn01, v1)
+ m1 = einsum("bhji, bhjd -> bhid", attn10.transpose(-2, -1), v0)
m0, m1 = self.map_(lambda t: t.transpose(1, 2).flatten(start_dim=-2), m0, m1)
m0, m1 = self.map_(self.to_out, m0, m1)
x0 = x0 + self.ffn(concatenate([x0, m0], -1))
@@ -214,7 +214,7 @@ class MatchAssignment(Module):
mdesc0, mdesc1 = self.final_proj(desc0), self.final_proj(desc1)
_, _, d = mdesc0.shape
mdesc0, mdesc1 = mdesc0 / d**0.25, mdesc1 / d**0.25
- sim = einsum('bmd,bnd->bmn', mdesc0, mdesc1)
+ sim = einsum("bmd,bnd->bmn", mdesc0, mdesc1)
z0 = self.matchability(desc0)
z1 = self.matchability(desc1)
scores = sigmoid_log_double_softmax(sim, z0, z1)
@@ -248,32 +248,32 @@ def filter_matches(scores: Tensor, th: float) -> Tuple[Tensor, Tensor, Tensor, T
class LightGlue(Module):
default_conf: ClassVar[Dict[str, Any]] = {
- 'name': 'lightglue', # just for interfacing
- 'input_dim': 256, # input descriptor dimension (autoselected from weights)
- 'descriptor_dim': 256,
- 'n_layers': 9,
- 'num_heads': 4,
- 'flash': True, # enable FlashAttention if available.
- 'mp': False, # enable mixed precision
- 'depth_confidence': 0.95, # early stopping, disable with -1
- 'width_confidence': 0.99, # point pruning, disable with -1
- 'filter_threshold': 0.1, # match threshold
- 'weights': None,
+ "name": "lightglue", # just for interfacing
+ "input_dim": 256, # input descriptor dimension (autoselected from weights)
+ "descriptor_dim": 256,
+ "n_layers": 9,
+ "num_heads": 4,
+ "flash": True, # enable FlashAttention if available.
+ "mp": False, # enable mixed precision
+ "depth_confidence": 0.95, # early stopping, disable with -1
+ "width_confidence": 0.99, # point pruning, disable with -1
+ "filter_threshold": 0.1, # match threshold
+ "weights": None,
}
- required_data_keys: ClassVar[List[str]] = ['image0', 'image1']
+ required_data_keys: ClassVar[List[str]] = ["image0", "image1"]
version: ClassVar[str] = "v0.1_arxiv"
url: ClassVar[str] = "https://github.com/cvg/LightGlue/releases/download/{}/{}_lightglue.pth"
- features: ClassVar[Dict[str, Any]] = {'superpoint': ('superpoint_lightglue', 256), 'disk': ('disk_lightglue', 128)}
+ features: ClassVar[Dict[str, Any]] = {"superpoint": ("superpoint_lightglue", 256), "disk": ("disk_lightglue", 128)}
- def __init__(self, features: str = 'superpoint', **conf) -> None: # type: ignore
+ def __init__(self, features: str = "superpoint", **conf) -> None: # type: ignore
super().__init__()
temp_conf = {**self.default_conf, **conf}
if features is not None:
KORNIA_CHECK(features in list(self.features.keys()), "Features keys are wrong")
- temp_conf['weights'], temp_conf['input_dim'] = self.features[features]
+ temp_conf["weights"], temp_conf["input_dim"] = self.features[features]
self.conf = conf_ = SimpleNamespace(**temp_conf)
if conf_.input_dim != conf_.descriptor_dim:
@@ -291,16 +291,16 @@ class LightGlue(Module):
self.token_confidence = ModuleList([TokenConfidence(d) for _ in range(n - 1)])
if features is not None:
- fname = f'{conf_.weights}_{self.version}.pth'.replace('.', '-')
+ fname = f"{conf_.weights}_{self.version}.pth".replace(".", "-")
state_dict = torch.hub.load_state_dict_from_url(self.url.format(self.version, features), file_name=fname)
self.load_state_dict(state_dict, strict=False)
elif conf_.weights is not None:
path = Path(__file__).parent
- path = path / f'weights/{self.conf.weights}.pth'
- state_dict = torch.load(str(path), map_location='cpu')
+ path = path / f"weights/{self.conf.weights}.pth"
+ state_dict = torch.load(str(path), map_location="cpu")
self.load_state_dict(state_dict, strict=False)
- print('Loaded LightGlue model')
+ print("Loaded LightGlue model")
def forward(self, data: Dict) -> Dict: # type: ignore
"""Match keypoints and descriptors between two images.
@@ -327,29 +327,29 @@ class LightGlue(Module):
def _forward(self, data: Dict[str, Dict[str, Tensor]]) -> Dict[str, Any]:
for key in self.required_data_keys:
- KORNIA_CHECK(key in data, f'Missing key {key} in data')
- data0, data1 = data['image0'], data['image1']
- kpts0_, kpts1_ = data0['keypoints'], data1['keypoints']
+ KORNIA_CHECK(key in data, f"Missing key {key} in data")
+ data0, data1 = data["image0"], data["image1"]
+ kpts0_, kpts1_ = data0["keypoints"], data1["keypoints"]
# torch 1.9.0 compatibility
- if hasattr(torch, 'inf'):
+ if hasattr(torch, "inf"):
inf = torch.inf
else:
inf = math.inf
b, m, _ = kpts0_.shape
b, n, _ = kpts1_.shape
- size0, size1 = data0.get('image_size'), data1.get('image_size')
- size0 = size0 if size0 is not None else data0['image'].shape[-2:][::-1] # type: ignore
- size1 = size1 if size1 is not None else data1['image'].shape[-2:][::-1] # type: ignore
+ size0, size1 = data0.get("image_size"), data1.get("image_size")
+ size0 = size0 if size0 is not None else data0["image"].shape[-2:][::-1] # type: ignore
+ size1 = size1 if size1 is not None else data1["image"].shape[-2:][::-1] # type: ignore
kpts0 = normalize_keypoints(kpts0_, size=size0)
kpts1 = normalize_keypoints(kpts1_, size=size1)
KORNIA_CHECK(torch.all(kpts0 >= -1).item() and torch.all(kpts0 <= 1).item(), "") # type: ignore
KORNIA_CHECK(torch.all(kpts1 >= -1).item() and torch.all(kpts1 <= 1).item(), "") # type: ignore
- desc0 = data0['descriptors'].detach()
- desc1 = data1['descriptors'].detach()
+ desc0 = data0["descriptors"].detach()
+ desc1 = data1["descriptors"].detach()
KORNIA_CHECK(desc0.shape[-1] == self.conf.input_dim, "Descriptor dimension does not match input dim in config")
KORNIA_CHECK(desc1.shape[-1] == self.conf.input_dim, "Descriptor dimension does not match input dim in config")
@@ -401,7 +401,7 @@ class LightGlue(Module):
scores[:, :-1, :-1] = -inf
scores[:, ind0[0], -1] = scores_[:, :-1, -1]
scores[:, -1, ind1[0]] = scores_[:, -1, :-1]
- x, y = torch_meshgrid([ind0[0], ind1[0]], 'ij')
+ x, y = torch_meshgrid([ind0[0], ind1[0]], "ij")
scores[:, x, y] = scores_[:, :-1, :-1]
else:
scores, _ = self.log_assignment[i](desc0, desc1)
@@ -415,16 +415,16 @@ class LightGlue(Module):
mscores.append(mscores0[k][valid])
return {
- 'log_assignment': scores,
- 'matches0': m0,
- 'matches1': m1,
- 'matching_scores0': mscores0,
- 'matching_scores1': mscores1,
- 'stop': i + 1,
- 'prune0': prune0,
- 'prune1': prune1,
- 'matches': matches,
- 'scores': mscores,
+ "log_assignment": scores,
+ "matches0": m0,
+ "matches1": m1,
+ "matching_scores0": mscores0,
+ "matching_scores1": mscores1,
+ "stop": i + 1,
+ "prune0": prune0,
+ "prune1": prune1,
+ "matches": matches,
+ "scores": mscores,
}
def conf_th(self, i: int) -> float:
diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.py
index 4d4629a8b..1bfa76381 100644
--- a/kornia/feature/lightglue_onnx/lightglue.py
+++ b/kornia/feature/lightglue_onnx/lightglue.py
@@ -33,6 +33,7 @@ class OnnxLightGlue:
are ``'disk'``, ``'superpoint'``, ``'disk_fp16'``, and ``'superpoint_fp16'``.
device: Device to run inference on. Currently, only ``'cuda'`` is supported. Defaults to ``'cuda'``.
"""
+
MODEL_URLS: ClassVar[dict[str, str]] = {
"disk": "https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/disk_lightglue_fused.onnx",
"superpoint": "https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/superpoint_lightglue_fused.onnx",
@@ -102,10 +103,10 @@ class OnnxLightGlue:
"""
# Input validation.
for key in self.required_data_keys:
- KORNIA_CHECK(key in data, f'Missing key {key} in data')
- data0, data1 = data['image0'], data['image1']
- kpts0_, kpts1_ = data0['keypoints'].contiguous(), data1['keypoints'].contiguous()
- desc0, desc1 = data0['descriptors'].contiguous(), data1['descriptors'].contiguous()
+ KORNIA_CHECK(key in data, f"Missing key {key} in data")
+ data0, data1 = data["image0"], data["image1"]
+ kpts0_, kpts1_ = data0["keypoints"].contiguous(), data1["keypoints"].contiguous()
+ desc0, desc1 = data0["descriptors"].contiguous(), data1["descriptors"].contiguous()
KORNIA_CHECK_SAME_DEVICES([kpts0_, desc0, kpts1_, desc1], "Wrong device")
KORNIA_CHECK(kpts0_.device.type == self.device.type, "Wrong device")
KORNIA_CHECK(torch.float32 == kpts0_.dtype == kpts1_.dtype == desc0.dtype == desc1.dtype, "Wrong dtype")
@@ -118,9 +119,9 @@ class OnnxLightGlue:
KORNIA_CHECK(desc0.shape[2] == desc1.shape[2], "Descriptors' dimensions do not match")
# Normalize keypoints.
- size0, size1 = data0.get('image_size'), data1.get('image_size')
- size0 = size0 if size0 is not None else data0['image'].shape[-2:][::-1] # type: ignore
- size1 = size1 if size1 is not None else data1['image'].shape[-2:][::-1] # type: ignore
+ size0, size1 = data0.get("image_size"), data1.get("image_size")
+ size0 = size0 if size0 is not None else data0["image"].shape[-2:][::-1] # type: ignore
+ size1 = size1 if size1 is not None else data1["image"].shape[-2:][::-1] # type: ignore
kpts0 = normalize_keypoints(kpts0_, size=size0) # type: ignore
kpts1 = normalize_keypoints(kpts1_, size=size1) # type: ignore
diff --git a/kornia/feature/lightglue_onnx/utils/download.py b/kornia/feature/lightglue_onnx/utils/download.py
index 3aaff41f5..ca8fc4267 100644
--- a/kornia/feature/lightglue_onnx/utils/download.py
+++ b/kornia/feature/lightglue_onnx/utils/download.py
@@ -42,7 +42,7 @@ def download_onnx_from_url(
"""
if model_dir is None:
hub_dir = get_dir()
- model_dir = os.path.join(hub_dir, 'checkpoints')
+ model_dir = os.path.join(hub_dir, "checkpoints")
os.makedirs(model_dir, exist_ok=True)
diff --git a/kornia/feature/loftr/backbone/__init__.py b/kornia/feature/loftr/backbone/__init__.py
index dbfd9e515..94db1daa7 100644
--- a/kornia/feature/loftr/backbone/__init__.py
+++ b/kornia/feature/loftr/backbone/__init__.py
@@ -6,10 +6,10 @@ from .resnet_fpn import ResNetFPN_8_2, ResNetFPN_16_4
def build_backbone(config: dict[str, Any]) -> ResNetFPN_8_2 | ResNetFPN_16_4:
- if config['backbone_type'] == 'ResNetFPN':
- if config['resolution'] == (8, 2):
- return ResNetFPN_8_2(config['resnetfpn'])
- elif config['resolution'] == (16, 4):
- return ResNetFPN_16_4(config['resnetfpn'])
+ if config["backbone_type"] == "ResNetFPN":
+ if config["resolution"] == (8, 2):
+ return ResNetFPN_8_2(config["resnetfpn"])
+ elif config["resolution"] == (16, 4):
+ return ResNetFPN_16_4(config["resnetfpn"])
raise ValueError(f"LOFTR.BACKBONE_TYPE {config['backbone_type']} with res {config['resolution']} not supported.")
diff --git a/kornia/feature/loftr/backbone/resnet_fpn.py b/kornia/feature/loftr/backbone/resnet_fpn.py
index 79e140718..a3e70f9b2 100644
--- a/kornia/feature/loftr/backbone/resnet_fpn.py
+++ b/kornia/feature/loftr/backbone/resnet_fpn.py
@@ -51,8 +51,8 @@ class ResNetFPN_8_2(nn.Module):
super().__init__()
# Config
block = BasicBlock
- initial_dim = config['initial_dim']
- block_dims = config['block_dims']
+ initial_dim = config["initial_dim"]
+ block_dims = config["block_dims"]
# Class Variable
self.in_planes = initial_dim
@@ -85,7 +85,7 @@ class ResNetFPN_8_2(nn.Module):
for m in self.modules():
if isinstance(m, nn.Conv2d):
- nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
@@ -109,11 +109,11 @@ class ResNetFPN_8_2(nn.Module):
x3_out = self.layer3_outconv(x3)
x2_out = self.layer2_outconv(x2)
- x3_out_2x = F.interpolate(x3_out, size=(x2_out.shape[2:]), mode='bilinear', align_corners=True)
+ x3_out_2x = F.interpolate(x3_out, size=(x2_out.shape[2:]), mode="bilinear", align_corners=True)
x2_out = self.layer2_outconv2(x2_out + x3_out_2x)
x1_out = self.layer1_outconv(x1)
- x2_out_2x = F.interpolate(x2_out, size=(x1_out.shape[2:]), mode='bilinear', align_corners=True)
+ x2_out_2x = F.interpolate(x2_out, size=(x1_out.shape[2:]), mode="bilinear", align_corners=True)
x1_out = self.layer1_outconv2(x1_out + x2_out_2x)
return [x3_out, x1_out]
@@ -129,8 +129,8 @@ class ResNetFPN_16_4(nn.Module):
super().__init__()
# Config
block = BasicBlock
- initial_dim = config['initial_dim']
- block_dims = config['block_dims']
+ initial_dim = config["initial_dim"]
+ block_dims = config["block_dims"]
# Class Variable
self.in_planes = initial_dim
@@ -165,7 +165,7 @@ class ResNetFPN_16_4(nn.Module):
for m in self.modules():
if isinstance(m, nn.Conv2d):
- nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
@@ -189,11 +189,11 @@ class ResNetFPN_16_4(nn.Module):
# FPN
x4_out = self.layer4_outconv(x4)
- x4_out_2x = F.interpolate(x4_out, scale_factor=2.0, mode='bilinear', align_corners=True)
+ x4_out_2x = F.interpolate(x4_out, scale_factor=2.0, mode="bilinear", align_corners=True)
x3_out = self.layer3_outconv(x3)
x3_out = self.layer3_outconv2(x3_out + x4_out_2x)
- x3_out_2x = F.interpolate(x3_out, scale_factor=2.0, mode='bilinear', align_corners=True)
+ x3_out_2x = F.interpolate(x3_out, scale_factor=2.0, mode="bilinear", align_corners=True)
x2_out = self.layer2_outconv(x2)
x2_out = self.layer2_outconv2(x2_out + x3_out_2x)
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index 65340ba2b..f61a8a17c 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -23,31 +23,31 @@ urls["indoor"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor.ckpt"
# Some do not change there anything, unless you want to retrain it.
default_cfg = {
- 'backbone_type': 'ResNetFPN',
- 'resolution': (8, 2),
- 'fine_window_size': 5,
- 'fine_concat_coarse_feat': True,
- 'resnetfpn': {'initial_dim': 128, 'block_dims': [128, 196, 256]},
- 'coarse': {
- 'd_model': 256,
- 'd_ffn': 256,
- 'nhead': 8,
- 'layer_names': ['self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross'],
- 'attention': 'linear',
- 'temp_bug_fix': False,
+ "backbone_type": "ResNetFPN",
+ "resolution": (8, 2),
+ "fine_window_size": 5,
+ "fine_concat_coarse_feat": True,
+ "resnetfpn": {"initial_dim": 128, "block_dims": [128, 196, 256]},
+ "coarse": {
+ "d_model": 256,
+ "d_ffn": 256,
+ "nhead": 8,
+ "layer_names": ["self", "cross", "self", "cross", "self", "cross", "self", "cross"],
+ "attention": "linear",
+ "temp_bug_fix": False,
},
- 'match_coarse': {
- 'thr': 0.2,
- 'border_rm': 2,
- 'match_type': 'dual_softmax',
- 'dsmax_temperature': 0.1,
- 'skh_iters': 3,
- 'skh_init_bin_score': 1.0,
- 'skh_prefilter': True,
- 'train_coarse_percent': 0.4,
- 'train_pad_num_gt_min': 200,
+ "match_coarse": {
+ "thr": 0.2,
+ "border_rm": 2,
+ "match_type": "dual_softmax",
+ "dsmax_temperature": 0.1,
+ "skh_iters": 3,
+ "skh_init_bin_score": 1.0,
+ "skh_prefilter": True,
+ "train_coarse_percent": 0.4,
+ "train_pad_num_gt_min": 200,
},
- 'fine': {'d_model': 128, 'd_ffn': 128, 'nhead': 8, 'layer_names': ['self', 'cross'], 'attention': 'linear'},
+ "fine": {"d_model": 128, "d_ffn": 128, "nhead": 8, "layer_names": ["self", "cross"], "attention": "linear"},
}
@@ -76,19 +76,19 @@ class LoFTR(Module):
>>> out = loftr(input)
"""
- def __init__(self, pretrained: Optional[str] = 'outdoor', config: dict[str, Any] = default_cfg) -> None:
+ def __init__(self, pretrained: Optional[str] = "outdoor", config: dict[str, Any] = default_cfg) -> None:
super().__init__()
# Misc
self.config = config
- if pretrained == 'indoor_new':
- self.config['coarse']['temp_bug_fix'] = True
+ if pretrained == "indoor_new":
+ self.config["coarse"]["temp_bug_fix"] = True
# Modules
self.backbone = build_backbone(config)
self.pos_encoding = PositionEncodingSine(
- config['coarse']['d_model'], temp_bug_fix=config['coarse']['temp_bug_fix']
+ config["coarse"]["d_model"], temp_bug_fix=config["coarse"]["temp_bug_fix"]
)
- self.loftr_coarse = LocalFeatureTransformer(config['coarse'])
- self.coarse_matching = CoarseMatching(config['match_coarse'])
+ self.loftr_coarse = LocalFeatureTransformer(config["coarse"])
+ self.coarse_matching = CoarseMatching(config["match_coarse"])
self.fine_preprocess = FinePreprocess(config)
self.loftr_fine = LocalFeatureTransformer(config["fine"])
self.fine_matching = FineMatching()
@@ -98,7 +98,7 @@ class LoFTR(Module):
raise ValueError(f"pretrained should be None or one of {urls.keys()}")
pretrained_dict = torch.hub.load_state_dict_from_url(urls[pretrained], map_location=map_location_to_cpu)
- self.load_state_dict(pretrained_dict['state_dict'])
+ self.load_state_dict(pretrained_dict["state_dict"])
self.eval()
def forward(self, data: dict[str, Tensor]) -> dict[str, Tensor]:
@@ -120,23 +120,23 @@ class LoFTR(Module):
"""
# 1. Local Feature CNN
_data: dict[str, Tensor | int | torch.Size] = {
- 'bs': data['image0'].size(0),
- 'hw0_i': data['image0'].shape[2:],
- 'hw1_i': data['image1'].shape[2:],
+ "bs": data["image0"].size(0),
+ "hw0_i": data["image0"].shape[2:],
+ "hw1_i": data["image1"].shape[2:],
}
- if _data['hw0_i'] == _data['hw1_i']: # faster & better BN convergence
- feats_c, feats_f = self.backbone(torch.cat([data['image0'], data['image1']], dim=0))
- (feat_c0, feat_c1), (feat_f0, feat_f1) = feats_c.split(_data['bs']), feats_f.split(_data['bs'])
+ if _data["hw0_i"] == _data["hw1_i"]: # faster & better BN convergence
+ feats_c, feats_f = self.backbone(torch.cat([data["image0"], data["image1"]], dim=0))
+ (feat_c0, feat_c1), (feat_f0, feat_f1) = feats_c.split(_data["bs"]), feats_f.split(_data["bs"])
else: # handle different input shapes
- (feat_c0, feat_f0), (feat_c1, feat_f1) = self.backbone(data['image0']), self.backbone(data['image1'])
+ (feat_c0, feat_f0), (feat_c1, feat_f1) = self.backbone(data["image0"]), self.backbone(data["image1"])
_data.update(
{
- 'hw0_c': feat_c0.shape[2:],
- 'hw1_c': feat_c1.shape[2:],
- 'hw0_f': feat_f0.shape[2:],
- 'hw1_f': feat_f1.shape[2:],
+ "hw0_c": feat_c0.shape[2:],
+ "hw1_c": feat_c1.shape[2:],
+ "hw0_f": feat_f0.shape[2:],
+ "hw1_f": feat_f1.shape[2:],
}
)
@@ -154,10 +154,10 @@ class LoFTR(Module):
feat_c1 = feat_c1.reshape(n1, -1, c1)
mask_c0 = mask_c1 = None # mask is useful in training
- if 'mask0' in _data:
- mask_c0 = resize(data['mask0'], _data['hw0_c'], interpolation='nearest').flatten(-2)
- if 'mask1' in _data:
- mask_c1 = resize(data['mask1'], _data['hw1_c'], interpolation='nearest').flatten(-2)
+ if "mask0" in _data:
+ mask_c0 = resize(data["mask0"], _data["hw0_c"], interpolation="nearest").flatten(-2)
+ if "mask1" in _data:
+ mask_c1 = resize(data["mask1"], _data["hw1_c"], interpolation="nearest").flatten(-2)
feat_c0, feat_c1 = self.loftr_coarse(feat_c0, feat_c1, mask_c0, mask_c1)
# 3. match coarse-level
@@ -172,10 +172,10 @@ class LoFTR(Module):
self.fine_matching(feat_f0_unfold, feat_f1_unfold, _data)
rename_keys: dict[str, str] = {
- "mkpts0_f": 'keypoints0',
- "mkpts1_f": 'keypoints1',
- "mconf": 'confidence',
- "b_ids": 'batch_indexes',
+ "mkpts0_f": "keypoints0",
+ "mkpts1_f": "keypoints1",
+ "mconf": "confidence",
+ "b_ids": "batch_indexes",
}
out: dict[str, Tensor] = {}
for k, v in rename_keys.items():
@@ -183,11 +183,11 @@ class LoFTR(Module):
if isinstance(_d, Tensor):
out[v] = _d
else:
- raise TypeError(f'Expected Tensor for item `{k}`. Gotcha {type(_d)}')
+ raise TypeError(f"Expected Tensor for item `{k}`. Gotcha {type(_d)}")
return out
def load_state_dict(self, state_dict: dict[str, Any], *args: Any, **kwargs: Any) -> Any: # type: ignore[override]
for k in list(state_dict.keys()):
- if k.startswith('matcher.'):
- state_dict[k.replace('matcher.', '', 1)] = state_dict.pop(k)
+ if k.startswith("matcher."):
+ state_dict[k.replace("matcher.", "", 1)] = state_dict.pop(k)
return super().load_state_dict(state_dict, *args, **kwargs)
diff --git a/kornia/feature/loftr/loftr_module/fine_preprocess.py b/kornia/feature/loftr/loftr_module/fine_preprocess.py
index e0ab06702..ca13904c5 100644
--- a/kornia/feature/loftr/loftr_module/fine_preprocess.py
+++ b/kornia/feature/loftr/loftr_module/fine_preprocess.py
@@ -12,11 +12,11 @@ class FinePreprocess(Module):
super().__init__()
self.config = config
- self.cat_c_feat = config['fine_concat_coarse_feat']
- self.W = self.config['fine_window_size']
+ self.cat_c_feat = config["fine_concat_coarse_feat"]
+ self.W = self.config["fine_window_size"]
- d_model_c = self.config['coarse']['d_model']
- d_model_f = self.config['fine']['d_model']
+ d_model_c = self.config["coarse"]["d_model"]
+ d_model_f = self.config["fine"]["d_model"]
self.d_model_f = d_model_f
if self.cat_c_feat:
self.down_proj = nn.Linear(d_model_c, d_model_f, bias=True)
@@ -33,10 +33,10 @@ class FinePreprocess(Module):
self, feat_f0: Tensor, feat_f1: Tensor, feat_c0: Tensor, feat_c1: Tensor, data: Dict[str, Any]
) -> Tuple[Tensor, Tensor]:
W = self.W
- stride = data['hw0_f'][0] // data['hw0_c'][0]
+ stride = data["hw0_f"][0] // data["hw0_c"][0]
- data.update({'W': W})
- if data['b_ids'].shape[0] == 0:
+ data.update({"W": W})
+ if data["b_ids"].shape[0] == 0:
feat0 = torch.empty(0, self.W**2, self.d_model_f, device=feat_f0.device)
feat1 = torch.empty(0, self.W**2, self.d_model_f, device=feat_f0.device)
return feat0, feat1
@@ -56,13 +56,13 @@ class FinePreprocess(Module):
feat_f1_unfold = feat_f1_unfold.reshape(n1, c1, -1, l1).permute(0, 3, 2, 1)
# 2. select only the predicted matches
- feat_f0_unfold = feat_f0_unfold[data['b_ids'], data['i_ids']] # [n, ww, cf]
- feat_f1_unfold = feat_f1_unfold[data['b_ids'], data['j_ids']]
+ feat_f0_unfold = feat_f0_unfold[data["b_ids"], data["i_ids"]] # [n, ww, cf]
+ feat_f1_unfold = feat_f1_unfold[data["b_ids"], data["j_ids"]]
# option: use coarse-level loftr feature as context: concat and linear
if self.cat_c_feat:
feat_c_win = self.down_proj(
- torch.cat([feat_c0[data['b_ids'], data['i_ids']], feat_c1[data['b_ids'], data['j_ids']]], 0)
+ torch.cat([feat_c0[data["b_ids"], data["i_ids"]], feat_c1[data["b_ids"], data["j_ids"]]], 0)
) # [2n, c]
feat_cf_win = self.merge_feat(
torch.cat(
diff --git a/kornia/feature/loftr/loftr_module/linear_attention.py b/kornia/feature/loftr/loftr_module/linear_attention.py
index c9122a7bc..bf240bdba 100644
--- a/kornia/feature/loftr/loftr_module/linear_attention.py
+++ b/kornia/feature/loftr/loftr_module/linear_attention.py
@@ -85,7 +85,7 @@ class FullAttention(Module):
# Compute the unnormalized attention and apply the masks
QK = torch.einsum("nlhd,nshd->nlsh", queries, keys)
if kv_mask is not None and q_mask is not None:
- QK.masked_fill_(~(q_mask[:, :, None, None] * kv_mask[:, None, :, None]), float('-inf'))
+ QK.masked_fill_(~(q_mask[:, :, None, None] * kv_mask[:, None, :, None]), float("-inf"))
# Compute the attention and the weighted average
softmax_temp = 1.0 / queries.size(3) ** 0.5 # sqrt(D)
diff --git a/kornia/feature/loftr/loftr_module/transformer.py b/kornia/feature/loftr/loftr_module/transformer.py
index 2468634f8..d33be6ec1 100644
--- a/kornia/feature/loftr/loftr_module/transformer.py
+++ b/kornia/feature/loftr/loftr_module/transformer.py
@@ -12,7 +12,7 @@ from .linear_attention import FullAttention, LinearAttention
class LoFTREncoderLayer(Module):
- def __init__(self, d_model: int, nhead: int, attention: Optional[Literal['linear']] = 'linear') -> None:
+ def __init__(self, d_model: int, nhead: int, attention: Optional[Literal["linear"]] = "linear") -> None:
super().__init__()
self.dim = d_model // nhead
@@ -22,7 +22,7 @@ class LoFTREncoderLayer(Module):
self.q_proj = nn.Linear(d_model, d_model, bias=False)
self.k_proj = nn.Linear(d_model, d_model, bias=False)
self.v_proj = nn.Linear(d_model, d_model, bias=False)
- self.attention = LinearAttention() if attention == 'linear' else FullAttention()
+ self.attention = LinearAttention() if attention == "linear" else FullAttention()
self.merge = nn.Linear(d_model, d_model, bias=False)
# feed-forward network
@@ -69,10 +69,10 @@ class LocalFeatureTransformer(Module):
super().__init__()
self.config = config
- self.d_model = config['d_model']
- self.nhead = config['nhead']
- self.layer_names = config['layer_names']
- encoder_layer = LoFTREncoderLayer(config['d_model'], config['nhead'], config['attention'])
+ self.d_model = config["d_model"]
+ self.nhead = config["nhead"]
+ self.layer_names = config["layer_names"]
+ encoder_layer = LoFTREncoderLayer(config["d_model"], config["nhead"], config["attention"])
self.layers = nn.ModuleList([copy.deepcopy(encoder_layer) for _ in range(len(self.layer_names))])
self._reset_parameters()
@@ -96,10 +96,10 @@ class LocalFeatureTransformer(Module):
raise ValueError(msg)
for layer, name in zip(self.layers, self.layer_names):
- if name == 'self':
+ if name == "self":
feat0 = layer(feat0, feat0, mask0, mask0)
feat1 = layer(feat1, feat1, mask1, mask1)
- elif name == 'cross':
+ elif name == "cross":
feat0 = layer(feat0, feat1, mask0, mask1)
feat1 = layer(feat1, feat0, mask1, mask0)
else:
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index ea6d0dfe9..dd11ca2eb 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -64,25 +64,25 @@ class CoarseMatching(Module):
super().__init__()
self.config = config
# general config
- self.thr = config['thr']
- self.border_rm = config['border_rm']
+ self.thr = config["thr"]
+ self.border_rm = config["border_rm"]
# -- # for training fine-level LoFTR
- self.train_coarse_percent = config['train_coarse_percent']
- self.train_pad_num_gt_min = config['train_pad_num_gt_min']
+ self.train_coarse_percent = config["train_coarse_percent"]
+ self.train_pad_num_gt_min = config["train_pad_num_gt_min"]
# we provide 2 options for differentiable matching
- self.match_type = config['match_type']
- if self.match_type == 'dual_softmax':
- self.temperature = config['dsmax_temperature']
- elif self.match_type == 'sinkhorn':
+ self.match_type = config["match_type"]
+ if self.match_type == "dual_softmax":
+ self.temperature = config["dsmax_temperature"]
+ elif self.match_type == "sinkhorn":
try:
from .superglue import log_optimal_transport
except ImportError:
raise ImportError("download superglue.py first!")
self.log_optimal_transport = log_optimal_transport
- self.bin_score = nn.Parameter(torch.tensor(config['skh_init_bin_score'], requires_grad=True))
- self.skh_iters = config['skh_iters']
- self.skh_prefilter = config['skh_prefilter']
+ self.bin_score = nn.Parameter(torch.tensor(config["skh_init_bin_score"], requires_grad=True))
+ self.skh_iters = config["skh_iters"]
+ self.skh_prefilter = config["skh_prefilter"]
else:
raise NotImplementedError
@@ -117,13 +117,13 @@ class CoarseMatching(Module):
# normalize
feat_c0, feat_c1 = (feat / feat.shape[-1] ** 0.5 for feat in [feat_c0, feat_c1])
- if self.match_type == 'dual_softmax':
+ if self.match_type == "dual_softmax":
sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1) / self.temperature
if mask_c0 is not None and mask_c1 is not None:
sim_matrix.masked_fill_(~(mask_c0[..., None] * mask_c1[:, None]).bool(), -INF)
conf_matrix = F.softmax(sim_matrix, 1) * F.softmax(sim_matrix, 2)
- elif self.match_type == 'sinkhorn':
+ elif self.match_type == "sinkhorn":
# sinkhorn, dustbin included
sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1)
if mask_c0 is not None and mask_c1 is not None:
@@ -141,10 +141,10 @@ class CoarseMatching(Module):
conf_matrix[filter0[..., None].repeat(1, 1, S)] = 0
conf_matrix[filter1[:, None].repeat(1, L, 1)] = 0
- if self.config['sparse_spvs']:
- data.update({'conf_matrix_with_bin': assign_matrix.clone()})
+ if self.config["sparse_spvs"]:
+ data.update({"conf_matrix_with_bin": assign_matrix.clone()})
- data.update({'conf_matrix': conf_matrix})
+ data.update({"conf_matrix": conf_matrix})
# predict coarse matches from conf_matrix
data.update(**self.get_coarse_match(conf_matrix, data))
@@ -167,23 +167,23 @@ class CoarseMatching(Module):
'mconf' (torch.Tensor): [M]}
"""
axes_lengths = {
- 'h0c': data['hw0_c'][0],
- 'w0c': data['hw0_c'][1],
- 'h1c': data['hw1_c'][0],
- 'w1c': data['hw1_c'][1],
+ "h0c": data["hw0_c"][0],
+ "w0c": data["hw0_c"][1],
+ "h1c": data["hw1_c"][0],
+ "w1c": data["hw1_c"][1],
}
_device = conf_matrix.device
# 1. confidence thresholding
mask = conf_matrix > self.thr
N = conf_matrix.shape[0]
- mask = mask.reshape(N, axes_lengths['h0c'], axes_lengths['w0c'], axes_lengths['h1c'], axes_lengths['w1c'])
+ mask = mask.reshape(N, axes_lengths["h0c"], axes_lengths["w0c"], axes_lengths["h1c"], axes_lengths["w1c"])
# mask = rearrange(mask, 'b (h0c w0c) (h1c w1c) -> b h0c w0c h1c w1c',
# **axes_lengths)
- if 'mask0' not in data:
+ if "mask0" not in data:
mask_border(mask, self.border_rm, False)
else:
- mask_border_with_padding(mask, self.border_rm, False, data['mask0'], data['mask1'])
- mask = mask.reshape(N, axes_lengths['h0c'] * axes_lengths['w0c'], axes_lengths['h1c'] * axes_lengths['w1c'])
+ mask_border_with_padding(mask, self.border_rm, False, data["mask0"], data["mask1"])
+ mask = mask.reshape(N, axes_lengths["h0c"] * axes_lengths["w0c"], axes_lengths["h1c"] * axes_lengths["w1c"])
# rearrange(mask, 'b h0c w0c h1c w1c -> b (h0c w0c) (h1c w1c)',
# **axes_lengths)
@@ -207,10 +207,10 @@ class CoarseMatching(Module):
# NOTE:
# The sampling is performed across all pairs in a batch without manually balancing
# #samples for fine-level increases w.r.t. batch_size
- if 'mask0' not in data:
+ if "mask0" not in data:
num_candidates_max = mask.size(0) * max(mask.size(1), mask.size(2))
else:
- num_candidates_max = compute_max_candidates(data['mask0'], data['mask1'])
+ num_candidates_max = compute_max_candidates(data["mask0"], data["mask1"])
num_matches_train = num_candidates_max * self.train_coarse_percent
num_matches_train = int(num_matches_train)
num_matches_pred = len(b_ids)
@@ -228,40 +228,40 @@ class CoarseMatching(Module):
# gt_pad_indices is to select from gt padding. e.g. max(3787-4800, 200)
gt_pad_indices = torch.randint(
- len(data['spv_b_ids']),
+ len(data["spv_b_ids"]),
(max(num_matches_train - num_matches_pred, self.train_pad_num_gt_min),),
device=_device,
)
- mconf_gt = torch.zeros(len(data['spv_b_ids']), device=_device) # set conf of gt paddings to all zero
+ mconf_gt = torch.zeros(len(data["spv_b_ids"]), device=_device) # set conf of gt paddings to all zero
b_ids, i_ids, j_ids, mconf = ( # type: ignore
torch.cat([x[pred_indices], y[gt_pad_indices]], dim=0) # type: ignore[has-type]
for x, y in zip(
- [b_ids, data['spv_b_ids']],
- [i_ids, data['spv_i_ids']],
- [j_ids, data['spv_j_ids']],
+ [b_ids, data["spv_b_ids"]],
+ [i_ids, data["spv_i_ids"]],
+ [j_ids, data["spv_j_ids"]],
[mconf, mconf_gt],
)
)
# These matches select patches that feed into fine-level network
- coarse_matches = {'b_ids': b_ids, 'i_ids': i_ids, 'j_ids': j_ids}
+ coarse_matches = {"b_ids": b_ids, "i_ids": i_ids, "j_ids": j_ids}
# 4. Update with matches in original image resolution
- scale = data['hw0_i'][0] / data['hw0_c'][0]
- scale0 = scale * data['scale0'][b_ids] if 'scale0' in data else scale
- scale1 = scale * data['scale1'][b_ids] if 'scale1' in data else scale
- mkpts0_c = torch.stack([i_ids % data['hw0_c'][1], i_ids // data['hw0_c'][1]], dim=1) * scale0
- mkpts1_c = torch.stack([j_ids % data['hw1_c'][1], j_ids // data['hw1_c'][1]], dim=1) * scale1
+ scale = data["hw0_i"][0] / data["hw0_c"][0]
+ scale0 = scale * data["scale0"][b_ids] if "scale0" in data else scale
+ scale1 = scale * data["scale1"][b_ids] if "scale1" in data else scale
+ mkpts0_c = torch.stack([i_ids % data["hw0_c"][1], i_ids // data["hw0_c"][1]], dim=1) * scale0
+ mkpts1_c = torch.stack([j_ids % data["hw1_c"][1], j_ids // data["hw1_c"][1]], dim=1) * scale1
# These matches is the current prediction (for visualization)
coarse_matches.update(
{
- 'gt_mask': mconf == 0,
- 'm_bids': b_ids[mconf != 0], # mconf == 0 => gt matches
- 'mkpts0_c': mkpts0_c[mconf != 0].to(dtype=conf_matrix.dtype),
- 'mkpts1_c': mkpts1_c[mconf != 0].to(dtype=conf_matrix.dtype),
- 'mconf': mconf[mconf != 0],
+ "gt_mask": mconf == 0,
+ "m_bids": b_ids[mconf != 0], # mconf == 0 => gt matches
+ "mkpts0_c": mkpts0_c[mconf != 0].to(dtype=conf_matrix.dtype),
+ "mkpts1_c": mkpts1_c[mconf != 0].to(dtype=conf_matrix.dtype),
+ "mconf": mconf[mconf != 0],
}
)
diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.py
index 70c849c24..c134ae8ef 100644
--- a/kornia/feature/loftr/utils/fine_matching.py
+++ b/kornia/feature/loftr/utils/fine_matching.py
@@ -30,7 +30,7 @@ class FineMatching(Module):
"""
M, WW, C = feat_f0.shape
W = int(math.sqrt(WW))
- scale = data['hw0_i'][0] / data['hw0_f'][0]
+ scale = data["hw0_i"][0] / data["hw0_f"][0]
self.M, self.W, self.WW, self.C, self.scale = M, W, WW, C, scale
# corner case: if no coarse matches found
@@ -40,15 +40,15 @@ class FineMatching(Module):
# logger.warning('No matches found in coarse-level.')
data.update(
{
- 'expec_f': torch.empty(0, 3, device=feat_f0.device, dtype=feat_f0.dtype),
- 'mkpts0_f': data['mkpts0_c'],
- 'mkpts1_f': data['mkpts1_c'],
+ "expec_f": torch.empty(0, 3, device=feat_f0.device, dtype=feat_f0.dtype),
+ "mkpts0_f": data["mkpts0_c"],
+ "mkpts1_f": data["mkpts1_c"],
}
)
return
feat_f0_picked = feat_f0_picked = feat_f0[:, WW // 2, :]
- sim_matrix = torch.einsum('mc,mrc->mr', feat_f0_picked, feat_f1)
+ sim_matrix = torch.einsum("mc,mrc->mr", feat_f0_picked, feat_f1)
softmax_temp = 1.0 / C**0.5
heatmap = torch.softmax(softmax_temp * sim_matrix, dim=1).view(-1, W, W)
@@ -56,16 +56,14 @@ class FineMatching(Module):
coords_normalized = dsnt.spatial_expectation2d(heatmap[None], True)[0] # [M, 2]
grid_normalized = create_meshgrid(
W, W, normalized_coordinates=True, device=heatmap.device, dtype=heatmap.dtype
- ).reshape(
- 1, -1, 2
- ) # [1, WW, 2]
+ ).reshape(1, -1, 2) # [1, WW, 2]
# compute std over <x, y>
var = torch.sum(grid_normalized**2 * heatmap.view(-1, WW, 1), dim=1) - coords_normalized**2 # [M, 2]
std = torch.sum(torch.sqrt(torch.clamp(var, min=1e-10)), -1) # [M] clamp needed for numerical stability
# for fine-level supervision
- data.update({'expec_f': torch.cat([coords_normalized, std.unsqueeze(1)], -1)})
+ data.update({"expec_f": torch.cat([coords_normalized, std.unsqueeze(1)], -1)})
# compute absolute kpt coords
self.get_fine_match(coords_normalized, data)
@@ -75,8 +73,8 @@ class FineMatching(Module):
W, _, _, scale = self.W, self.WW, self.C, self.scale
# mkpts0_f and mkpts1_f
- mkpts0_f = data['mkpts0_c']
- scale1 = scale * data['scale1'][data['b_ids']] if 'scale0' in data else scale
- mkpts1_f = data['mkpts1_c'] + (coords_normed * (W // 2) * scale1)[: len(data['mconf'])]
+ mkpts0_f = data["mkpts0_c"]
+ scale1 = scale * data["scale1"][data["b_ids"]] if "scale0" in data else scale
+ mkpts1_f = data["mkpts1_c"] + (coords_normed * (W // 2) * scale1)[: len(data["mconf"])]
data.update({"mkpts0_f": mkpts0_f, "mkpts1_f": mkpts1_f})
diff --git a/kornia/feature/loftr/utils/position_encoding.py b/kornia/feature/loftr/utils/position_encoding.py
index dd6991260..066d310c8 100644
--- a/kornia/feature/loftr/utils/position_encoding.py
+++ b/kornia/feature/loftr/utils/position_encoding.py
@@ -25,7 +25,7 @@ class PositionEncodingSine(Module):
self.temp_bug_fix = temp_bug_fix
pe = self._create_position_encoding(max_shape)
- self.register_buffer('pe', pe, persistent=False) # [1, C, H, W]
+ self.register_buffer("pe", pe, persistent=False) # [1, C, H, W]
def _create_position_encoding(self, max_shape: Tuple[int, int]) -> Tensor:
"""Creates a position encoding from scratch.
diff --git a/kornia/feature/loftr/utils/supervision.py b/kornia/feature/loftr/utils/supervision.py
index c4a4aba9d..f8f164bf4 100644
--- a/kornia/feature/loftr/utils/supervision.py
+++ b/kornia/feature/loftr/utils/supervision.py
@@ -40,12 +40,12 @@ def spvs_coarse(data: dict[str, Any], config: dict[str, Any]) -> None:
- for megadepth dataset, there're 4 kinds of resolution {i, i_resize, c, f}
"""
# 1. misc
- device = data['image0'].device
- N, _, H0, W0 = data['image0'].shape
- _, _, H1, W1 = data['image1'].shape
- scale = config['LOFTR']['RESOLUTION'][0]
- scale0 = scale * data['scale0'][:, None] if 'scale0' in data else scale
- scale1 = scale * data['scale1'][:, None] if 'scale0' in data else scale
+ device = data["image0"].device
+ N, _, H0, W0 = data["image0"].shape
+ _, _, H1, W1 = data["image1"].shape
+ scale = config["LOFTR"]["RESOLUTION"][0]
+ scale0 = scale * data["scale0"][:, None] if "scale0" in data else scale
+ scale1 = scale * data["scale1"][:, None] if "scale0" in data else scale
h0, w0, h1, w1 = (x // scale for x in [H0, W0, H1, W1])
# 2. warp grids
@@ -56,15 +56,15 @@ def spvs_coarse(data: dict[str, Any], config: dict[str, Any]) -> None:
grid_pt1_i = scale1 * grid_pt1_c
# mask padded region to (0, 0), so no need to manually mask conf_matrix_gt
- if 'mask0' in data:
- grid_pt0_i = mask_pts_at_padded_regions(grid_pt0_i, data['mask0'])
- grid_pt1_i = mask_pts_at_padded_regions(grid_pt1_i, data['mask1'])
+ if "mask0" in data:
+ grid_pt0_i = mask_pts_at_padded_regions(grid_pt0_i, data["mask0"])
+ grid_pt1_i = mask_pts_at_padded_regions(grid_pt1_i, data["mask1"])
# warp kpts bi-directionally and resize them to coarse-level resolution
# (no depth consistency check, since it leads to worse results experimentally)
# (unhandled edge case: points with 0-depth will be warped to the left-up corner)
- _, w_pt0_i = warp_kpts(grid_pt0_i, data['depth0'], data['depth1'], data['T_0to1'], data['K0'], data['K1'])
- _, w_pt1_i = warp_kpts(grid_pt1_i, data['depth1'], data['depth0'], data['T_1to0'], data['K1'], data['K0'])
+ _, w_pt0_i = warp_kpts(grid_pt0_i, data["depth0"], data["depth1"], data["T_0to1"], data["K0"], data["K1"])
+ _, w_pt1_i = warp_kpts(grid_pt1_i, data["depth1"], data["depth0"], data["T_1to0"], data["K1"], data["K0"])
w_pt0_c = w_pt0_i / scale1
w_pt1_c = w_pt1_i / scale0
@@ -91,7 +91,7 @@ def spvs_coarse(data: dict[str, Any], config: dict[str, Any]) -> None:
j_ids = nearest_index1[b_ids, i_ids]
conf_matrix_gt[b_ids, i_ids, j_ids] = 1
- data.update({'conf_matrix_gt': conf_matrix_gt})
+ data.update({"conf_matrix_gt": conf_matrix_gt})
# 5. save coarse matches(gt) for training fine level
if len(b_ids) == 0:
@@ -100,20 +100,20 @@ def spvs_coarse(data: dict[str, Any], config: dict[str, Any]) -> None:
i_ids = torch.tensor([0], device=device)
j_ids = torch.tensor([0], device=device)
- data.update({'spv_b_ids': b_ids, 'spv_i_ids': i_ids, 'spv_j_ids': j_ids})
+ data.update({"spv_b_ids": b_ids, "spv_i_ids": i_ids, "spv_j_ids": j_ids})
# 6. save intermediate results (for fast fine-level computation)
- data.update({'spv_w_pt0_i': w_pt0_i, 'spv_pt1_i': grid_pt1_i})
+ data.update({"spv_w_pt0_i": w_pt0_i, "spv_pt1_i": grid_pt1_i})
def compute_supervision_coarse(data: dict[str, Any], config: dict[str, Any]) -> None:
- if len(set(data['dataset_name'])) != 1:
+ if len(set(data["dataset_name"])) != 1:
raise ValueError("Do not support mixed datasets training!")
- data_source = data['dataset_name'][0]
- if data_source.lower() in ['scannet', 'megadepth']:
+ data_source = data["dataset_name"][0]
+ if data_source.lower() in ["scannet", "megadepth"]:
spvs_coarse(data, config)
else:
- raise ValueError(f'Unknown data source: {data_source}')
+ raise ValueError(f"Unknown data source: {data_source}")
# Fine-Level supervision
@@ -126,23 +126,23 @@ def spvs_fine(data: dict[str, Any], config: dict[str, Any]) -> None:
"""
# 1. misc
# w_pt0_i, pt1_i = data.pop('spv_w_pt0_i'), data.pop('spv_pt1_i')
- w_pt0_i, pt1_i = data['spv_w_pt0_i'], data['spv_pt1_i']
- scale = config['LOFTR']['RESOLUTION'][1]
- radius = config['LOFTR']['FINE_WINDOW_SIZE'] // 2
+ w_pt0_i, pt1_i = data["spv_w_pt0_i"], data["spv_pt1_i"]
+ scale = config["LOFTR"]["RESOLUTION"][1]
+ radius = config["LOFTR"]["FINE_WINDOW_SIZE"] // 2
# 2. get coarse prediction
- b_ids, i_ids, j_ids = data['b_ids'], data['i_ids'], data['j_ids']
+ b_ids, i_ids, j_ids = data["b_ids"], data["i_ids"], data["j_ids"]
# 3. compute gt
- scale = scale * data['scale1'][b_ids] if 'scale0' in data else scale
+ scale = scale * data["scale1"][b_ids] if "scale0" in data else scale
# `expec_f_gt` might exceed the window, i.e. abs(*) > 1, which would be filtered later
expec_f_gt = (w_pt0_i[b_ids, i_ids] - pt1_i[b_ids, j_ids]) / scale / radius # [M, 2]
data.update({"expec_f_gt": expec_f_gt})
def compute_supervision_fine(data: dict[str, Any], config: dict[str, Any]) -> None:
- data_source = data['dataset_name'][0]
- if data_source.lower() in ['scannet', 'megadepth']:
+ data_source = data["dataset_name"][0]
+ if data_source.lower() in ["scannet", "megadepth"]:
spvs_fine(data, config)
else:
raise NotImplementedError
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index f0109f87b..2e83a8e47 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -298,10 +298,10 @@ class DescriptorMatcher(Module):
th: threshold on distance ratio, or other quality measure.
"""
- def __init__(self, match_mode: str = 'snn', th: float = 0.8) -> None:
+ def __init__(self, match_mode: str = "snn", th: float = 0.8) -> None:
super().__init__()
_match_mode: str = match_mode.lower()
- self.known_modes = ['nn', 'mnn', 'snn', 'smnn']
+ self.known_modes = ["nn", "mnn", "snn", "smnn"]
if _match_mode not in self.known_modes:
raise NotImplementedError(f"{match_mode} is not supported. Try one of {self.known_modes}")
self.match_mode = _match_mode
@@ -320,13 +320,13 @@ class DescriptorMatcher(Module):
- Long tensor indexes of matching descriptors in desc1 and desc2,
shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
"""
- if self.match_mode == 'nn':
+ if self.match_mode == "nn":
out = match_nn(desc1, desc2)
- elif self.match_mode == 'mnn':
+ elif self.match_mode == "mnn":
out = match_mnn(desc1, desc2)
- elif self.match_mode == 'snn':
+ elif self.match_mode == "snn":
out = match_snn(desc1, desc2, self.th)
- elif self.match_mode == 'smnn':
+ elif self.match_mode == "smnn":
out = match_smnn(desc1, desc2, self.th)
else:
raise NotImplementedError
@@ -344,9 +344,9 @@ class GeometryAwareDescriptorMatcher(Module):
th: threshold on distance ratio, or other quality measure.
"""
- known_modes: ClassVar[List[str]] = ['fginn', "adalam"]
+ known_modes: ClassVar[List[str]] = ["fginn", "adalam"]
- def __init__(self, match_mode: str = 'fginn', params: Dict[str, Tensor] = {}) -> None:
+ def __init__(self, match_mode: str = "fginn", params: Dict[str, Tensor] = {}) -> None:
super().__init__()
_match_mode: str = match_mode.lower()
if _match_mode not in self.known_modes:
@@ -367,11 +367,11 @@ class GeometryAwareDescriptorMatcher(Module):
- Long tensor indexes of matching descriptors in desc1 and desc2,
shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
"""
- if self.match_mode == 'fginn':
+ if self.match_mode == "fginn":
params = _get_default_fginn_params()
params.update(self.params)
- out = match_fginn(desc1, desc2, lafs1, lafs2, params['th'], params['spatial_th'], params['mutual'])
- elif self.match_mode == 'adalam':
+ out = match_fginn(desc1, desc2, lafs1, lafs2, params["th"], params["spatial_th"], params["mutual"])
+ elif self.match_mode == "adalam":
_params = get_adalam_default_config()
_params.update(self.params) # type: ignore[typeddict-item]
out = match_adalam(desc1, desc2, lafs1, lafs2, config=_params)
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index 383fff6de..85839af32 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -16,11 +16,11 @@ sqrt2: float = 1.4142135623730951
COEFFS_N1_K1: List[float] = [0.38214156, 0.48090413]
COEFFS_N2_K8: List[float] = [0.14343168, 0.268285, 0.21979234]
COEFFS_N3_K8: List[float] = [0.14343168, 0.268285, 0.21979234, 0.15838885]
-COEFFS: Dict[str, List[float]] = {'xy': COEFFS_N1_K1, 'rhophi': COEFFS_N2_K8, 'theta': COEFFS_N3_K8}
+COEFFS: Dict[str, List[float]] = {"xy": COEFFS_N1_K1, "rhophi": COEFFS_N2_K8, "theta": COEFFS_N3_K8}
urls: Dict[str, str] = {
- k: f'https://github.com/manyids2/mkd_pytorch/raw/master/mkd_pytorch/mkd-{k}-64.pth'
- for k in ['cart', 'polar', 'concat']
+ k: f"https://github.com/manyids2/mkd_pytorch/raw/master/mkd_pytorch/mkd-{k}-64.pth"
+ for k in ["cart", "polar", "concat"]
}
@@ -30,7 +30,7 @@ def get_grid_dict(patch_size: int = 32) -> Dict[str, Tensor]:
x = kgrid[0, :, :, 0]
y = kgrid[0, :, :, 1]
rho, phi = cart2pol(x, y)
- grid_dict = {'x': x, 'y': y, 'rho': rho, 'phi': phi}
+ grid_dict = {"x": x, "y": y, "rho": rho, "phi": phi}
return grid_dict
@@ -71,7 +71,7 @@ class MKDGradients(nn.Module):
super().__init__()
self.eps = 1e-8
- self.grad = SpatialGradient(mode='diff', order=1, normalized=False)
+ self.grad = SpatialGradient(mode="diff", order=1, normalized=False)
def forward(self, x: Tensor) -> Tensor:
if not isinstance(x, Tensor):
@@ -117,7 +117,7 @@ class VonMisesKernel(nn.Module):
self.patch_size = patch_size
b_coeffs = tensor(coeffs)
- self.register_buffer('coeffs', b_coeffs)
+ self.register_buffer("coeffs", b_coeffs)
# Compute parameters.
n = len(coeffs) - 1
@@ -132,9 +132,9 @@ class VonMisesKernel(nn.Module):
weights[: n + 1] = torch.sqrt(b_coeffs)
weights[n + 1 :] = torch.sqrt(b_coeffs[1:])
weights = weights.reshape(-1, 1, 1)
- self.register_buffer('emb0', emb0)
- self.register_buffer('frange', frange)
- self.register_buffer('weights', weights)
+ self.register_buffer("emb0", emb0)
+ self.register_buffer("frange", frange)
+ self.register_buffer("weights", weights)
def forward(self, x: Tensor) -> Tensor:
if not isinstance(x, Tensor):
@@ -186,12 +186,12 @@ class EmbedGradients(nn.Module):
self.eps = 1e-8
# Theta kernel for gradients.
- self.kernel = VonMisesKernel(patch_size=patch_size, coeffs=COEFFS['theta'])
+ self.kernel = VonMisesKernel(patch_size=patch_size, coeffs=COEFFS["theta"])
# Relative gradients.
kgrid = create_meshgrid(height=patch_size, width=patch_size, normalized_coordinates=True)
_, phi = cart2pol(kgrid[:, :, :, 0], kgrid[:, :, :, 1])
- self.register_buffer('phi', phi)
+ self.register_buffer("phi", phi)
def emb_mags(self, mags: Tensor) -> Tensor:
"""Embed square roots of magnitudes with eps for numerical reasons."""
@@ -217,12 +217,12 @@ class EmbedGradients(nn.Module):
def spatial_kernel_embedding(kernel_type: str, grids: Dict[str, Tensor]) -> Tensor:
r"""Compute embeddings for cartesian and polar parametrizations."""
factors = {"phi": 1.0, "rho": pi / sqrt2, "x": pi / 2, "y": pi / 2}
- if kernel_type == 'cart':
- coeffs_ = 'xy'
- params_ = ['x', 'y']
- elif kernel_type == 'polar':
- coeffs_ = 'rhophi'
- params_ = ['phi', 'rho']
+ if kernel_type == "cart":
+ coeffs_ = "xy"
+ params_ = ["x", "y"]
+ elif kernel_type == "polar":
+ coeffs_ = "rhophi"
+ params_ = ["phi", "rho"]
# Infer patch_size.
keys = list(grids.keys())
@@ -274,7 +274,7 @@ class ExplicitSpacialEncoding(nn.Module):
def __init__(
self,
- kernel_type: str = 'polar',
+ kernel_type: str = "polar",
fmap_size: int = 32,
in_dims: int = 7,
do_gmask: bool = True,
@@ -282,8 +282,8 @@ class ExplicitSpacialEncoding(nn.Module):
) -> None:
super().__init__()
- if kernel_type not in ['polar', 'cart']:
- raise NotImplementedError(f'{kernel_type} is not valid, use polar or cart).')
+ if kernel_type not in ["polar", "cart"]:
+ raise NotImplementedError(f"{kernel_type} is not valid, use polar or cart).")
self.kernel_type = kernel_type
self.fmap_size = fmap_size
@@ -302,19 +302,19 @@ class ExplicitSpacialEncoding(nn.Module):
emb = emb * self.gmask
# Store precomputed embedding.
- self.register_buffer('emb', emb.unsqueeze(0))
+ self.register_buffer("emb", emb.unsqueeze(0))
self.d_emb: int = emb.shape[0]
self.out_dims: int = self.in_dims * self.d_emb
self.odims: int = self.out_dims
# Store kronecker form.
emb2, idx1 = self.init_kron()
- self.register_buffer('emb2', emb2)
- self.register_buffer('idx1', idx1)
+ self.register_buffer("emb2", emb2)
+ self.register_buffer("idx1", idx1)
def get_gmask(self, sigma: float) -> Tensor:
"""Compute Gaussian mask."""
- norm_rho = self.grid['rho'] / self.grid['rho'].max()
+ norm_rho = self.grid["rho"] / self.grid["rho"].max()
gmask = torch.exp(-1 * norm_rho**2 / sigma**2)
return gmask
@@ -340,13 +340,13 @@ class ExplicitSpacialEncoding(nn.Module):
def __repr__(self) -> str:
return (
- f'{self.__class__.__name__}('
- f'kernel_type={self.kernel_type}, '
- f'fmap_size={self.fmap_size}, '
- f'in_dims={self.in_dims}, '
- f'out_dims={self.out_dims}, '
- f'do_gmask={self.do_gmask}, '
- f'do_l2={self.do_l2})'
+ f"{self.__class__.__name__}("
+ f"kernel_type={self.kernel_type}, "
+ f"fmap_size={self.fmap_size}, "
+ f"in_dims={self.in_dims}, "
+ f"out_dims={self.out_dims}, "
+ f"do_gmask={self.do_gmask}, "
+ f"do_l2={self.do_l2})"
)
@@ -415,17 +415,17 @@ class Whitening(nn.Module):
self.load_whitening_parameters(whitening_model)
def load_whitening_parameters(self, whitening_model: Dict[str, Dict[str, Tensor]]) -> None:
- algo = 'lw' if self.xform == 'lw' else 'pca'
+ algo = "lw" if self.xform == "lw" else "pca"
wh_model = whitening_model[algo]
- self.mean.data = wh_model['mean']
- self.evecs.data = wh_model['eigvecs'][:, : self.output_dims]
- self.evals.data = wh_model['eigvals'][: self.output_dims]
+ self.mean.data = wh_model["mean"]
+ self.evecs.data = wh_model["eigvecs"][:, : self.output_dims]
+ self.evals.data = wh_model["eigvals"][: self.output_dims]
modifications = {
- 'pca': self._modify_pca,
- 'lw': self._modify_lw,
- 'pcaws': self._modify_pcaws,
- 'pcawt': self._modify_pcawt,
+ "pca": self._modify_pca,
+ "lw": self._modify_lw,
+ "pcaws": self._modify_pcaws,
+ "pcawt": self._modify_pcawt,
}
# Call modification.
@@ -460,7 +460,7 @@ class Whitening(nn.Module):
return F.normalize(x, dim=1)
def __repr__(self) -> str:
- return f'{self.__class__.__name__}(xform={self.xform}, in_dims={self.in_dims}, output_dims={self.output_dims})'
+ return f"{self.__class__.__name__}(xform={self.xform}, in_dims={self.in_dims}, output_dims={self.output_dims})"
class MKDDescriptor(nn.Module):
@@ -496,9 +496,9 @@ class MKDDescriptor(nn.Module):
def __init__(
self,
patch_size: int = 32,
- kernel_type: str = 'concat',
- whitening: str = 'pcawt',
- training_set: str = 'liberty',
+ kernel_type: str = "concat",
+ whitening: str = "pcawt",
+ training_set: str = "liberty",
output_dims: int = 128,
) -> None:
super().__init__()
@@ -509,12 +509,12 @@ class MKDDescriptor(nn.Module):
self.training_set: str = training_set
self.sigma = 1.4 * (patch_size / 64)
- self.smoothing = GaussianBlur2d((5, 5), (self.sigma, self.sigma), 'replicate')
+ self.smoothing = GaussianBlur2d((5, 5), (self.sigma, self.sigma), "replicate")
self.gradients = MKDGradients()
# This stupid thing needed for jitting...
- polar_s: str = 'polar'
- cart_s: str = 'cart'
- self.parametrizations = [polar_s, cart_s] if self.kernel_type == 'concat' else [self.kernel_type]
+ polar_s: str = "polar"
+ cart_s: str = "cart"
+ self.parametrizations = [polar_s, cart_s] if self.kernel_type == "concat" else [self.kernel_type]
# Initialize cartesian/polar embedding with absolute/relative gradients.
self.odims: int = 0
@@ -572,12 +572,12 @@ class MKDDescriptor(nn.Module):
def __repr__(self) -> str:
return (
- f'{self.__class__.__name__}('
- f'patch_size={self.patch_size}, '
- f'kernel_type={self.kernel_type}, '
- f'whitening={self.whitening}, '
- f'training_set={self.training_set}, '
- f'output_dims={self.output_dims})'
+ f"{self.__class__.__name__}("
+ f"patch_size={self.patch_size}, "
+ f"kernel_type={self.kernel_type}, "
+ f"whitening={self.whitening}, "
+ f"training_set={self.training_set}, "
+ f"output_dims={self.output_dims})"
)
@@ -593,18 +593,18 @@ class SimpleKD(nn.Module):
def __init__(
self,
patch_size: int = 32,
- kernel_type: str = 'polar', # 'cart' 'polar'
- whitening: str = 'pcawt', # 'lw', 'pca', 'pcaws', 'pcawt
- training_set: str = 'liberty', # 'liberty', 'notredame', 'yosemite'
+ kernel_type: str = "polar", # 'cart' 'polar'
+ whitening: str = "pcawt", # 'lw', 'pca', 'pcaws', 'pcawt
+ training_set: str = "liberty", # 'liberty', 'notredame', 'yosemite'
output_dims: int = 128,
) -> None:
super().__init__()
- relative: bool = kernel_type == 'polar'
+ relative: bool = kernel_type == "polar"
sigma: float = 1.4 * (patch_size / 64)
self.patch_size = patch_size
# Sequence of modules.
- smoothing = GaussianBlur2d((5, 5), (sigma, sigma), 'replicate')
+ smoothing = GaussianBlur2d((5, 5), (sigma, sigma), "replicate")
gradients = MKDGradients()
ori = EmbedGradients(patch_size=patch_size, relative=relative)
ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=patch_size, in_dims=ori.kernel.d)
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index 7b237f99f..05c2361fd 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -46,7 +46,7 @@ class PatchDominantGradientOrientation(nn.Module):
super().__init__()
self.patch_size = patch_size
self.num_ang_bins = num_angular_bins
- self.gradient = SpatialGradient('sobel', 1)
+ self.gradient = SpatialGradient("sobel", 1)
self.eps = eps
self.angular_smooth = nn.Conv1d(1, 1, kernel_size=5, padding=2, bias=False, padding_mode="circular")
with torch.no_grad():
@@ -56,7 +56,7 @@ class PatchDominantGradientOrientation(nn.Module):
def __repr__(self) -> str:
return (
- f'{self.__class__.__name__}(patch_size={self.patch_size}, num_ang_bins={self.num_ang_bins}, eps={self.eps})'
+ f"{self.__class__.__name__}(patch_size={self.patch_size}, num_ang_bins={self.num_ang_bins}, eps={self.eps})"
)
def forward(self, patch: torch.Tensor) -> torch.Tensor:
@@ -162,8 +162,8 @@ class OriNet(nn.Module):
self.eps = eps
# use torch.hub to load pretrained model
if pretrained:
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['orinet'], map_location=map_location_to_cpu)
- self.load_state_dict(pretrained_dict['state_dict'], strict=False)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls["orinet"], map_location=map_location_to_cpu)
+ self.load_state_dict(pretrained_dict["state_dict"], strict=False)
self.eval()
@staticmethod
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index f1bd1e0f7..7f263182e 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -20,7 +20,7 @@ def _get_kernel_size(sigma: float) -> int:
def harris_response(
- input: Tensor, k: Union[Tensor, float] = 0.04, grads_mode: str = 'sobel', sigmas: Optional[Tensor] = None
+ input: Tensor, k: Union[Tensor, float] = 0.04, grads_mode: str = "sobel", sigmas: Optional[Tensor] = None
) -> Tensor:
r"""Compute the Harris cornerness function.
@@ -105,7 +105,7 @@ def harris_response(
return scores
-def gftt_response(input: Tensor, grads_mode: str = 'sobel', sigmas: Optional[Tensor] = None) -> Tensor:
+def gftt_response(input: Tensor, grads_mode: str = "sobel", sigmas: Optional[Tensor] = None) -> Tensor:
r"""Compute the Shi-Tomasi cornerness function.
.. image:: _static/img/gftt_response.png
@@ -179,7 +179,7 @@ def gftt_response(input: Tensor, grads_mode: str = 'sobel', sigmas: Optional[Ten
return scores
-def hessian_response(input: Tensor, grads_mode: str = 'sobel', sigmas: Optional[Tensor] = None) -> Tensor:
+def hessian_response(input: Tensor, grads_mode: str = "sobel", sigmas: Optional[Tensor] = None) -> Tensor:
r"""Compute the absolute of determinant of the Hessian matrix.
.. image:: _static/img/hessian_response.png
@@ -321,7 +321,7 @@ class BlobDoGSingle(Module):
self.sigma2 = sigma2
def __repr__(self) -> str:
- return f'{self.__class__.__name__}, sigma1={self.sigma1}, sigma2={self.sigma2})'
+ return f"{self.__class__.__name__}, sigma1={self.sigma1}, sigma2={self.sigma2})"
def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
return dog_response_single(input, self.sigma1, self.sigma2)
@@ -334,18 +334,19 @@ class CornerHarris(Module):
See :func:`~kornia.feature.harris_response` for details.
"""
+
k: Tensor
- def __init__(self, k: Union[float, Tensor], grads_mode: str = 'sobel') -> None:
+ def __init__(self, k: Union[float, Tensor], grads_mode: str = "sobel") -> None:
super().__init__()
if isinstance(k, float):
- self.register_buffer('k', tensor(k))
+ self.register_buffer("k", tensor(k))
else:
- self.register_buffer('k', k)
+ self.register_buffer("k", k)
self.grads_mode: str = grads_mode
def __repr__(self) -> str:
- return f'{self.__class__.__name__}(k={self.k}, grads_mode={self.grads_mode})'
+ return f"{self.__class__.__name__}(k={self.k}, grads_mode={self.grads_mode})"
def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
return harris_response(input, self.k, self.grads_mode, sigmas)
@@ -359,12 +360,12 @@ class CornerGFTT(Module):
See :func:`~kornia.feature.gftt_response` for details.
"""
- def __init__(self, grads_mode: str = 'sobel') -> None:
+ def __init__(self, grads_mode: str = "sobel") -> None:
super().__init__()
self.grads_mode: str = grads_mode
def __repr__(self) -> str:
- return f'{self.__class__.__name__}(grads_mode={self.grads_mode})'
+ return f"{self.__class__.__name__}(grads_mode={self.grads_mode})"
def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
return gftt_response(input, self.grads_mode, sigmas)
@@ -378,12 +379,12 @@ class BlobHessian(Module):
See :func:`~kornia.feature.hessian_response` for details.
"""
- def __init__(self, grads_mode: str = 'sobel') -> None:
+ def __init__(self, grads_mode: str = "sobel") -> None:
super().__init__()
self.grads_mode: str = grads_mode
def __repr__(self) -> str:
- return f'{self.__class__.__name__}(grads_mode={self.grads_mode})'
+ return f"{self.__class__.__name__}(grads_mode={self.grads_mode})"
def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
return hessian_response(input, self.grads_mode, sigmas)
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index a232efc94..c685e8093 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -44,7 +44,7 @@ def _scale_index_to_scale(max_coords: Tensor, sigmas: Tensor, num_levels: int) -
def _create_octave_mask(mask: Tensor, octave_shape: List[int]) -> Tensor:
r"""Downsample a mask based on the given octave shape."""
mask_shape = octave_shape[-2:]
- mask_octave = F.interpolate(mask, mask_shape, mode='bilinear', align_corners=False)
+ mask_octave = F.interpolate(mask, mask_shape, mode="bilinear", align_corners=False)
return mask_octave.unsqueeze(1)
@@ -172,8 +172,8 @@ class ScaleSpaceDetector(Module):
num_levels = self.scale_pyr.n_levels
else:
raise TypeError(
- 'Expected the scale pyramid module to have `n_levels` as a Tensor or int.'
- f'Gotcha {type(self.scale_pyr.n_levels)}'
+ "Expected the scale pyramid module to have `n_levels` as a Tensor or int."
+ f"Gotcha {type(self.scale_pyr.n_levels)}"
)
max_coords_best = _scale_index_to_scale(max_coords_best, sigmas_oct, num_levels)
@@ -236,11 +236,11 @@ class Detector_config(TypedDict):
def get_default_detector_config() -> Detector_config:
return {
# Extraction Parameters
- 'nms_size': 15,
- 'pyramid_levels': 4,
- 'up_levels': 1,
- 'scale_factor_levels': math.sqrt(2),
- 's_mult': 22.0,
+ "nms_size": 15,
+ "pyramid_levels": 4,
+ "up_levels": 1,
+ "scale_factor_levels": math.sqrt(2),
+ "s_mult": 22.0,
}
@@ -272,11 +272,11 @@ class MultiResolutionDetector(Module):
super().__init__()
self.model = model
# Load extraction configuration
- self.num_pyramid_levels = config['pyramid_levels']
- self.num_upscale_levels = config['up_levels']
- self.scale_factor_levels = config['scale_factor_levels']
- self.mr_size = config['s_mult']
- self.nms_size = config['nms_size']
+ self.num_pyramid_levels = config["pyramid_levels"]
+ self.num_upscale_levels = config["up_levels"]
+ self.scale_factor_levels = config["scale_factor_levels"]
+ self.mr_size = config["s_mult"]
+ self.nms_size = config["nms_size"]
self.nms = NonMaximaSuppression2d((self.nms_size, self.nms_size))
self.num_features = num_features
@@ -342,7 +342,7 @@ class MultiResolutionDetector(Module):
up_factor = self.scale_factor_levels ** (1 + idx_level)
nh, nw = int(h * up_factor), int(w * up_factor)
up_factor_kpts = (float(w) / float(nw), float(h) / float(nh))
- img_up = resize(img_up, (nh, nw), interpolation='bilinear', align_corners=False)
+ img_up = resize(img_up, (nh, nw), interpolation="bilinear", align_corners=False)
cur_scores, cur_lafs = self.detect_features_on_single_level(img_up, num_points_level, up_factor_kpts)
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index f3eb85d33..d9deccb78 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -132,7 +132,7 @@ class SIFTDescriptor(Module):
B: int = input.shape[0]
self.pk = self.pk.to(input.dtype).to(input.device)
- grads = spatial_gradient(input, 'diff')
+ grads = spatial_gradient(input, "diff")
# unpack the edges
gx = grads[:, :, 0]
gy = grads[:, :, 1]
@@ -209,13 +209,13 @@ class DenseSIFTDescriptor(Module):
def __repr__(self) -> str:
return (
- f'{self.__class__.__name__}('
- f'num_ang_bins={self.num_ang_bins}, '
- f'num_spatial_bins={self.num_spatial_bins}, '
- f'spatial_bin_size={self.spatial_bin_size}, '
- f'rootsift={self.rootsift}, '
- f'stride={self.stride}, '
- f'clipval={self.clipval})'
+ f"{self.__class__.__name__}("
+ f"num_ang_bins={self.num_ang_bins}, "
+ f"num_spatial_bins={self.num_spatial_bins}, "
+ f"spatial_bin_size={self.spatial_bin_size}, "
+ f"rootsift={self.rootsift}, "
+ f"stride={self.stride}, "
+ f"clipval={self.clipval})"
)
def __init__(
@@ -268,7 +268,7 @@ class DenseSIFTDescriptor(Module):
B, CH, W, H = input.size()
self.bin_pooling_kernel = self.bin_pooling_kernel.to(input.dtype).to(input.device)
self.PoolingConv = self.PoolingConv.to(input.dtype).to(input.device)
- grads = spatial_gradient(input, 'diff')
+ grads = spatial_gradient(input, "diff")
# unpack the edges
gx = grads[:, :, 0]
gy = grads[:, :, 1]
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index f5870e118..8958064c0 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -16,35 +16,35 @@ urls["wireframe"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pt
default_cfg: Dict[str, Any] = {
- 'backbone_cfg': {'input_channel': 1, 'depth': 4, 'num_stacks': 2, 'num_blocks': 1, 'num_classes': 5},
- 'use_descriptor': True,
- 'grid_size': 8,
- 'keep_border_valid': True,
- 'detection_thresh': 0.0153846, # = 1/65: threshold of junction detection
- 'max_num_junctions': 500, # maximum number of junctions per image
- 'line_detector_cfg': {
- 'detect_thresh': 0.5,
- 'num_samples': 64,
- 'inlier_thresh': 0.99,
- 'use_candidate_suppression': True,
- 'nms_dist_tolerance': 3.0,
- 'use_heatmap_refinement': True,
- 'heatmap_refine_cfg': {
- 'mode': "local",
- 'ratio': 0.2,
- 'valid_thresh': 0.001,
- 'num_blocks': 20,
- 'overlap_ratio': 0.5,
+ "backbone_cfg": {"input_channel": 1, "depth": 4, "num_stacks": 2, "num_blocks": 1, "num_classes": 5},
+ "use_descriptor": True,
+ "grid_size": 8,
+ "keep_border_valid": True,
+ "detection_thresh": 0.0153846, # = 1/65: threshold of junction detection
+ "max_num_junctions": 500, # maximum number of junctions per image
+ "line_detector_cfg": {
+ "detect_thresh": 0.5,
+ "num_samples": 64,
+ "inlier_thresh": 0.99,
+ "use_candidate_suppression": True,
+ "nms_dist_tolerance": 3.0,
+ "use_heatmap_refinement": True,
+ "heatmap_refine_cfg": {
+ "mode": "local",
+ "ratio": 0.2,
+ "valid_thresh": 0.001,
+ "num_blocks": 20,
+ "overlap_ratio": 0.5,
},
- 'use_junction_refinement': True,
- 'junction_refine_cfg': {'num_perturbs': 9, 'perturb_interval': 0.25},
+ "use_junction_refinement": True,
+ "junction_refine_cfg": {"num_perturbs": 9, "perturb_interval": 0.25},
},
- 'line_matcher_cfg': {
- 'cross_check': True,
- 'num_samples': 5,
- 'min_dist_pts': 8,
- 'top_k_candidates': 10,
- 'grid_size': 4,
+ "line_matcher_cfg": {
+ "cross_check": True,
+ "num_samples": 5,
+ "min_dist_pts": 8,
+ "top_k_candidates": 10,
+ "grid_size": 4,
},
}
@@ -87,7 +87,7 @@ class SOLD2(Module):
self.model = SOLD2Net(self.config)
if pretrained:
pretrained_dict = torch.hub.load_state_dict_from_url(urls["wireframe"], map_location=map_location_to_cpu)
- state_dict = self.adapt_state_dict(pretrained_dict['model_state_dict'])
+ state_dict = self.adapt_state_dict(pretrained_dict["model_state_dict"])
self.model.load_state_dict(state_dict)
self.eval()
@@ -242,7 +242,7 @@ class WunschLineMatcher(Module):
# Sample the points separated by at least min_dist_pts along each line
# The number of samples depends on the length of the line
num_samples_lst = torch.clamp(
- torch.div(line_lengths, self.min_dist_pts, rounding_mode='floor'), 2, self.num_samples
+ torch.div(line_lengths, self.min_dist_pts, rounding_mode="floor"), 2, self.num_samples
).int()
line_points = torch.empty((num_lines, self.num_samples, 2), dtype=torch.float, device=dev)
valid_points = torch.empty((num_lines, self.num_samples), dtype=torch.bool, device=dev)
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index 3083192a0..33b14cfc5 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -15,28 +15,28 @@ urls["wireframe"] = "https://www.polybox.ethz.ch/index.php/s/blOrW89gqSLoHOk/dow
default_detector_cfg = {
- 'backbone_cfg': {'input_channel': 1, 'depth': 4, 'num_stacks': 2, 'num_blocks': 1, 'num_classes': 5},
- 'use_descriptor': False,
- 'grid_size': 8,
- 'keep_border_valid': True,
- 'detection_thresh': 0.0153846, # = 1/65: threshold of junction detection
- 'max_num_junctions': 500, # maximum number of junctions per image
- 'line_detector_cfg': {
- 'detect_thresh': 0.5,
- 'num_samples': 64,
- 'inlier_thresh': 0.99,
- 'use_candidate_suppression': True,
- 'nms_dist_tolerance': 3.0,
- 'use_heatmap_refinement': True,
- 'heatmap_refine_cfg': {
- 'mode': "local",
- 'ratio': 0.2,
- 'valid_thresh': 0.001,
- 'num_blocks': 20,
- 'overlap_ratio': 0.5,
+ "backbone_cfg": {"input_channel": 1, "depth": 4, "num_stacks": 2, "num_blocks": 1, "num_classes": 5},
+ "use_descriptor": False,
+ "grid_size": 8,
+ "keep_border_valid": True,
+ "detection_thresh": 0.0153846, # = 1/65: threshold of junction detection
+ "max_num_junctions": 500, # maximum number of junctions per image
+ "line_detector_cfg": {
+ "detect_thresh": 0.5,
+ "num_samples": 64,
+ "inlier_thresh": 0.99,
+ "use_candidate_suppression": True,
+ "nms_dist_tolerance": 3.0,
+ "use_heatmap_refinement": True,
+ "heatmap_refine_cfg": {
+ "mode": "local",
+ "ratio": 0.2,
+ "valid_thresh": 0.001,
+ "num_blocks": 20,
+ "overlap_ratio": 0.5,
},
- 'use_junction_refinement': True,
- 'junction_refine_cfg': {'num_perturbs': 9, 'perturb_interval': 0.25},
+ "use_junction_refinement": True,
+ "junction_refine_cfg": {"num_perturbs": 9, "perturb_interval": 0.25},
},
}
@@ -73,7 +73,7 @@ class SOLD2_detector(Module):
self.model = SOLD2Net(self.config)
if pretrained:
pretrained_dict = torch.hub.load_state_dict_from_url(urls["wireframe"], map_location=map_location_to_cpu)
- state_dict = self.adapt_state_dict(pretrained_dict['model_state_dict'])
+ state_dict = self.adapt_state_dict(pretrained_dict["model_state_dict"])
self.model.load_state_dict(state_dict)
self.eval()
@@ -366,11 +366,11 @@ class LineSegmentDetectionModule:
cand_vecs = junctions[None, ...] - start_points.unsqueeze(dim=1)
cand_vecs_norm = torch.norm(cand_vecs, dim=-1)
# Check whether they are projected directly onto the segment
- proj = torch.einsum('bij,bjk->bik', cand_vecs, dir_vecs[..., None]) / line_dists[..., None, None]
+ proj = torch.einsum("bij,bjk->bik", cand_vecs, dir_vecs[..., None]) / line_dists[..., None, None]
# proj is num_segs x num_junction x 1
proj_mask = (proj >= 0) * (proj <= 1)
cand_angles = torch.acos(
- torch.einsum('bij,bjk->bik', cand_vecs, dir_vecs[..., None]) / cand_vecs_norm[..., None]
+ torch.einsum("bij,bjk->bik", cand_vecs, dir_vecs[..., None]) / cand_vecs_norm[..., None]
)
cand_dists = cand_vecs_norm[..., None] * torch.sin(cand_angles)
junc_dist_mask = cand_dists <= dist_tolerance
@@ -394,7 +394,7 @@ class LineSegmentDetectionModule:
"""Refine the line endpoints in a similar way as in LSD."""
# Fetch refinement parameters
if not isinstance(self.junction_refine_cfg, dict):
- raise TypeError(f'Expected to have a dict of config for junction. Gotcha {type(self.junction_refine_cfg)}')
+ raise TypeError(f"Expected to have a dict of config for junction. Gotcha {type(self.junction_refine_cfg)}")
num_perturbs = self.junction_refine_cfg["num_perturbs"]
perturb_interval = self.junction_refine_cfg["perturb_interval"]
side_perturbs = (num_perturbs - 1) // 2
@@ -408,7 +408,7 @@ class LineSegmentDetectionModule:
)
h1_grid, w1_grid, h2_grid, w2_grid = torch_meshgrid(
- [perturb_vec, perturb_vec, perturb_vec, perturb_vec], indexing='ij'
+ [perturb_vec, perturb_vec, perturb_vec, perturb_vec], indexing="ij"
)
perturb_tensor = concatenate(
diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.py
index 7d13bfa86..0d715dc21 100644
--- a/kornia/feature/sosnet.py
+++ b/kornia/feature/sosnet.py
@@ -29,6 +29,7 @@ class SOSNet(nn.Module):
>>> sosnet = SOSNet()
>>> descs = sosnet(input) # 8x128
"""
+
patch_size = 32
def __init__(self, pretrained: bool = False) -> None:
@@ -60,7 +61,7 @@ class SOSNet(nn.Module):
self.desc_norm = nn.Sequential(nn.LocalResponseNorm(256, alpha=256.0, beta=0.5, k=0.0))
# load pretrained model
if pretrained:
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['lib'], map_location=map_location_to_cpu)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls["lib"], map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
index 59a0549f3..6badd4ce6 100644
--- a/kornia/feature/tfeat.py
+++ b/kornia/feature/tfeat.py
@@ -8,12 +8,8 @@ from kornia.utils.helpers import map_location_to_cpu
urls: Dict[str, str] = {}
urls["liberty"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-liberty.params" # pylint: disable
-urls[
- "notredame"
-] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-notredame.params" # pylint: disable
-urls[
- "yosemite"
-] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-yosemite.params" # pylint: disable
+urls["notredame"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-notredame.params" # pylint: disable
+urls["yosemite"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-yosemite.params" # pylint: disable
class TFeat(nn.Module):
@@ -38,6 +34,7 @@ class TFeat(nn.Module):
>>> tfeat = TFeat()
>>> descs = tfeat(input) # 16x128
"""
+
patch_size = 32
def __init__(self, pretrained: bool = False) -> None:
@@ -53,7 +50,7 @@ class TFeat(nn.Module):
self.descr = nn.Sequential(nn.Linear(64 * 8 * 8, 128), nn.Tanh())
# use torch.hub to load pretrained model
if pretrained:
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty'], map_location=map_location_to_cpu)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls["liberty"], map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
diff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.py
index ae1d5d3db..ef9a7af91 100644
--- a/kornia/filters/bilateral.py
+++ b/kornia/filters/bilateral.py
@@ -15,24 +15,24 @@ def _bilateral_blur(
kernel_size: tuple[int, int] | int,
sigma_color: float | Tensor,
sigma_space: tuple[float, float] | Tensor,
- border_type: str = 'reflect',
- color_distance_type: str = 'l1',
+ border_type: str = "reflect",
+ color_distance_type: str = "l1",
) -> Tensor:
"Single implementation for both Bilateral Filter and Joint Bilateral Filter"
KORNIA_CHECK_IS_TENSOR(input)
- KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
if guidance is not None:
# NOTE: allow guidance and input having different number of channels
KORNIA_CHECK_IS_TENSOR(guidance)
- KORNIA_CHECK_SHAPE(guidance, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(guidance, ["B", "C", "H", "W"])
KORNIA_CHECK(
(guidance.shape[0] == input.shape[0]) and (guidance.shape[-2:] == input.shape[-2:]),
"guidance and input should have the same batch size and spatial dimensions",
)
if isinstance(sigma_color, Tensor):
- KORNIA_CHECK_SHAPE(sigma_color, ['B'])
+ KORNIA_CHECK_SHAPE(sigma_color, ["B"])
sigma_color = sigma_color.to(device=input.device, dtype=input.dtype).view(-1, 1, 1, 1, 1)
ky, kx = _unpack_2d_ks(kernel_size)
@@ -70,8 +70,8 @@ def bilateral_blur(
kernel_size: tuple[int, int] | int,
sigma_color: float | Tensor,
sigma_space: tuple[float, float] | Tensor,
- border_type: str = 'reflect',
- color_distance_type: str = 'l1',
+ border_type: str = "reflect",
+ color_distance_type: str = "l1",
) -> Tensor:
r"""Blur a tensor using a Bilateral filter.
@@ -114,8 +114,8 @@ def joint_bilateral_blur(
kernel_size: tuple[int, int] | int,
sigma_color: float | Tensor,
sigma_space: tuple[float, float] | Tensor,
- border_type: str = 'reflect',
- color_distance_type: str = 'l1',
+ border_type: str = "reflect",
+ color_distance_type: str = "l1",
) -> Tensor:
r"""Blur a tensor using a Joint Bilateral filter.
@@ -160,7 +160,7 @@ class _BilateralBlur(Module):
kernel_size: tuple[int, int] | int,
sigma_color: float | Tensor,
sigma_space: tuple[float, float] | Tensor,
- border_type: str = 'reflect',
+ border_type: str = "reflect",
color_distance_type: str = "l1",
) -> None:
super().__init__()
diff --git a/kornia/filters/blur.py b/kornia/filters/blur.py
index 5363a16b1..f2ae767ba 100644
--- a/kornia/filters/blur.py
+++ b/kornia/filters/blur.py
@@ -8,7 +8,7 @@ from .kernels import _unpack_2d_ks, get_box_kernel1d, get_box_kernel2d
def box_blur(
- input: Tensor, kernel_size: tuple[int, int] | int, border_type: str = 'reflect', separable: bool = False
+ input: Tensor, kernel_size: tuple[int, int] | int, border_type: str = "reflect", separable: bool = False
) -> Tensor:
r"""Blur an image using the box filter.
@@ -95,7 +95,7 @@ class BoxBlur(Module):
"""
def __init__(
- self, kernel_size: tuple[int, int] | int, border_type: str = 'reflect', separable: bool = False
+ self, kernel_size: tuple[int, int] | int, border_type: str = "reflect", separable: bool = False
) -> None:
super().__init__()
self.kernel_size = kernel_size
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index d9fe5f60e..372624457 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -14,7 +14,7 @@ __all__ = [
"EdgeAwareBlurPool2D",
"blur_pool2d",
"max_blur_pool2d",
- 'edge_aware_blur_pool2d',
+ "edge_aware_blur_pool2d",
]
@@ -200,7 +200,7 @@ def max_blur_pool2d(
tensor([[[[0.5625, 0.3125],
[0.3125, 0.8750]]]])
"""
- KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
kernel = get_pascal_kernel_2d(kernel_size, norm=True, device=input.device, dtype=input.dtype).repeat(
(input.shape[1], 1, 1, 1)
diff --git a/kornia/filters/canny.py b/kornia/filters/canny.py
index b75513493..c2830d889 100644
--- a/kornia/filters/canny.py
+++ b/kornia/filters/canny.py
@@ -53,14 +53,14 @@ def canny(
torch.Size([5, 1, 4, 4])
"""
KORNIA_CHECK_IS_TENSOR(input)
- KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
KORNIA_CHECK(
low_threshold <= high_threshold,
"Invalid input thresholds. low_threshold should be smaller than the high_threshold. Got: "
f"{low_threshold}>{high_threshold}",
)
- KORNIA_CHECK(0 < low_threshold < 1, f'Invalid low threshold. Should be in range (0, 1). Got: {low_threshold}')
- KORNIA_CHECK(0 < high_threshold < 1, f'Invalid high threshold. Should be in range (0, 1). Got: {high_threshold}')
+ KORNIA_CHECK(0 < low_threshold < 1, f"Invalid low threshold. Should be in range (0, 1). Got: {low_threshold}")
+ KORNIA_CHECK(0 < high_threshold < 1, f"Invalid high threshold. Should be in range (0, 1). Got: {high_threshold}")
device = input.device
dtype = input.dtype
@@ -186,9 +186,9 @@ class Canny(Module):
"Invalid input thresholds. low_threshold should be smaller than the high_threshold. Got: "
f"{low_threshold}>{high_threshold}",
)
- KORNIA_CHECK(0 < low_threshold < 1, f'Invalid low threshold. Should be in range (0, 1). Got: {low_threshold}')
+ KORNIA_CHECK(0 < low_threshold < 1, f"Invalid low threshold. Should be in range (0, 1). Got: {low_threshold}")
KORNIA_CHECK(
- 0 < high_threshold < 1, f'Invalid high threshold. Should be in range (0, 1). Got: {high_threshold}'
+ 0 < high_threshold < 1, f"Invalid high threshold. Should be in range (0, 1). Got: {high_threshold}"
)
# Gaussian blur parameters
@@ -205,13 +205,13 @@ class Canny(Module):
self.eps: float = eps
def __repr__(self) -> str:
- return ''.join(
+ return "".join(
(
- f'{type(self).__name__}(',
- ', '.join(
- f'{name}={getattr(self, name)}' for name in sorted(self.__dict__) if not name.startswith('_')
+ f"{type(self).__name__}(",
+ ", ".join(
+ f"{name}={getattr(self, name)}" for name in sorted(self.__dict__) if not name.startswith("_")
),
- ')',
+ ")",
)
)
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index 63b3567a8..3353afc33 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -64,12 +64,12 @@ class _DenseLayer(nn.Sequential):
super().__init__(
OrderedDict(
[
- ('relu1', nn.ReLU(inplace=True)),
- ('conv1', nn.Conv2d(input_features, out_features, kernel_size=3, stride=1, padding=2, bias=True)),
- ('norm1', nn.BatchNorm2d(out_features)),
- ('relu2', nn.ReLU(inplace=True)),
- ('conv2', nn.Conv2d(out_features, out_features, kernel_size=3, stride=1, bias=True)),
- ('norm2', nn.BatchNorm2d(out_features)),
+ ("relu1", nn.ReLU(inplace=True)),
+ ("conv1", nn.Conv2d(input_features, out_features, kernel_size=3, stride=1, padding=2, bias=True)),
+ ("norm1", nn.BatchNorm2d(out_features)),
+ ("relu2", nn.ReLU(inplace=True)),
+ ("conv2", nn.Conv2d(out_features, out_features, kernel_size=3, stride=1, bias=True)),
+ ("norm2", nn.BatchNorm2d(out_features)),
]
)
)
@@ -87,7 +87,7 @@ class _DenseBlock(nn.Sequential):
super().__init__()
for i in range(num_layers):
layer = _DenseLayer(input_features, out_features)
- self.add_module('denselayer%d' % (i + 1), layer)
+ self.add_module("denselayer%d" % (i + 1), layer)
input_features = out_features
def forward(self, x: list[Tensor]) -> list[Tensor]:
@@ -126,7 +126,7 @@ class UpConvBlock(Module):
def forward(self, x: Tensor, out_shape: list[int]) -> Tensor:
out = self.features(x)
if out.shape[-2:] != out_shape:
- out = F.interpolate(out, out_shape, mode='bilinear')
+ out = F.interpolate(out, out_shape, mode="bilinear")
return out
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 0df46c217..bf7372e43 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -7,9 +7,9 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK
from .kernels import normalize_kernel2d
-_VALID_BORDERS = {'constant', 'reflect', 'replicate', 'circular'}
-_VALID_PADDING = {'valid', 'same'}
-_VALID_BEHAVIOUR = {'conv', 'corr'}
+_VALID_BORDERS = {"constant", "reflect", "replicate", "circular"}
+_VALID_PADDING = {"valid", "same"}
+_VALID_BEHAVIOUR = {"conv", "corr"}
def _compute_padding(kernel_size: list[int]) -> list[int]:
@@ -38,10 +38,10 @@ def _compute_padding(kernel_size: list[int]) -> list[int]:
def filter2d(
input: Tensor,
kernel: Tensor,
- border_type: str = 'reflect',
+ border_type: str = "reflect",
normalized: bool = False,
- padding: str = 'same',
- behaviour: str = 'corr',
+ padding: str = "same",
+ behaviour: str = "corr",
) -> Tensor:
r"""Convolve a tensor with a 2d kernel.
@@ -85,25 +85,25 @@ def filter2d(
[0., 0., 0., 0., 0.]]]])
"""
KORNIA_CHECK_IS_TENSOR(input)
- KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
KORNIA_CHECK_IS_TENSOR(kernel)
- KORNIA_CHECK_SHAPE(kernel, ['B', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(kernel, ["B", "H", "W"])
KORNIA_CHECK(
str(border_type).lower() in _VALID_BORDERS,
- f'Invalid border, gotcha {border_type}. Expected one of {_VALID_BORDERS}',
+ f"Invalid border, gotcha {border_type}. Expected one of {_VALID_BORDERS}",
)
KORNIA_CHECK(
str(padding).lower() in _VALID_PADDING,
- f'Invalid padding mode, gotcha {padding}. Expected one of {_VALID_PADDING}',
+ f"Invalid padding mode, gotcha {padding}. Expected one of {_VALID_PADDING}",
)
KORNIA_CHECK(
str(behaviour).lower() in _VALID_BEHAVIOUR,
- f'Invalid padding mode, gotcha {behaviour}. Expected one of {_VALID_BEHAVIOUR}',
+ f"Invalid padding mode, gotcha {behaviour}. Expected one of {_VALID_BEHAVIOUR}",
)
# prepare kernel
b, c, h, w = input.shape
- if str(behaviour).lower() == 'conv':
+ if str(behaviour).lower() == "conv":
tmp_kernel = kernel.flip((-2, -1))[:, None, ...].to(device=input.device, dtype=input.dtype)
else:
tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
@@ -117,7 +117,7 @@ def filter2d(
height, width = tmp_kernel.shape[-2:]
# pad the input tensor
- if padding == 'same':
+ if padding == "same":
padding_shape: list[int] = _compute_padding([height, width])
input = pad(input, padding_shape, mode=border_type)
@@ -128,7 +128,7 @@ def filter2d(
# convolve the tensor with the kernel.
output = F.conv2d(input, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1)
- if padding == 'same':
+ if padding == "same":
out = output.view(b, c, h, w)
else:
out = output.view(b, c, h - height + 1, w - width + 1)
@@ -140,9 +140,9 @@ def filter2d_separable(
input: Tensor,
kernel_x: Tensor,
kernel_y: Tensor,
- border_type: str = 'reflect',
+ border_type: str = "reflect",
normalized: bool = False,
- padding: str = 'same',
+ padding: str = "same",
) -> Tensor:
r"""Convolve a tensor with two 1d kernels, in x and y directions.
@@ -190,7 +190,7 @@ def filter2d_separable(
return out
-def filter3d(input: Tensor, kernel: Tensor, border_type: str = 'replicate', normalized: bool = False) -> Tensor:
+def filter3d(input: Tensor, kernel: Tensor, border_type: str = "replicate", normalized: bool = False) -> Tensor:
r"""Convolve a tensor with a 3d kernel.
The function applies a given kernel to a tensor. The kernel is applied
@@ -251,13 +251,13 @@ def filter3d(input: Tensor, kernel: Tensor, border_type: str = 'replicate', norm
[0., 0., 0., 0., 0.]]]]])
"""
KORNIA_CHECK_IS_TENSOR(input)
- KORNIA_CHECK_SHAPE(input, ['B', 'C', 'D', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "D", "H", "W"])
KORNIA_CHECK_IS_TENSOR(kernel)
- KORNIA_CHECK_SHAPE(kernel, ['B', 'D', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(kernel, ["B", "D", "H", "W"])
KORNIA_CHECK(
str(border_type).lower() in _VALID_BORDERS,
- f'Invalid border, gotcha {border_type}. Expected one of {_VALID_BORDERS}',
+ f"Invalid border, gotcha {border_type}. Expected one of {_VALID_BORDERS}",
)
# prepare kernel
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index 7272fafda..d5ddddf52 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -14,7 +14,7 @@ def gaussian_blur2d(
input: Tensor,
kernel_size: tuple[int, int] | int,
sigma: tuple[float, float] | Tensor,
- border_type: str = 'reflect',
+ border_type: str = "reflect",
separable: bool = True,
) -> Tensor:
r"""Create an operator that blurs a tensor using a Gaussian filter.
@@ -104,7 +104,7 @@ class GaussianBlur2d(Module):
self,
kernel_size: tuple[int, int] | int,
sigma: tuple[float, float] | Tensor,
- border_type: str = 'reflect',
+ border_type: str = "reflect",
separable: bool = True,
) -> None:
super().__init__()
@@ -126,6 +126,6 @@ class GaussianBlur2d(Module):
return gaussian_blur2d(input, self.kernel_size, self.sigma, self.border_type, self.separable)
-@deprecated(replace_with='gaussian_blur2d', version='6.9.10')
+@deprecated(replace_with="gaussian_blur2d", version="6.9.10")
def gaussian_blur2d_t(*args: Any, **kwargs: Any) -> Tensor:
return gaussian_blur2d(*args, **kwargs)
diff --git a/kornia/filters/guided.py b/kornia/filters/guided.py
index 1e975f5af..e00fc1477 100644
--- a/kornia/filters/guided.py
+++ b/kornia/filters/guided.py
@@ -30,7 +30,7 @@ def _guided_blur_grayscale_guidance(
input: Tensor,
kernel_size: tuple[int, int] | int,
eps: float | Tensor,
- border_type: str = 'reflect',
+ border_type: str = "reflect",
subsample: int = 1,
) -> Tensor:
guidance_sub, input_sub, kernel_size = _preprocess_fast_guided_blur(guidance, input, kernel_size, subsample)
@@ -69,7 +69,7 @@ def _guided_blur_multichannel_guidance(
input: Tensor,
kernel_size: tuple[int, int] | int,
eps: float | Tensor,
- border_type: str = 'reflect',
+ border_type: str = "reflect",
subsample: int = 1,
) -> Tensor:
guidance_sub, input_sub, kernel_size = _preprocess_fast_guided_blur(guidance, input, kernel_size, subsample)
@@ -114,7 +114,7 @@ def guided_blur(
input: Tensor,
kernel_size: tuple[int, int] | int,
eps: float | Tensor,
- border_type: str = 'reflect',
+ border_type: str = "reflect",
subsample: int = 1,
) -> Tensor:
r"""Blur a tensor using a Guided filter.
@@ -146,10 +146,10 @@ def guided_blur(
"""
KORNIA_CHECK_IS_TENSOR(guidance)
- KORNIA_CHECK_SHAPE(guidance, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(guidance, ["B", "C", "H", "W"])
if input is not guidance:
KORNIA_CHECK_IS_TENSOR(input)
- KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
KORNIA_CHECK(
(guidance.shape[0] == input.shape[0]) and (guidance.shape[-2:] == input.shape[-2:]),
"guidance and input should have the same batch size and spatial dimensions",
@@ -192,7 +192,7 @@ class GuidedBlur(Module):
"""
def __init__(
- self, kernel_size: tuple[int, int] | int, eps: float, border_type: str = 'reflect', subsample: int = 1
+ self, kernel_size: tuple[int, int] | int, eps: float, border_type: str = "reflect", subsample: int = 1
) -> None:
super().__init__()
self.kernel_size = kernel_size
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 2639c0e39..8aeec36b0 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -15,11 +15,11 @@ def _check_kernel_size(kernel_size: tuple[int, ...] | int, min_value: int = 0, a
if isinstance(kernel_size, int):
kernel_size = (kernel_size,)
- fmt = 'even or odd' if allow_even else 'odd'
+ fmt = "even or odd" if allow_even else "odd"
for size in kernel_size:
KORNIA_CHECK(
isinstance(size, int) and (((size % 2 == 1) or allow_even) and size > min_value),
- f'Kernel size must be an {fmt} integer bigger than {min_value}. Gotcha {size} on {kernel_size}',
+ f"Kernel size must be an {fmt} integer bigger than {min_value}. Gotcha {size} on {kernel_size}",
)
@@ -27,7 +27,7 @@ def _unpack_2d_ks(kernel_size: tuple[int, int] | int) -> tuple[int, int]:
if isinstance(kernel_size, int):
ky = kx = kernel_size
else:
- KORNIA_CHECK(len(kernel_size) == 2, '2D Kernel size should have a length of 2.')
+ KORNIA_CHECK(len(kernel_size) == 2, "2D Kernel size should have a length of 2.")
ky, kx = kernel_size
ky = int(ky)
@@ -40,7 +40,7 @@ def _unpack_3d_ks(kernel_size: tuple[int, int, int] | int) -> tuple[int, int, in
if isinstance(kernel_size, int):
kz = ky = kx = kernel_size
else:
- KORNIA_CHECK(len(kernel_size) == 3, '3D Kernel size should have a length of 3.')
+ KORNIA_CHECK(len(kernel_size) == 3, "3D Kernel size should have a length of 3.")
kz, ky, kx = kernel_size
kz = int(kz)
@@ -52,7 +52,7 @@ def _unpack_3d_ks(kernel_size: tuple[int, int, int] | int) -> tuple[int, int, in
def normalize_kernel2d(input: Tensor) -> Tensor:
r"""Normalize both derivative and smoothing kernel."""
- KORNIA_CHECK_SHAPE(input, ['*', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(input, ["*", "H", "W"])
norm = input.abs().sum(dim=-1).sum(dim=-1)
@@ -452,16 +452,16 @@ def get_spatial_gradient_kernel2d(
sobel, diff.
"""
- KORNIA_CHECK(mode.lower() in {'sobel', 'diff'}, f'Mode should be `sobel` or `diff`. Got {mode}')
- KORNIA_CHECK(order in {1, 2}, f'Order should be 1 or 2. Got {order}')
+ KORNIA_CHECK(mode.lower() in {"sobel", "diff"}, f"Mode should be `sobel` or `diff`. Got {mode}")
+ KORNIA_CHECK(order in {1, 2}, f"Order should be 1 or 2. Got {order}")
- if mode == 'sobel' and order == 1:
+ if mode == "sobel" and order == 1:
kernel: Tensor = get_sobel_kernel2d(device=device, dtype=dtype)
- elif mode == 'sobel' and order == 2:
+ elif mode == "sobel" and order == 2:
kernel = get_sobel_kernel2d_2nd_order(device=device, dtype=dtype)
- elif mode == 'diff' and order == 1:
+ elif mode == "diff" and order == 1:
kernel = get_diff_kernel2d(device=device, dtype=dtype)
- elif mode == 'diff' and order == 2:
+ elif mode == "diff" and order == 2:
kernel = get_diff_kernel2d_2nd_order(device=device, dtype=dtype)
else:
raise NotImplementedError(f"Not implemented for order {order} on mode {mode}")
@@ -474,12 +474,12 @@ def get_spatial_gradient_kernel3d(
) -> Tensor:
r"""Function that returns kernel for 1st or 2nd order scale pyramid gradients, using one of the following
operators: sobel, diff."""
- KORNIA_CHECK(mode.lower() in {'sobel', 'diff'}, f'Mode should be `sobel` or `diff`. Got {mode}')
- KORNIA_CHECK(order in {1, 2}, f'Order should be 1 or 2. Got {order}')
+ KORNIA_CHECK(mode.lower() in {"sobel", "diff"}, f"Mode should be `sobel` or `diff`. Got {mode}")
+ KORNIA_CHECK(order in {1, 2}, f"Order should be 1 or 2. Got {order}")
- if mode == 'diff' and order == 1:
+ if mode == "diff" and order == 1:
kernel = get_diff_kernel3d(device=device, dtype=dtype)
- elif mode == 'diff' and order == 2:
+ elif mode == "diff" and order == 2:
kernel = get_diff_kernel3d_2nd_order(device=device, dtype=dtype)
else:
raise NotImplementedError(f"Not implemented 3d gradient kernel for order {order} on mode {mode}")
@@ -957,16 +957,16 @@ def get_hanning_kernel2d(
return kernel2d
-@deprecated(replace_with='get_gaussian_kernel1d', version='6.9.10')
+@deprecated(replace_with="get_gaussian_kernel1d", version="6.9.10")
def get_gaussian_kernel1d_t(*args: Any, **kwargs: Any) -> Tensor:
return get_gaussian_kernel1d(*args, **kwargs)
-@deprecated(replace_with='get_gaussian_kernel2d', version='6.9.10')
+@deprecated(replace_with="get_gaussian_kernel2d", version="6.9.10")
def get_gaussian_kernel2d_t(*args: Any, **kwargs: Any) -> Tensor:
return get_gaussian_kernel2d(*args, **kwargs)
-@deprecated(replace_with='get_gaussian_kernel3d', version='6.9.10')
+@deprecated(replace_with="get_gaussian_kernel3d", version="6.9.10")
def get_gaussian_kernel3d_t(*args: Any, **kwargs: Any) -> Tensor:
return get_gaussian_kernel3d(*args, **kwargs)
diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.py
index 0bdb45378..e334dcece 100644
--- a/kornia/filters/kernels_geometry.py
+++ b/kornia/filters/kernels_geometry.py
@@ -11,7 +11,7 @@ from .kernels import _check_kernel_size, _unpack_2d_ks, _unpack_3d_ks
def get_motion_kernel2d(
- kernel_size: int, angle: Tensor | float, direction: Tensor | float = 0.0, mode: str = 'nearest'
+ kernel_size: int, angle: Tensor | float, direction: Tensor | float = 0.0, mode: str = "nearest"
) -> Tensor:
r"""Return 2D motion blur filter.
@@ -54,7 +54,7 @@ def get_motion_kernel2d(
if angle.dim() == 0:
angle = angle[None]
- KORNIA_CHECK_SHAPE(angle, ['B'])
+ KORNIA_CHECK_SHAPE(angle, ["B"])
if not isinstance(direction, Tensor):
direction = tensor([direction], device=device, dtype=dtype)
@@ -62,10 +62,10 @@ def get_motion_kernel2d(
if direction.dim() == 0:
direction = direction[None]
- KORNIA_CHECK_SHAPE(direction, ['B'])
+ KORNIA_CHECK_SHAPE(direction, ["B"])
KORNIA_CHECK(
direction.size(0) == angle.size(0),
- f'direction and angle must have the same length. Got {direction} and {angle}.',
+ f"direction and angle must have the same length. Got {direction} and {angle}.",
)
# direction from [-1, 1] to [0, 1] range
@@ -82,7 +82,7 @@ def get_motion_kernel2d(
kernel = pad(k[:, None], [0, 0, kernel_size // 2, kernel_size // 2, 0, 0])
expected_shape = torch.Size([direction.size(0), *kernel_tuple])
- KORNIA_CHECK(kernel.shape == expected_shape, f'Kernel shape should be {expected_shape}. Gotcha {kernel.shape}')
+ KORNIA_CHECK(kernel.shape == expected_shape, f"Kernel shape should be {expected_shape}. Gotcha {kernel.shape}")
kernel = kernel[:, None, ...]
# rotate (counterclockwise) kernel by given angle
@@ -93,7 +93,7 @@ def get_motion_kernel2d(
def get_motion_kernel3d(
- kernel_size: int, angle: Tensor | tuple[float, float, float], direction: Tensor | float = 0.0, mode: str = 'nearest'
+ kernel_size: int, angle: Tensor | tuple[float, float, float], direction: Tensor | float = 0.0, mode: str = "nearest"
) -> Tensor:
r"""Return 3D motion blur filter.
@@ -152,7 +152,7 @@ def get_motion_kernel3d(
if angle.dim() == 1:
angle = angle[None]
- KORNIA_CHECK_SHAPE(angle, ['B', '3'])
+ KORNIA_CHECK_SHAPE(angle, ["B", "3"])
if not isinstance(direction, Tensor):
direction = tensor([direction], device=device, dtype=dtype)
@@ -160,10 +160,10 @@ def get_motion_kernel3d(
if direction.dim() == 0:
direction = direction[None]
- KORNIA_CHECK_SHAPE(direction, ['B'])
+ KORNIA_CHECK_SHAPE(direction, ["B"])
KORNIA_CHECK(
direction.size(0) == angle.size(0),
- f'direction and angle must have the same batch size. Got {direction.shape} and {angle.shape}.',
+ f"direction and angle must have the same batch size. Got {direction.shape} and {angle.shape}.",
)
# direction from [-1, 1] to [0, 1] range
@@ -177,7 +177,7 @@ def get_motion_kernel3d(
kernel = pad(k[:, None, None], [0, 0, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, 0, 0])
expected_shape = torch.Size([direction.size(0), *kernel_tuple])
- KORNIA_CHECK(kernel.shape == expected_shape, f'Kernel shape should be {expected_shape}. Gotcha {kernel.shape}')
+ KORNIA_CHECK(kernel.shape == expected_shape, f"Kernel shape should be {expected_shape}. Gotcha {kernel.shape}")
kernel = kernel[:, None, ...]
# rotate (counterclockwise) kernel by given angle
diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.py
index b2b786694..ad102af50 100644
--- a/kornia/filters/laplacian.py
+++ b/kornia/filters/laplacian.py
@@ -7,7 +7,7 @@ from .kernels import get_laplacian_kernel2d, normalize_kernel2d
def laplacian(
- input: Tensor, kernel_size: tuple[int, int] | int, border_type: str = 'reflect', normalized: bool = True
+ input: Tensor, kernel_size: tuple[int, int] | int, border_type: str = "reflect", normalized: bool = True
) -> Tensor:
r"""Create an operator that returns a tensor using a Laplacian filter.
@@ -70,7 +70,7 @@ class Laplacian(Module):
"""
def __init__(
- self, kernel_size: tuple[int, int] | int, border_type: str = 'reflect', normalized: bool = True
+ self, kernel_size: tuple[int, int] | int, border_type: str = "reflect", normalized: bool = True
) -> None:
super().__init__()
self.kernel_size = kernel_size
diff --git a/kornia/filters/median.py b/kornia/filters/median.py
index 62ad88ab3..56d9c2915 100644
--- a/kornia/filters/median.py
+++ b/kornia/filters/median.py
@@ -36,7 +36,7 @@ def median_blur(input: Tensor, kernel_size: tuple[int, int] | int) -> Tensor:
torch.Size([2, 4, 5, 7])
"""
KORNIA_CHECK_IS_TENSOR(input)
- KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
padding = _compute_zero_padding(kernel_size)
diff --git a/kornia/filters/motion.py b/kornia/filters/motion.py
index 107023f0e..0cd7b88c4 100644
--- a/kornia/filters/motion.py
+++ b/kornia/filters/motion.py
@@ -37,7 +37,7 @@ class MotionBlur(Module):
"""
def __init__(
- self, kernel_size: int, angle: float, direction: float, border_type: str = 'constant', mode: str = 'nearest'
+ self, kernel_size: int, angle: float, direction: float, border_type: str = "constant", mode: str = "nearest"
) -> None:
super().__init__()
self.kernel_size = kernel_size
@@ -48,8 +48,8 @@ class MotionBlur(Module):
def __repr__(self) -> str:
return (
- f'{self.__class__.__name__} (kernel_size={self.kernel_size}, '
- f'angle={self.angle}, direction={self.direction}, border_type={self.border_type})'
+ f"{self.__class__.__name__} (kernel_size={self.kernel_size}, "
+ f"angle={self.angle}, direction={self.direction}, border_type={self.border_type})"
)
def forward(self, x: Tensor) -> Tensor:
@@ -88,14 +88,14 @@ class MotionBlur3D(Module):
kernel_size: int,
angle: float | tuple[float, float, float] | Tensor,
direction: float | Tensor,
- border_type: str = 'constant',
- mode: str = 'nearest',
+ border_type: str = "constant",
+ mode: str = "nearest",
) -> None:
super().__init__()
self.kernel_size = kernel_size
KORNIA_CHECK(
isinstance(angle, (Tensor, float, list, tuple)),
- f'Angle should be a Tensor, float or a sequence of floats. Got {angle}',
+ f"Angle should be a Tensor, float or a sequence of floats. Got {angle}",
)
if isinstance(angle, float):
self.angle = (angle, angle, angle)
@@ -108,8 +108,8 @@ class MotionBlur3D(Module):
def __repr__(self) -> str:
return (
- f'{self.__class__.__name__} (kernel_size={self.kernel_size}, '
- f'angle={self.angle}, direction={self.direction}, border_type={self.border_type})'
+ f"{self.__class__.__name__} (kernel_size={self.kernel_size}, "
+ f"angle={self.angle}, direction={self.direction}, border_type={self.border_type})"
)
def forward(self, x: Tensor) -> Tensor:
@@ -121,8 +121,8 @@ def motion_blur(
kernel_size: int,
angle: float | Tensor,
direction: float | Tensor,
- border_type: str = 'constant',
- mode: str = 'nearest',
+ border_type: str = "constant",
+ mode: str = "nearest",
) -> Tensor:
r"""Perform motion blur on tensor images.
@@ -165,8 +165,8 @@ def motion_blur3d(
kernel_size: int,
angle: tuple[float, float, float] | Tensor,
direction: float | Tensor,
- border_type: str = 'constant',
- mode: str = 'nearest',
+ border_type: str = "constant",
+ mode: str = "nearest",
) -> Tensor:
r"""Perform motion blur on 3D volumes (5D tensor).
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index 74a7302f3..14e7c7ca7 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -9,7 +9,7 @@ from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d
-def spatial_gradient(input: Tensor, mode: str = 'sobel', order: int = 1, normalized: bool = True) -> Tensor:
+def spatial_gradient(input: Tensor, mode: str = "sobel", order: int = 1, normalized: bool = True) -> Tensor:
r"""Compute the first order image derivative in both x and y using a Sobel operator.
.. image:: _static/img/spatial_gradient.png
@@ -33,7 +33,7 @@ def spatial_gradient(input: Tensor, mode: str = 'sobel', order: int = 1, normali
torch.Size([1, 3, 2, 4, 4])
"""
KORNIA_CHECK_IS_TENSOR(input)
- KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
# allocate kernel
kernel = get_spatial_gradient_kernel2d(mode, order, device=input.device, dtype=input.dtype)
@@ -47,12 +47,12 @@ def spatial_gradient(input: Tensor, mode: str = 'sobel', order: int = 1, normali
# Pad with "replicate for spatial dims, but with zeros for channel
spatial_pad = [kernel.size(1) // 2, kernel.size(1) // 2, kernel.size(2) // 2, kernel.size(2) // 2]
out_channels: int = 3 if order == 2 else 2
- padded_inp: Tensor = pad(input.reshape(b * c, 1, h, w), spatial_pad, 'replicate')
+ padded_inp: Tensor = pad(input.reshape(b * c, 1, h, w), spatial_pad, "replicate")
out = F.conv2d(padded_inp, tmp_kernel, groups=1, padding=0, stride=1)
return out.reshape(b, c, out_channels, h, w)
-def spatial_gradient3d(input: Tensor, mode: str = 'diff', order: int = 1) -> Tensor:
+def spatial_gradient3d(input: Tensor, mode: str = "diff", order: int = 1) -> Tensor:
r"""Compute the first and second order volume derivative in x, y and d using a diff operator.
Args:
@@ -71,14 +71,14 @@ def spatial_gradient3d(input: Tensor, mode: str = 'diff', order: int = 1) -> Ten
torch.Size([1, 4, 3, 2, 4, 4])
"""
KORNIA_CHECK_IS_TENSOR(input)
- KORNIA_CHECK_SHAPE(input, ['B', 'C', 'D', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "D", "H", "W"])
b, c, d, h, w = input.shape
dev = input.device
dtype = input.dtype
- if (mode == 'diff') and (order == 1):
+ if (mode == "diff") and (order == 1):
# we go for the special case implementation due to conv3d bad speed
- x: Tensor = pad(input, 6 * [1], 'replicate')
+ x: Tensor = pad(input, 6 * [1], "replicate")
center = slice(1, -1)
left = slice(0, -2)
right = slice(2, None)
@@ -107,7 +107,7 @@ def spatial_gradient3d(input: Tensor, mode: str = 'diff', order: int = 1) -> Ten
kernel.size(4) // 2,
]
out_ch: int = 6 if order == 2 else 3
- out = F.conv3d(pad(input, spatial_pad, 'replicate'), kernel_flip, padding=0, groups=c).view(
+ out = F.conv3d(pad(input, spatial_pad, "replicate"), kernel_flip, padding=0, groups=c).view(
b, c, out_ch, d, h, w
)
return out
@@ -136,7 +136,7 @@ def sobel(input: Tensor, normalized: bool = True, eps: float = 1e-6) -> Tensor:
torch.Size([1, 3, 4, 4])
"""
KORNIA_CHECK_IS_TENSOR(input)
- KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
# comput the x/y gradients
edges: Tensor = spatial_gradient(input, normalized=normalized)
@@ -171,7 +171,7 @@ class SpatialGradient(Module):
>>> output = SpatialGradient()(input) # 1x3x2x4x4
"""
- def __init__(self, mode: str = 'sobel', order: int = 1, normalized: bool = True) -> None:
+ def __init__(self, mode: str = "sobel", order: int = 1, normalized: bool = True) -> None:
super().__init__()
self.normalized: bool = normalized
self.order: int = order
@@ -205,7 +205,7 @@ class SpatialGradient3d(Module):
torch.Size([1, 4, 3, 2, 4, 4])
"""
- def __init__(self, mode: str = 'diff', order: int = 1) -> None:
+ def __init__(self, mode: str = "diff", order: int = 1) -> None:
super().__init__()
self.order: int = order
self.mode: str = mode
diff --git a/kornia/filters/unsharp.py b/kornia/filters/unsharp.py
index d5bfe982a..1d790b5dc 100644
--- a/kornia/filters/unsharp.py
+++ b/kornia/filters/unsharp.py
@@ -6,7 +6,7 @@ from .gaussian import gaussian_blur2d
def unsharp_mask(
- input: Tensor, kernel_size: tuple[int, int] | int, sigma: tuple[float, float] | Tensor, border_type: str = 'reflect'
+ input: Tensor, kernel_size: tuple[int, int] | int, sigma: tuple[float, float] | Tensor, border_type: str = "reflect"
) -> Tensor:
r"""Create an operator that sharpens a tensor by applying operation out = 2 * image - gaussian_blur2d(image).
@@ -63,7 +63,7 @@ class UnsharpMask(Module):
"""
def __init__(
- self, kernel_size: tuple[int, int] | int, sigma: tuple[float, float] | Tensor, border_type: str = 'reflect'
+ self, kernel_size: tuple[int, int] | int, sigma: tuple[float, float] | Tensor, border_type: str = "reflect"
) -> None:
super().__init__()
self.kernel_size = kernel_size
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 22d8b41b9..e309d1501 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -491,7 +491,7 @@ def transform_bbox(
restored_boxes[..., 3] = torch.max(transformed_boxes[..., [1, 3]], dim=-1)[0]
transformed_boxes = restored_boxes
- if mode == 'xywh':
+ if mode == "xywh":
transformed_boxes[..., 2] = transformed_boxes[..., 2] - transformed_boxes[..., 0]
transformed_boxes[..., 3] = transformed_boxes[..., 3] - transformed_boxes[..., 1]
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index e09b4b49c..39c01f8fd 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -510,7 +510,7 @@ class Boxes:
offset = torch.as_tensor([0, 0, 1, 1], device=boxes.device, dtype=boxes.dtype)
boxes = boxes + offset
- if mode.startswith('vertices'):
+ if mode.startswith("vertices"):
boxes = _boxes_to_polygons(boxes[..., 0], boxes[..., 1], boxes[..., 2], boxes[..., 3])
if self._N is not None and not as_padded_sequence:
@@ -761,7 +761,7 @@ class Boxes3D:
>>> boxes3d.get_boxes_shape()
(tensor([30., 60.]), tensor([20., 50.]), tensor([10., 40.]))
"""
- boxes_xyzwhd = self.to_tensor(mode='xyzwhd')
+ boxes_xyzwhd = self.to_tensor(mode="xyzwhd")
widths, heights, depths = boxes_xyzwhd[..., 3], boxes_xyzwhd[..., 4], boxes_xyzwhd[..., 5]
return depths, heights, widths
@@ -910,7 +910,7 @@ class Boxes3D:
offset = torch.as_tensor([0, 0, 0, 1, 1, 1], device=boxes.device, dtype=boxes.dtype)
boxes = boxes + offset
- if mode.startswith('vertices'):
+ if mode.startswith("vertices"):
xmin, ymin, zmin = boxes[..., 0], boxes[..., 1], boxes[..., 2]
width, height, depth = boxes[..., 3], boxes[..., 4], boxes[..., 5]
diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.py
index a560a4206..b27e2c44b 100644
--- a/kornia/geometry/calibration/distort.py
+++ b/kornia/geometry/calibration/distort.py
@@ -16,7 +16,7 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool
torch.Tensor: Inverse tilt projection matrix with shape :math:`(*, 3, 3)`.
"""
if taux.shape != tauy.shape:
- raise ValueError(f'Shape of taux {taux.shape} and tauy {tauy.shape} do not match.')
+ raise ValueError(f"Shape of taux {taux.shape} and tauy {tauy.shape} do not match.")
ndim: int = taux.dim()
taux = taux.reshape(-1)
@@ -84,18 +84,18 @@ def distort_points(
>>> points_dist = distort_points(points, K, dist_coeff)
"""
if points.dim() < 2 and points.shape[-1] != 2:
- raise ValueError(f'points shape is invalid. Got {points.shape}.')
+ raise ValueError(f"points shape is invalid. Got {points.shape}.")
if K.shape[-2:] != (3, 3):
- raise ValueError(f'K matrix shape is invalid. Got {K.shape}.')
+ raise ValueError(f"K matrix shape is invalid. Got {K.shape}.")
if new_K is None:
new_K = K
elif new_K.shape[-2:] != (3, 3):
- raise ValueError(f'new_K matrix shape is invalid. Got {new_K.shape}.')
+ raise ValueError(f"new_K matrix shape is invalid. Got {new_K.shape}.")
if dist.shape[-1] not in [4, 5, 8, 12, 14]:
- raise ValueError(f'Invalid number of distortion coefficients. Got {dist.shape[-1]}')
+ raise ValueError(f"Invalid number of distortion coefficients. Got {dist.shape[-1]}")
# Adding zeros to obtain vector with 14 coeffs.
if dist.shape[-1] < 14:
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index 61372d096..28738d5b7 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -45,15 +45,15 @@ def undistort_points(
[-0.1843, -0.1606]]])
"""
if points.dim() < 2 and points.shape[-1] != 2:
- raise ValueError(f'points shape is invalid. Got {points.shape}.')
+ raise ValueError(f"points shape is invalid. Got {points.shape}.")
if K.shape[-2:] != (3, 3):
- raise ValueError(f'K matrix shape is invalid. Got {K.shape}.')
+ raise ValueError(f"K matrix shape is invalid. Got {K.shape}.")
if new_K is None:
new_K = K
elif new_K.shape[-2:] != (3, 3):
- raise ValueError(f'new_K matrix shape is invalid. Got {new_K.shape}.')
+ raise ValueError(f"new_K matrix shape is invalid. Got {new_K.shape}.")
if dist.shape[-1] not in [4, 5, 8, 12, 14]:
raise ValueError(f"Invalid number of distortion coefficients. Got {dist.shape[-1]}")
@@ -143,21 +143,21 @@ def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->
raise ValueError(f"Image shape is invalid. Got: {image.shape}.")
if K.shape[-2:] != (3, 3):
- raise ValueError(f'K matrix shape is invalid. Got {K.shape}.')
+ raise ValueError(f"K matrix shape is invalid. Got {K.shape}.")
if dist.shape[-1] not in [4, 5, 8, 12, 14]:
- raise ValueError(f'Invalid number of distortion coefficients. Got {dist.shape[-1]}.')
+ raise ValueError(f"Invalid number of distortion coefficients. Got {dist.shape[-1]}.")
if not image.is_floating_point():
- raise ValueError(f'Invalid input image data type. Input should be float. Got {image.dtype}.')
+ raise ValueError(f"Invalid input image data type. Input should be float. Got {image.dtype}.")
if image.shape[:-3] != K.shape[:-2] or image.shape[:-3] != dist.shape[:-1]:
# Input with image shape (1, C, H, W), K shape (3, 3), dist shape (4)
# allowed to avoid a breaking change.
if not all((image.shape[:-3] == (1,), K.shape[:-2] == (), dist.shape[:-1] == ())):
raise ValueError(
- 'Input shape is invalid. Input batch dimensions should match. '
- f'Got {image.shape[:-3]}, {K.shape[:-2]}, {dist.shape[:-1]}.'
+ "Input shape is invalid. Input batch dimensions should match. "
+ f"Got {image.shape[:-3]}, {K.shape[:-2]}, {dist.shape[:-1]}."
)
channels, rows, cols = image.shape[-3:]
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index 76cfce2a5..9ea492fcf 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -150,7 +150,7 @@ class PinholeCamera:
return self.extrinsics[..., 0, -1]
@tx.setter
- def tx(self, value: Union[Tensor, float]) -> 'PinholeCamera':
+ def tx(self, value: Union[Tensor, float]) -> "PinholeCamera":
r"""Set the x-coordinate of the translation vector with the given value."""
self.extrinsics[..., 0, -1] = value
return self
@@ -165,7 +165,7 @@ class PinholeCamera:
return self.extrinsics[..., 1, -1]
@ty.setter
- def ty(self, value: Union[Tensor, float]) -> 'PinholeCamera':
+ def ty(self, value: Union[Tensor, float]) -> "PinholeCamera":
r"""Set the y-coordinate of the translation vector with the given value."""
self.extrinsics[..., 1, -1] = value
return self
@@ -180,7 +180,7 @@ class PinholeCamera:
return self.extrinsics[..., 2, -1]
@tz.setter
- def tz(self, value: Union[Tensor, float]) -> 'PinholeCamera':
+ def tz(self, value: Union[Tensor, float]) -> "PinholeCamera":
r"""Set the y-coordinate of the translation vector with the given value."""
self.extrinsics[..., 2, -1] = value
return self
@@ -221,7 +221,7 @@ class PinholeCamera:
"""
return self.extrinsics[..., :3, -1:]
- def clone(self) -> 'PinholeCamera':
+ def clone(self) -> "PinholeCamera":
r"""Return a deep copy of the current object instance."""
height: Tensor = self.height.clone()
width: Tensor = self.width.clone()
@@ -237,7 +237,7 @@ class PinholeCamera:
"""
return self.intrinsics.inverse()
- def scale(self, scale_factor: Tensor) -> 'PinholeCamera':
+ def scale(self, scale_factor: Tensor) -> "PinholeCamera":
r"""Scale the pinhole model.
Args:
@@ -259,7 +259,7 @@ class PinholeCamera:
width: Tensor = scale_factor * self.width.clone()
return PinholeCamera(intrinsics, self.extrinsics, height, width)
- def scale_(self, scale_factor: Union[float, Tensor]) -> 'PinholeCamera':
+ def scale_(self, scale_factor: Union[float, Tensor]) -> "PinholeCamera":
r"""Scale the pinhole model in-place.
Args:
@@ -353,7 +353,7 @@ class PinholeCamera:
batch_size: int,
device: Device,
dtype: torch.dtype,
- ) -> 'PinholeCamera':
+ ) -> "PinholeCamera":
# create the camera matrix
intrinsics = torch.zeros(batch_size, 4, 4, device=device, dtype=dtype)
intrinsics[..., 0, 0] += fx
@@ -394,7 +394,7 @@ class PinholeCamerasList(PinholeCamera):
def __init__(self, pinholes_list: Iterable[PinholeCamera]) -> None:
self._initialize_parameters(pinholes_list)
- def _initialize_parameters(self, pinholes: Iterable[PinholeCamera]) -> 'PinholeCamerasList':
+ def _initialize_parameters(self, pinholes: Iterable[PinholeCamera]) -> "PinholeCamerasList":
r"""Initialise the class attributes given a cameras list."""
if not isinstance(pinholes, (list, tuple)):
raise TypeError(f"pinhole must of type list or tuple. Got {type(pinholes)}")
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 2e80aa417..6dc1337cd 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -342,7 +342,7 @@ def axis_angle_to_rotation_matrix(axis_angle: Tensor) -> Tensor:
return rotation_matrix # Nx3x3
-@deprecated(replace_with='axis_angle_to_rotation_matrix', version='0.7.0')
+@deprecated(replace_with="axis_angle_to_rotation_matrix", version="0.7.0")
def angle_axis_to_rotation_matrix(axis_angle: Tensor) -> Tensor:
return axis_angle_to_rotation_matrix(axis_angle)
@@ -378,7 +378,7 @@ def rotation_matrix_to_axis_angle(rotation_matrix: Tensor) -> Tensor:
return quaternion_to_axis_angle(quaternion)
-@deprecated(replace_with='rotation_matrix_to_axis_angle', version='0.7.0')
+@deprecated(replace_with="rotation_matrix_to_axis_angle", version="0.7.0")
def rotation_matrix_to_angle_axis(rotation_matrix: Tensor) -> Tensor:
return rotation_matrix_to_axis_angle(rotation_matrix)
@@ -616,7 +616,7 @@ def quaternion_to_axis_angle(quaternion: Tensor) -> Tensor:
return axis_angle
-@deprecated(replace_with='quaternion_to_axis_angle', version='0.7.0')
+@deprecated(replace_with="quaternion_to_axis_angle", version="0.7.0")
def quaternion_to_angle_axis(quaternion: Tensor) -> Tensor:
return quaternion_to_axis_angle(quaternion)
@@ -756,7 +756,7 @@ def axis_angle_to_quaternion(axis_angle: Tensor) -> Tensor:
return quaternion
-@deprecated(replace_with='axis_angle_to_quaternion', version='0.7.0')
+@deprecated(replace_with="axis_angle_to_quaternion", version="0.7.0")
def angle_axis_to_quaternion(axis_angle: Tensor) -> Tensor:
return axis_angle_to_quaternion(axis_angle)
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index b8aa4ffa7..9757ea778 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -290,8 +290,8 @@ class DepthWarper(Module):
pinhole_dst: PinholeCamera,
height: int,
width: int,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> None:
super().__init__()
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index b9b84e0e7..782c08eba 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -38,7 +38,7 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[t
Returns:
the computed essential matrix with shape :math:`(B, 3, 3)`.
"""
- KORNIA_CHECK_SHAPE(points1, ['B', 'N', '2'])
+ KORNIA_CHECK_SHAPE(points1, ["B", "N", "2"])
KORNIA_CHECK_SAME_SHAPE(points1, points2)
KORNIA_CHECK(points1.shape[1] >= 5, "Number of points should be >=5")
if weights is not None:
@@ -503,7 +503,7 @@ def find_essential(
-1
)
- KORNIA_CHECK_SHAPE(error, ['f{batch_size}', '10'])
+ KORNIA_CHECK_SHAPE(error, ["f{batch_size}", "10"])
chosen_indices = torch.argmin(error, dim=-1)
result = torch.stack([(E.view(-1, solution_num, 3, 3))[i, chosen_indices[i], :] for i in range(batch_size)])
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 01654c8ad..912a10a77 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -83,8 +83,8 @@ def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
Returns:
the computed fundamental matrix with shape :math:`(B, 3*m, 3), Valid values of m are 1, 2 or 3`
"""
- KORNIA_CHECK_SHAPE(points1, ['B', '7', '2'])
- KORNIA_CHECK_SHAPE(points2, ['B', '7', '2'])
+ KORNIA_CHECK_SHAPE(points1, ["B", "7", "2"])
+ KORNIA_CHECK_SHAPE(points2, ["B", "7", "2"])
batch_size = points1.shape[0]
@@ -120,8 +120,8 @@ def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
f1_det = torch.linalg.det(f1)
f2_det = torch.linalg.det(f2)
coeffs[:, 0] = f1_det
- coeffs[:, 1] = torch.einsum('bii->b', f2 @ torch.inverse(f1)) * f1_det
- coeffs[:, 2] = torch.einsum('bii->b', f1 @ torch.inverse(f2)) * f2_det
+ coeffs[:, 1] = torch.einsum("bii->b", f2 @ torch.inverse(f1)) * f1_det
+ coeffs[:, 2] = torch.einsum("bii->b", f1 @ torch.inverse(f2)) * f2_det
coeffs[:, 3] = f2_det
# solve the cubic equation, there can be 1 to 3 roots
@@ -223,7 +223,7 @@ def run_8point(points1: Tensor, points2: Tensor, weights: Optional[Tensor] = Non
def find_fundamental(
- points1: Tensor, points2: Tensor, weights: Optional[Tensor] = None, method: Literal['8POINT', '7POINT'] = '8POINT'
+ points1: Tensor, points2: Tensor, weights: Optional[Tensor] = None, method: Literal["8POINT", "7POINT"] = "8POINT"
) -> Tensor:
r"""
Args:
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index d3540e900..85e6244a5 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -120,7 +120,7 @@ def line_segment_transfer_error_one_way(ls1: Tensor, ls2: Tensor, H: Tensor, squ
def find_homography_dlt(
- points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None, solver: str = 'lu'
+ points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None, solver: str = "lu"
) -> torch.Tensor:
r"""Compute the homography matrix using the DLT formulation.
@@ -168,14 +168,14 @@ def find_homography_dlt(
w_diag = torch.diag_embed(weights.unsqueeze(dim=-1).repeat(1, 1, 2).reshape(weights.shape[0], -1))
A = A.transpose(-2, -1) @ w_diag @ A
- if solver == 'svd':
+ if solver == "svd":
try:
_, _, V = _torch_svd_cast(A)
except RuntimeError:
- warnings.warn('SVD did not converge', RuntimeWarning)
+ warnings.warn("SVD did not converge", RuntimeWarning)
return torch.empty((points1_norm.size(0), 3, 3), device=device, dtype=dtype)
H = V[..., -1].view(-1, 3, 3)
- elif solver == 'lu':
+ elif solver == "lu":
B = torch.ones(A.shape[0], A.shape[1], device=device, dtype=dtype)
sol, _, _ = safe_solve_with_mask(B, A)
H = sol.reshape(-1, 3, 3)
@@ -306,7 +306,7 @@ def find_homography_lines_dlt(ls1: Tensor, ls2: Tensor, weights: Optional[Tensor
try:
_, _, V = torch.svd(A)
except RuntimeError:
- warnings.warn('SVD did not converge', RuntimeWarning)
+ warnings.warn("SVD did not converge", RuntimeWarning)
return torch.empty((points1_norm.size(0), 3, 3), device=device, dtype=dtype)
H = V[..., -1].view(-1, 3, 3)
diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.py
index 372105021..623deacfc 100644
--- a/kornia/geometry/keypoints.py
+++ b/kornia/geometry/keypoints.py
@@ -6,7 +6,7 @@ from torch import Size
from kornia.core import Tensor
from kornia.geometry import transform_points
-__all__ = ['Keypoints', 'Keypoints3D']
+__all__ = ["Keypoints", "Keypoints3D"]
def _merge_keypoint_list(keypoints: List[Tensor]) -> Tensor:
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index 37ed5045a..659ce3f99 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -319,7 +319,7 @@ class Se2(Module):
r_inv: So2 = self.r.inverse()
_t = -1 * self.t
if isinstance(_t, int):
- raise TypeError('Unexpected integer from `-1 * translation`')
+ raise TypeError("Unexpected integer from `-1 * translation`")
return Se2(r_inv, r_inv * _t)
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 16ff9fd41..a4d2912ec 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -340,7 +340,7 @@ class Se3(Module):
r_inv = self.r.inverse()
_t = -1 * self.t
if isinstance(_t, int):
- raise TypeError('Unexpected integer from `-1 * translation`')
+ raise TypeError("Unexpected integer from `-1 * translation`")
return Se3(r_inv, r_inv * _t)
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index 64089c107..59d11bef7 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -89,7 +89,7 @@ class Hyperplane(Module):
norm = normal.norm(-1)
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L108
- def compute_normal_svd(v0: Tensor, v1: Tensor) -> 'Vector3':
+ def compute_normal_svd(v0: Tensor, v1: Tensor) -> "Vector3":
# NOTE: for reason TensorWrapper does not stack well
m = stack((unwrap(v0), unwrap(v1)), -2) # Bx2x3
_, _, V = _torch_svd_cast(m) # kornia solution lies in the last row
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index ecb6ddcd0..62806e677 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -71,10 +71,10 @@ class Quaternion(Module):
def __repr__(self) -> str:
return f"{self.data}"
- def __getitem__(self, idx: Union[int, slice]) -> 'Quaternion':
+ def __getitem__(self, idx: Union[int, slice]) -> "Quaternion":
return Quaternion(self.data[idx])
- def __neg__(self) -> 'Quaternion':
+ def __neg__(self) -> "Quaternion":
"""Inverts the sign of the quaternion data.
Example:
@@ -84,7 +84,7 @@ class Quaternion(Module):
"""
return Quaternion(-self.data)
- def __add__(self, right: 'Quaternion') -> 'Quaternion':
+ def __add__(self, right: "Quaternion") -> "Quaternion":
"""Add a given quaternion.
Args:
@@ -101,7 +101,7 @@ class Quaternion(Module):
KORNIA_CHECK_TYPE(right, Quaternion)
return Quaternion(self.data + right.data)
- def __sub__(self, right: 'Quaternion') -> 'Quaternion':
+ def __sub__(self, right: "Quaternion") -> "Quaternion":
"""Subtract a given quaternion.
Args:
@@ -118,7 +118,7 @@ class Quaternion(Module):
KORNIA_CHECK_TYPE(right, Quaternion)
return Quaternion(self.data - right.data)
- def __mul__(self, right: 'Quaternion') -> 'Quaternion':
+ def __mul__(self, right: "Quaternion") -> "Quaternion":
KORNIA_CHECK_TYPE(right, Quaternion)
# NOTE: borrowed from sophus sympy. Produce less multiplications compared to others.
# https://github.com/strasdat/Sophus/blob/785fef35b7d9e0fc67b4964a69124277b7434a44/sympy/sophus/quaternion.py#L19
@@ -126,16 +126,16 @@ class Quaternion(Module):
new_vec = self.real[..., None] * right.vec + right.real[..., None] * self.vec + self.vec.cross(right.vec)
return Quaternion(concatenate((new_real[..., None], new_vec), -1))
- def __div__(self, right: Union[Tensor, 'Quaternion']) -> 'Quaternion':
+ def __div__(self, right: Union[Tensor, "Quaternion"]) -> "Quaternion":
if isinstance(right, Tensor):
return Quaternion(self.data / right[..., None])
KORNIA_CHECK_TYPE(right, Quaternion)
return self * right.inv()
- def __truediv__(self, right: 'Quaternion') -> 'Quaternion':
+ def __truediv__(self, right: "Quaternion") -> "Quaternion":
return self.__div__(right)
- def __pow__(self, t: float) -> 'Quaternion':
+ def __pow__(self, t: float) -> "Quaternion":
"""Return the power of a quaternion raised to exponent t.
Args:
@@ -243,7 +243,7 @@ class Quaternion(Module):
return quaternion_to_rotation_matrix(self.data)
@classmethod
- def from_matrix(cls, matrix: Tensor) -> 'Quaternion':
+ def from_matrix(cls, matrix: Tensor) -> "Quaternion":
"""Create a quaternion from a rotation matrix.
Args:
@@ -259,7 +259,7 @@ class Quaternion(Module):
return cls(rotation_matrix_to_quaternion(matrix))
@classmethod
- def from_axis_angle(cls, axis_angle: Tensor) -> 'Quaternion':
+ def from_axis_angle(cls, axis_angle: Tensor) -> "Quaternion":
"""Create a quaternion from axis-angle representation.
Args:
@@ -277,7 +277,7 @@ class Quaternion(Module):
@classmethod
def identity(
cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None
- ) -> 'Quaternion':
+ ) -> "Quaternion":
"""Create a quaternion representing an identity rotation.
Args:
@@ -295,7 +295,7 @@ class Quaternion(Module):
return cls(data)
@classmethod
- def from_coeffs(cls, w: float, x: float, y: float, z: float) -> 'Quaternion':
+ def from_coeffs(cls, w: float, x: float, y: float, z: float) -> "Quaternion":
"""Create a quaternion from the data coefficients.
Args:
@@ -317,7 +317,7 @@ class Quaternion(Module):
@classmethod
def random(
cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None
- ) -> 'Quaternion':
+ ) -> "Quaternion":
"""Create a random unit quaternion of shape :math:`(B, 4)`.
Uniformly distributed across the rotation space as per: http://planning.cs.uiuc.edu/node198.html
@@ -338,7 +338,7 @@ class Quaternion(Module):
q4 = r1.sqrt() * (2 * pi * r3).cos()
return cls(stack((q1, q2, q3, q4), -1))
- def slerp(self, q1: 'Quaternion', t: float) -> 'Quaternion':
+ def slerp(self, q1: "Quaternion", t: float) -> "Quaternion":
"""Returns a unit quaternion spherically interpolated between quaternions self.q and q1.
See more: https://en.wikipedia.org/wiki/Slerp
@@ -363,15 +363,15 @@ class Quaternion(Module):
return self.data.norm(2, -1, keepdim)
# TODO: add docs
- def normalize(self) -> 'Quaternion':
+ def normalize(self) -> "Quaternion":
return Quaternion(normalize_quaternion(self.data))
# TODO: add docs
- def conj(self) -> 'Quaternion':
+ def conj(self) -> "Quaternion":
return Quaternion(concatenate((self.real[..., None], -self.vec), -1))
# TODO: add docs
- def inv(self) -> 'Quaternion':
+ def inv(self) -> "Quaternion":
return self.conj() / self.squared_norm()
# TODO: add docs
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index d0670f4a5..1e3365bcc 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -39,7 +39,7 @@ class RANSAC(Module):
def __init__(
self,
- model_type: str = 'homography',
+ model_type: str = "homography",
inl_th: float = 2.0,
batch_size: int = 2048,
max_iter: int = 10,
@@ -47,7 +47,7 @@ class RANSAC(Module):
max_lo_iters: int = 5,
) -> None:
super().__init__()
- self.supported_models = ['homography', 'fundamental', 'fundamental_7pt', 'homography_from_linesegments']
+ self.supported_models = ["homography", "fundamental", "fundamental_7pt", "homography_from_linesegments"]
self.inl_th = inl_th
self.max_iter = max_iter
self.batch_size = batch_size
@@ -60,30 +60,30 @@ class RANSAC(Module):
self.minimal_solver: Callable[..., Tensor]
self.polisher_solver: Callable[..., Tensor]
- if model_type == 'homography':
+ if model_type == "homography":
self.error_fn = oneway_transfer_error
self.minimal_solver = find_homography_dlt
self.polisher_solver = find_homography_dlt_iterated
self.minimal_sample_size = 4
- elif model_type == 'homography_from_linesegments':
+ elif model_type == "homography_from_linesegments":
self.error_fn = line_segment_transfer_error_one_way
self.minimal_solver = find_homography_lines_dlt
self.polisher_solver = find_homography_lines_dlt_iterated
self.minimal_sample_size = 4
- elif model_type == 'fundamental':
+ elif model_type == "fundamental":
self.error_fn = symmetrical_epipolar_distance
self.minimal_solver = find_fundamental
self.minimal_sample_size = 8
self.polisher_solver = find_fundamental
- elif model_type == 'fundamental_7pt':
+ elif model_type == "fundamental_7pt":
self.error_fn = symmetrical_epipolar_distance
- self.minimal_solver = partial(find_fundamental, method='7POINT')
+ self.minimal_solver = partial(find_fundamental, method="7POINT")
self.minimal_sample_size = 7
self.polisher_solver = find_fundamental
else:
raise NotImplementedError(f"{model_type} is unknown. Try one of {self.supported_models}")
- def sample(self, sample_size: int, pop_size: int, batch_size: int, device: Device = torch.device('cpu')) -> Tensor:
+ def sample(self, sample_size: int, pop_size: int, batch_size: int, device: Device = torch.device("cpu")) -> Tensor:
"""Minimal sampler, but unlike traditional RANSAC we sample in batches to get benefit of the parallel
processing, esp.
@@ -115,7 +115,7 @@ class RANSAC(Module):
if len(kp2.shape) == 2:
kp2 = kp2[None]
batch_size = models.shape[0]
- if self.model_type == 'homography_from_linesegments':
+ if self.model_type == "homography_from_linesegments":
errors = self.error_fn(kp1.expand(batch_size, -1, 2, 2), kp2.expand(batch_size, -1, 2, 2), models)
else:
errors = self.error_fn(kp1.expand(batch_size, -1, 2), kp2.expand(batch_size, -1, 2), models)
@@ -131,7 +131,7 @@ class RANSAC(Module):
""""""
# ToDo: add (model-specific) verification of the samples,
# E.g. constraints on not to be a degenerate sample
- if self.model_type == 'homography':
+ if self.model_type == "homography":
mask = sample_is_valid_for_homography(kp1, kp2)
return kp1[mask], kp2[mask]
return kp1, kp2
@@ -154,7 +154,7 @@ class RANSAC(Module):
return model
def validate_inputs(self, kp1: Tensor, kp2: Tensor, weights: Optional[Tensor] = None) -> None:
- if self.model_type in ['homography', 'fundamental']:
+ if self.model_type in ["homography", "fundamental"]:
KORNIA_CHECK_SHAPE(kp1, ["N", "2"])
KORNIA_CHECK_SHAPE(kp2, ["N", "2"])
if not (kp1.shape[0] == kp2.shape[0]) or (kp1.shape[0] < self.minimal_sample_size):
@@ -162,7 +162,7 @@ class RANSAC(Module):
"kp1 and kp2 should be equal shape at at least"
f" [{self.minimal_sample_size}, 2], got {kp1.shape}, {kp2.shape}"
)
- if self.model_type == 'homography_from_linesegments':
+ if self.model_type == "homography_from_linesegments":
KORNIA_CHECK_SHAPE(kp1, ["N", "2", "2"])
KORNIA_CHECK_SHAPE(kp2, ["N", "2", "2"])
if not (kp1.shape[0] == kp2.shape[0]) or (kp1.shape[0] < self.minimal_sample_size):
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index f346fc605..a1a720d60 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -31,7 +31,7 @@ def solve_quadratic(coeffs: Tensor) -> Tensor:
a consistent output shape for all cases.
"""
- KORNIA_CHECK_SHAPE(coeffs, ['B', '3'])
+ KORNIA_CHECK_SHAPE(coeffs, ["B", "3"])
# Coefficients of quadratic equation
a = coeffs[:, 0] # coefficient of x^2
@@ -92,7 +92,7 @@ def solve_cubic(coeffs: Tensor) -> Tensor:
roots should be represented as 0. Thus, the output for a single real root should be in the
format [real_root, 0, 0], and for two real roots, it should be [real_root_1, real_root_2, 0].
"""
- KORNIA_CHECK_SHAPE(coeffs, ['B', '4'])
+ KORNIA_CHECK_SHAPE(coeffs, ["B", "4"])
_PI = torch.tensor(math.pi, device=coeffs.device, dtype=coeffs.dtype)
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 28b8e84a5..aca16dd73 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -14,7 +14,7 @@ from kornia.utils.grid import create_meshgrid
def _validate_batched_image_tensor_input(tensor: Tensor) -> None:
KORNIA_CHECK_IS_TENSOR(tensor)
- KORNIA_CHECK_SHAPE(tensor, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(tensor, ["B", "C", "H", "W"])
def spatial_softmax2d(input: Tensor, temperature: Tensor = torch.tensor(1.0)) -> Tensor:
diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.py
index b93ddfd02..52c251ce0 100644
--- a/kornia/geometry/subpix/nms.py
+++ b/kornia/geometry/subpix/nms.py
@@ -29,13 +29,14 @@ class NonMaximaSuppression2d(Module):
Flag `minima_are_also_good` is useful, when you want to detect both maxima and minima, e.g. for DoG
"""
+
kernel: Tensor
def __init__(self, kernel_size: tuple[int, int]) -> None:
super().__init__()
self.kernel_size: tuple[int, int] = kernel_size
self.padding: tuple[int, int, int, int] = self._compute_zero_padding2d(kernel_size)
- self.register_buffer('kernel', _get_nms_kernel2d(*kernel_size))
+ self.register_buffer("kernel", _get_nms_kernel2d(*kernel_size))
@staticmethod
def _compute_zero_padding2d(kernel_size: tuple[int, int]) -> tuple[int, int, int, int]:
@@ -56,7 +57,7 @@ class NonMaximaSuppression2d(Module):
raise AssertionError(x.shape)
B, CH, H, W = x.size()
# find local maximum values
- x_padded = pad(x, list(self.padding)[::-1], mode='replicate')
+ x_padded = pad(x, list(self.padding)[::-1], mode="replicate")
B, CH, HP, WP = x_padded.size()
neighborhood = F.conv2d(x_padded.view(B * CH, 1, HP, WP), self.kernel.to(x.device, x.dtype), stride=1).view(
@@ -134,7 +135,7 @@ class NonMaximaSuppression3d(Module):
else:
max_non_center = (
F.conv3d(
- pad(x, list(self.padding)[::-1], mode='replicate'),
+ pad(x, list(self.padding)[::-1], mode="replicate"),
self.kernel.repeat(CH, 1, 1, 1, 1).to(x.device, x.dtype),
stride=1,
groups=CH,
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 78a7ff9d7..fe6eacfec 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -14,7 +14,7 @@ from .dsnt import spatial_expectation2d, spatial_softmax2d
from .nms import nms3d
-def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.device('cpu')) -> Tensor:
+def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.device("cpu")) -> Tensor:
r"""Helper function, which generates a kernel to with window coordinates, residual to window center.
Args:
@@ -31,7 +31,7 @@ def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.devic
return conv_kernel
-def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device('cpu')) -> Tensor:
+def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device("cpu")) -> Tensor:
r"""Helper function, which generates a kernel to return center coordinates, when applied with F.conv2d to 2d
coordinates grid.
@@ -62,7 +62,7 @@ def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device('cp
return center_kernel
-def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device('cpu')) -> Tensor:
+def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device("cpu")) -> Tensor:
r"""Helper function, which generates a kernel to return center coordinates, when applied with F.conv2d to 3d
coordinates grid.
@@ -100,7 +100,7 @@ def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.de
return center_kernel
-def _get_window_grid_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device('cpu')) -> Tensor:
+def _get_window_grid_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device("cpu")) -> Tensor:
r"""Helper function, which generates a kernel to return coordinates, residual to window center.
Args:
@@ -562,9 +562,9 @@ def conv_quad_interp3d(input: Tensor, strict_maxima_bonus: float = 10.0, eps: fl
# to determine the location we are solving system of linear equations Ax = b, where b is 1st order gradient
# and A is Hessian matrix
- b: Tensor = spatial_gradient3d(input, order=1, mode='diff') #
+ b: Tensor = spatial_gradient3d(input, order=1, mode="diff") #
b = b.permute(0, 1, 3, 4, 5, 2).reshape(-1, 3, 1)
- A: Tensor = spatial_gradient3d(input, order=2, mode='diff')
+ A: Tensor = spatial_gradient3d(input, order=2, mode="diff")
A = A.permute(0, 1, 3, 4, 5, 2).reshape(-1, 6)
dxx = A[..., 0]
dyy = A[..., 1]
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index c7f01fd9f..9aeea8a39 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -119,8 +119,8 @@ def _compute_shear_matrix(shear: torch.Tensor) -> torch.Tensor:
def affine(
tensor: torch.Tensor,
matrix: torch.Tensor,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> torch.Tensor:
r"""Apply an affine transformation to the image.
@@ -170,8 +170,8 @@ def affine(
def affine3d(
tensor: torch.Tensor,
matrix: torch.Tensor,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = False,
) -> torch.Tensor:
r"""Apply an affine transformation to the 3d volume.
@@ -226,8 +226,8 @@ def rotate(
tensor: torch.Tensor,
angle: torch.Tensor,
center: Union[None, torch.Tensor] = None,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> torch.Tensor:
r"""Rotate the tensor anti-clockwise about the center.
@@ -292,8 +292,8 @@ def rotate3d(
pitch: torch.Tensor,
roll: torch.Tensor,
center: Union[None, torch.Tensor] = None,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = False,
) -> torch.Tensor:
r"""Rotate 3D the tensor anti-clockwise about the centre.
@@ -355,8 +355,8 @@ def rotate3d(
def translate(
tensor: torch.Tensor,
translation: torch.Tensor,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> torch.Tensor:
r"""Translate the tensor in pixel units.
@@ -404,8 +404,8 @@ def scale(
tensor: torch.Tensor,
scale_factor: torch.Tensor,
center: Union[None, torch.Tensor] = None,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> torch.Tensor:
r"""Scale the tensor by a factor.
@@ -464,8 +464,8 @@ def scale(
def shear(
tensor: torch.Tensor,
shear: torch.Tensor,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = False,
) -> torch.Tensor:
r"""Shear the tensor.
@@ -525,7 +525,7 @@ def _side_to_image_size(side_size: int, aspect_ratio: float, side: str = "short"
def resize(
input: torch.Tensor,
size: Union[int, Tuple[int, int]],
- interpolation: str = 'bilinear',
+ interpolation: str = "bilinear",
align_corners: Optional[bool] = None,
side: str = "short",
antialias: bool = False,
@@ -562,7 +562,7 @@ def resize(
raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(input)}")
if len(input.shape) < 2:
- raise ValueError(f'Input tensor must have at least two dimensions. Got {len(input.shape)}')
+ raise ValueError(f"Input tensor must have at least two dimensions. Got {len(input.shape)}")
input_size = h, w = input.shape[-2:]
if isinstance(size, int):
@@ -675,7 +675,7 @@ class Resize(nn.Module):
def __init__(
self,
size: Union[int, Tuple[int, int]],
- interpolation: str = 'bilinear',
+ interpolation: str = "bilinear",
align_corners: Optional[bool] = None,
side: str = "short",
antialias: bool = False,
@@ -740,8 +740,8 @@ class Affine(nn.Module):
scale_factor: Optional[torch.Tensor] = None,
shear: Optional[torch.Tensor] = None,
center: Optional[torch.Tensor] = None,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> None:
batch_sizes = [arg.size()[0] for arg in (angle, translation, scale_factor, shear) if arg is not None]
@@ -867,8 +867,8 @@ class Rotate(nn.Module):
self,
angle: torch.Tensor,
center: Union[None, torch.Tensor] = None,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> None:
super().__init__()
@@ -907,7 +907,7 @@ class Translate(nn.Module):
"""
def __init__(
- self, translation: torch.Tensor, mode: str = 'bilinear', padding_mode: str = 'zeros', align_corners: bool = True
+ self, translation: torch.Tensor, mode: str = "bilinear", padding_mode: str = "zeros", align_corners: bool = True
) -> None:
super().__init__()
self.translation: torch.Tensor = translation
@@ -951,8 +951,8 @@ class Scale(nn.Module):
self,
scale_factor: torch.Tensor,
center: Union[None, torch.Tensor] = None,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> None:
super().__init__()
@@ -991,7 +991,7 @@ class Shear(nn.Module):
"""
def __init__(
- self, shear: torch.Tensor, mode: str = 'bilinear', padding_mode: str = 'zeros', align_corners: bool = True
+ self, shear: torch.Tensor, mode: str = "bilinear", padding_mode: str = "zeros", align_corners: bool = True
) -> None:
super().__init__()
self.shear: torch.Tensor = shear
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index fb85edc10..057981d5b 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -15,8 +15,8 @@ def crop_and_resize(
input_tensor: Tensor,
boxes: Tensor,
size: Tuple[int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> Tensor:
r"""Extract crops from 2D images (4D tensor) and resize given a bounding box.
@@ -88,8 +88,8 @@ def crop_and_resize(
def center_crop(
input_tensor: Tensor,
size: Tuple[int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> Tensor:
r"""Crop the 2D images (4D tensor) from the center.
@@ -166,8 +166,8 @@ def crop_by_boxes(
input_tensor: Tensor,
src_box: Tensor,
dst_box: Tensor,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
validate_boxes: bool = True,
) -> Tensor:
@@ -247,8 +247,8 @@ def crop_by_transform_mat(
input_tensor: Tensor,
transform: Tensor,
out_size: Tuple[int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> Tensor:
"""Perform crop transform on 2D images (4D tensor) given a perspective transformation matrix.
@@ -287,7 +287,7 @@ def crop_by_indices(
input_tensor: Tensor,
src_box: Tensor,
size: Optional[Tuple[int, int]] = None,
- interpolation: str = 'bilinear',
+ interpolation: str = "bilinear",
align_corners: Optional[bool] = None,
antialias: bool = False,
shape_compensation: str = "resize",
diff --git a/kornia/geometry/transform/crop3d.py b/kornia/geometry/transform/crop3d.py
index 32e1b02c2..3511c329f 100644
--- a/kornia/geometry/transform/crop3d.py
+++ b/kornia/geometry/transform/crop3d.py
@@ -13,7 +13,7 @@ def crop_and_resize3d(
tensor: torch.Tensor,
boxes: torch.Tensor,
size: Tuple[int, int, int],
- interpolation: str = 'bilinear',
+ interpolation: str = "bilinear",
align_corners: bool = False,
) -> torch.Tensor:
r"""Extract crops from 3D volumes (5D tensor) and resize them.
@@ -111,7 +111,7 @@ def crop_and_resize3d(
def center_crop3d(
- tensor: torch.Tensor, size: Tuple[int, int, int], interpolation: str = 'bilinear', align_corners: bool = True
+ tensor: torch.Tensor, size: Tuple[int, int, int], interpolation: str = "bilinear", align_corners: bool = True
) -> torch.Tensor:
r"""Crop the 3D volumes (5D tensor) at the center.
@@ -229,7 +229,7 @@ def crop_by_boxes3d(
tensor: torch.Tensor,
src_box: torch.Tensor,
dst_box: torch.Tensor,
- interpolation: str = 'bilinear',
+ interpolation: str = "bilinear",
align_corners: bool = False,
) -> torch.Tensor:
"""Perform crop transform on 3D volumes (5D tensor) by bounding boxes.
@@ -332,8 +332,8 @@ def crop_by_transform_mat3d(
tensor: torch.Tensor,
transform: torch.Tensor,
out_size: Tuple[int, int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> torch.Tensor:
"""Perform crop transform on 3D volumes (5D tensor) given a perspective transformation matrix.
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index 72e2405ec..a15dcb61d 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -18,8 +18,8 @@ def elastic_transform2d(
sigma: Union[Tuple[float, float], Tensor] = (32.0, 32.0),
alpha: Union[Tuple[float, float], Tensor] = (1.0, 1.0),
align_corners: bool = False,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
) -> Tensor:
r"""Apply elastic transform of images as described in :cite:`Simard2003BestPF`.
@@ -62,8 +62,8 @@ def elastic_transform2d(
"""
KORNIA_CHECK_IS_TENSOR(image)
KORNIA_CHECK_IS_TENSOR(noise)
- KORNIA_CHECK_SHAPE(image, ['B', 'C', 'H', 'W'])
- KORNIA_CHECK_SHAPE(noise, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(image, ["B", "C", "H", "W"])
+ KORNIA_CHECK_SHAPE(noise, ["B", "C", "H", "W"])
device, dtype = image.device, image.dtype
# if isinstance(sigma, tuple):
@@ -87,8 +87,8 @@ def elastic_transform2d(
disp_x = noise[:, :1]
disp_y = noise[:, 1:]
- disp_x = filter2d(disp_x, kernel=kernel_y, border_type='constant') * alpha_x
- disp_y = filter2d(disp_y, kernel=kernel_x, border_type='constant') * alpha_y
+ disp_x = filter2d(disp_x, kernel=kernel_y, border_type="constant") * alpha_x
+ disp_y = filter2d(disp_y, kernel=kernel_x, border_type="constant") * alpha_y
# stack and normalize displacement
disp = concatenate([disp_x, disp_y], 1).permute(0, 2, 3, 1)
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 51d5d3f54..c925843a8 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -44,14 +44,15 @@ class HomographyWarper(BaseWarper):
normalized_coordinates: whether to use a grid with normalized coordinates.
align_corners: interpolation flag.
"""
+
_warped_grid: Optional[Tensor]
def __init__(
self,
height: int,
width: int,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
normalized_coordinates: bool = True,
align_corners: bool = False,
) -> None:
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 36cc5d79d..2f93e57df 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -38,7 +38,7 @@ class Homography(BaseModel):
self.reset_model()
def __repr__(self) -> str:
- return f'{self.__class__.__name__}({self.model})'
+ return f"{self.__class__.__name__}({self.model})"
def reset_model(self) -> None:
"""Initializes the model with identity transform."""
@@ -76,20 +76,20 @@ class Similarity(BaseModel):
if rotation:
self.rot = nn.Parameter(torch.zeros(1))
else:
- self.register_buffer('rot', torch.zeros(1))
+ self.register_buffer("rot", torch.zeros(1))
if shift:
self.shift = nn.Parameter(torch.zeros(1, 2, 1))
else:
- self.register_buffer('shift', torch.zeros(1, 2, 1))
+ self.register_buffer("shift", torch.zeros(1, 2, 1))
if scale:
self.scale = nn.Parameter(torch.ones(1))
else:
- self.register_buffer('scale', torch.ones(1))
+ self.register_buffer("scale", torch.ones(1))
self.reset_model()
def __repr__(self) -> str:
return (
- f'{self.__class__.__name__}(angle = {self.rot}, \n shift={self.shift}, \n scale={self.scale})'
+ f"{self.__class__.__name__}(angle = {self.rot}, \n shift={self.shift}, \n scale={self.scale})"
)
def reset_model(self) -> None:
@@ -141,7 +141,7 @@ class ImageRegistrator(Module):
# TODO: resolve better type, potentially using factory.
def __init__(
self,
- model_type: Union[str, BaseModel] = 'homography',
+ model_type: Union[str, BaseModel] = "homography",
optimizer: Type[optim.Optimizer] = optim.Adam,
loss_fn: Callable[..., Tensor] = F.l1_loss,
pyramid_levels: int = 5,
@@ -151,7 +151,7 @@ class ImageRegistrator(Module):
warper: Optional[Type[BaseWarper]] = None,
) -> None:
super().__init__()
- self.known_models = ['homography', 'similarity', 'translation', 'scale', 'rotation']
+ self.known_models = ["homography", "similarity", "translation", "scale", "rotation"]
# We provide pre-defined combinations or allow user to supply model
# together with warper
if not isinstance(model_type, str):
@@ -195,7 +195,7 @@ class ImageRegistrator(Module):
warper = self.warper(_height, _width)
img_src_to_dst = warper(img_src, transform_model)
# compute and mask loss
- loss = self.loss_fn(img_src_to_dst, img_dst, reduction='none') # 1xCxHxW
+ loss = self.loss_fn(img_src_to_dst, img_dst, reduction="none") # 1xCxHxW
ones = warper(torch.ones_like(img_src), transform_model)
loss = loss.masked_select(ones > 0.9).mean()
return loss
@@ -223,7 +223,7 @@ class ImageRegistrator(Module):
self.reset_model()
# ToDo: better parameter passing to optimizer
_opt_args: Dict[str, Any] = {}
- _opt_args['lr'] = self.lr
+ _opt_args["lr"] = self.lr
opt = self.optimizer(self.model.parameters(), **_opt_args)
# compute the gaussian pyramids
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index e54ef0ac7..c5030fa58 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -49,8 +49,8 @@ def warp_perspective(
src: Tensor,
M: Tensor,
dsize: tuple[int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
fill_value: Tensor = zeros(3), # needed for jit
) -> Tensor:
@@ -132,8 +132,8 @@ def warp_affine(
src: Tensor,
M: Tensor,
dsize: tuple[int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
fill_value: Tensor = zeros(3), # needed for jit
) -> Tensor:
@@ -459,8 +459,8 @@ def remap(
image: Tensor,
map_x: Tensor,
map_y: Tensor,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: Optional[bool] = None,
normalized_coordinates: bool = False,
) -> Tensor:
@@ -825,8 +825,8 @@ def warp_affine3d(
src: Tensor,
M: Tensor,
dsize: tuple[int, int, int],
- flags: str = 'bilinear',
- padding_mode: str = 'zeros',
+ flags: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = True,
) -> Tensor:
r"""Apply a projective transformation a to 3d tensor.
@@ -1049,9 +1049,9 @@ def get_perspective_transform3d(src: Tensor, dst: Tensor) -> Tensor:
# 000, 100, 110, 101, 011
for i in [0, 1, 2, 5, 7]:
- p.append(_build_perspective_param3d(src[:, i], dst[:, i], 'x'))
- p.append(_build_perspective_param3d(src[:, i], dst[:, i], 'y'))
- p.append(_build_perspective_param3d(src[:, i], dst[:, i], 'z'))
+ p.append(_build_perspective_param3d(src[:, i], dst[:, i], "x"))
+ p.append(_build_perspective_param3d(src[:, i], dst[:, i], "y"))
+ p.append(_build_perspective_param3d(src[:, i], dst[:, i], "z"))
# A is Bx15x15
A = stack(p, 1)
@@ -1097,7 +1097,7 @@ def _build_perspective_param3d(p: Tensor, q: Tensor, axis: str) -> Tensor:
ones = torch.ones_like(p)[..., 0:1]
zeros = torch.zeros_like(p)[..., 0:1]
- if axis == 'x':
+ if axis == "x":
return concatenate(
[
p[:, 0:1],
@@ -1119,7 +1119,7 @@ def _build_perspective_param3d(p: Tensor, q: Tensor, axis: str) -> Tensor:
1,
)
- if axis == 'y':
+ if axis == "y":
return concatenate(
[
zeros,
@@ -1141,7 +1141,7 @@ def _build_perspective_param3d(p: Tensor, q: Tensor, axis: str) -> Tensor:
1,
)
- if axis == 'z':
+ if axis == "z":
return concatenate(
[
zeros,
@@ -1170,8 +1170,8 @@ def warp_perspective3d(
src: Tensor,
M: Tensor,
dsize: tuple[int, int, int],
- flags: str = 'bilinear',
- border_mode: str = 'zeros',
+ flags: str = "bilinear",
+ border_mode: str = "zeros",
align_corners: bool = False,
) -> Tensor:
r"""Apply a perspective transformation to an image.
@@ -1222,8 +1222,8 @@ def homography_warp(
patch_src: Tensor,
src_homo_dst: Tensor,
dsize: tuple[int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = False,
normalized_coordinates: bool = True,
normalized_homography: bool = True,
@@ -1273,7 +1273,7 @@ def homography_warp(
return F.grid_sample(patch_src, warped_grid, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
return warp_perspective(
- patch_src, src_homo_dst, dsize, mode='bilinear', padding_mode=padding_mode, align_corners=True
+ patch_src, src_homo_dst, dsize, mode="bilinear", padding_mode=padding_mode, align_corners=True
)
@@ -1297,8 +1297,8 @@ def homography_warp3d(
patch_src: Tensor,
src_homo_dst: Tensor,
dsize: tuple[int, int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
align_corners: bool = False,
normalized_coordinates: bool = True,
) -> Tensor:
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 01222ea3a..1c1001d38 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -61,7 +61,7 @@ class PyrDown(Module):
>>> output = PyrDown()(input) # 1x2x2x2
"""
- def __init__(self, border_type: str = 'reflect', align_corners: bool = False, factor: float = 2.0) -> None:
+ def __init__(self, border_type: str = "reflect", align_corners: bool = False, factor: float = 2.0) -> None:
super().__init__()
self.border_type: str = border_type
self.align_corners: bool = align_corners
@@ -92,7 +92,7 @@ class PyrUp(Module):
>>> output = PyrUp()(input) # 1x2x8x8
"""
- def __init__(self, border_type: str = 'reflect', align_corners: bool = False) -> None:
+ def __init__(self, border_type: str = "reflect", align_corners: bool = False) -> None:
super().__init__()
self.border_type: str = border_type
self.align_corners: bool = align_corners
@@ -143,14 +143,14 @@ class ScalePyramid(Module):
def __repr__(self) -> str:
return (
- f'{self.__class__.__name__}('
- f'n_levels={self.n_levels}, '
- f'init_sigma={self.init_sigma}, '
- f'min_size={self.min_size}, '
- f'extra_levels={self.extra_levels}, '
- f'border={self.border}, '
- f'sigma_step={self.sigma_step}, '
- f'double_image={self.double_image})'
+ f"{self.__class__.__name__}("
+ f"n_levels={self.n_levels}, "
+ f"init_sigma={self.init_sigma}, "
+ f"min_size={self.min_size}, "
+ f"extra_levels={self.extra_levels}, "
+ f"border={self.border}, "
+ f"sigma_step={self.sigma_step}, "
+ f"double_image={self.double_image})"
)
def get_kernel_size(self, sigma: float) -> int:
@@ -227,7 +227,7 @@ class ScalePyramid(Module):
return output_pyr, sigmas, pixel_dists
-def pyrdown(input: Tensor, border_type: str = 'reflect', align_corners: bool = False, factor: float = 2.0) -> Tensor:
+def pyrdown(input: Tensor, border_type: str = "reflect", align_corners: bool = False, factor: float = 2.0) -> Tensor:
r"""Blur a tensor and downsamples it.
.. image:: _static/img/pyrdown.png
@@ -261,13 +261,13 @@ def pyrdown(input: Tensor, border_type: str = 'reflect', align_corners: bool = F
out: Tensor = F.interpolate(
x_blur,
size=(int(float(height) / factor), int(float(width) // factor)),
- mode='bilinear',
+ mode="bilinear",
align_corners=align_corners,
)
return out
-def pyrup(input: Tensor, border_type: str = 'reflect', align_corners: bool = False) -> Tensor:
+def pyrup(input: Tensor, border_type: str = "reflect", align_corners: bool = False) -> Tensor:
r"""Upsample a tensor and then blurs it.
.. image:: _static/img/pyrup.png
@@ -295,7 +295,7 @@ def pyrup(input: Tensor, border_type: str = 'reflect', align_corners: bool = Fal
# upsample tensor
_, _, height, width = input.shape
# TODO: use kornia.geometry.resize/rescale
- x_up: Tensor = F.interpolate(input, size=(height * 2, width * 2), mode='bilinear', align_corners=align_corners)
+ x_up: Tensor = F.interpolate(input, size=(height * 2, width * 2), mode="bilinear", align_corners=align_corners)
# blurs upsampled tensor
x_blur: Tensor = filter2d(x_up, kernel, border_type)
@@ -303,7 +303,7 @@ def pyrup(input: Tensor, border_type: str = 'reflect', align_corners: bool = Fal
def build_pyramid(
- input: Tensor, max_level: int, border_type: str = 'reflect', align_corners: bool = False
+ input: Tensor, max_level: int, border_type: str = "reflect", align_corners: bool = False
) -> list[Tensor]:
r"""Construct the Gaussian pyramid for a tensor image.
@@ -356,7 +356,7 @@ def find_next_powerof_two(x: int) -> int:
def build_laplacian_pyramid(
- input: Tensor, max_level: int, border_type: str = 'reflect', align_corners: bool = False
+ input: Tensor, max_level: int, border_type: str = "reflect", align_corners: bool = False
) -> list[Tensor]:
r"""Construct the Laplacian pyramid for a tensor image.
diff --git a/kornia/image/base.py b/kornia/image/base.py
index a351c415c..98c7c94f3 100644
--- a/kornia/image/base.py
+++ b/kornia/image/base.py
@@ -21,12 +21,14 @@ class ImageSize:
>>> size.width
4
"""
+
height: int | Tensor
width: int | Tensor
class ColorSpace(Enum):
r"""Enum that represents the color space of an image."""
+
UNKNOWN = 0 # for now, in case of multi band images
GRAY = 1
RGB = 2
@@ -55,6 +57,7 @@ class PixelFormat:
class ChannelsOrder(Enum):
r"""Enum that represents the channels order of an image."""
+
CHANNELS_FIRST = 0
CHANNELS_LAST = 1
diff --git a/kornia/io/io.py b/kornia/io/io.py
index cced7f16c..22cbae879 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -21,6 +21,7 @@ from kornia.core.check import KORNIA_CHECK
class ImageLoadType(Enum):
r"""Enum to specify the desired image type."""
+
UNCHANGED = 0
GRAY8 = 1
RGB8 = 2
diff --git a/kornia/losses/cauchy.py b/kornia/losses/cauchy.py
index a44194cdc..09b6b93c0 100644
--- a/kornia/losses/cauchy.py
+++ b/kornia/losses/cauchy.py
@@ -64,7 +64,7 @@ def cauchy_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
elif reduction == "none" or reduction is None:
pass
else:
- raise NotImplementedError('Invalid reduction option.')
+ raise NotImplementedError("Invalid reduction option.")
return loss
diff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.py
index 80e7e4f70..95a8e260c 100644
--- a/kornia/losses/charbonnier.py
+++ b/kornia/losses/charbonnier.py
@@ -70,7 +70,7 @@ def charbonnier_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Ten
elif reduction == "none" or reduction is None:
pass
else:
- raise NotImplementedError('Invalid reduction option.')
+ raise NotImplementedError("Invalid reduction option.")
return loss
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index 771025c46..b7bb7d56e 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -12,7 +12,7 @@ def _kl_div_2d(p: Tensor, q: Tensor) -> Tensor:
# D_KL(P || Q)
batch, chans, height, width = p.shape
unsummed_kl = F.kl_div(
- q.reshape(batch * chans, height * width).log(), p.reshape(batch * chans, height * width), reduction='none'
+ q.reshape(batch * chans, height * width).log(), p.reshape(batch * chans, height * width), reduction="none"
)
kl_values = unsummed_kl.sum(-1).view(batch, chans)
return kl_values
@@ -25,15 +25,13 @@ def _js_div_2d(p: Tensor, q: Tensor) -> Tensor:
# TODO: add this to the main module
-
-
def _reduce_loss(losses: Tensor, reduction: str) -> Tensor:
- if reduction == 'none':
+ if reduction == "none":
return losses
- return torch.mean(losses) if reduction == 'mean' else torch.sum(losses)
+ return torch.mean(losses) if reduction == "mean" else torch.sum(losses)
-def js_div_loss_2d(pred: Tensor, target: Tensor, reduction: str = 'mean') -> Tensor:
+def js_div_loss_2d(pred: Tensor, target: Tensor, reduction: str = "mean") -> Tensor:
r"""Calculate the Jensen-Shannon divergence loss between heatmaps.
Args:
@@ -54,7 +52,7 @@ def js_div_loss_2d(pred: Tensor, target: Tensor, reduction: str = 'mean') -> Ten
return _reduce_loss(_js_div_2d(target, pred), reduction)
-def kl_div_loss_2d(pred: Tensor, target: Tensor, reduction: str = 'mean') -> Tensor:
+def kl_div_loss_2d(pred: Tensor, target: Tensor, reduction: str = "mean") -> Tensor:
r"""Calculate the Kullback-Leibler divergence loss between heatmaps.
Args:
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index 707877caf..05e2a4fbe 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -18,7 +18,7 @@ def focal_loss(
target: Tensor,
alpha: Optional[float],
gamma: float = 2.0,
- reduction: str = 'none',
+ reduction: str = "none",
weight: Optional[Tensor] = None,
) -> Tensor:
r"""Criterion that computes Focal loss.
@@ -61,7 +61,7 @@ def focal_loss(
out_size = (pred.shape[0],) + pred.shape[2:]
KORNIA_CHECK(
(pred.shape[0] == target.shape[0] and target.shape[1:] == pred.shape[2:]),
- f'Expected target size {out_size}, got {target.shape}',
+ f"Expected target size {out_size}, got {target.shape}",
)
KORNIA_CHECK(
pred.device == target.device,
@@ -88,7 +88,7 @@ def focal_loss(
KORNIA_CHECK_IS_TENSOR(weight, "weight must be Tensor or None.")
KORNIA_CHECK(
(weight.shape[0] == num_of_classes and weight.numel() == num_of_classes),
- f'weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}',
+ f"weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}",
)
KORNIA_CHECK(
weight.device == pred.device,
@@ -98,11 +98,11 @@ def focal_loss(
weight = weight.view(boradcast_dims)
loss_tmp = weight * loss_tmp
- if reduction == 'none':
+ if reduction == "none":
loss = loss_tmp
- elif reduction == 'mean':
+ elif reduction == "mean":
loss = torch.mean(loss_tmp)
- elif reduction == 'sum':
+ elif reduction == "sum":
loss = torch.sum(loss_tmp)
else:
raise NotImplementedError(f"Invalid reduction mode: {reduction}")
@@ -147,7 +147,7 @@ class FocalLoss(nn.Module):
"""
def __init__(
- self, alpha: Optional[float], gamma: float = 2.0, reduction: str = 'none', weight: Optional[Tensor] = None
+ self, alpha: Optional[float], gamma: float = 2.0, reduction: str = "none", weight: Optional[Tensor] = None
) -> None:
super().__init__()
self.alpha: Optional[float] = alpha
@@ -164,7 +164,7 @@ def binary_focal_loss_with_logits(
target: Tensor,
alpha: Optional[float] = 0.25,
gamma: float = 2.0,
- reduction: str = 'none',
+ reduction: str = "none",
pos_weight: Optional[Tensor] = None,
weight: Optional[Tensor] = None,
) -> Tensor:
@@ -207,7 +207,7 @@ def binary_focal_loss_with_logits(
"""
KORNIA_CHECK_SHAPE(pred, ["B", "C", "*"])
- KORNIA_CHECK(pred.shape == target.shape, f'Expected target size {pred.shape}, got {target.shape}')
+ KORNIA_CHECK(pred.shape == target.shape, f"Expected target size {pred.shape}, got {target.shape}")
KORNIA_CHECK(
pred.device == target.device,
f"pred and target must be in the same device. Got: {pred.device} and {target.device}",
@@ -228,7 +228,7 @@ def binary_focal_loss_with_logits(
KORNIA_CHECK_IS_TENSOR(pos_weight, "pos_weight must be Tensor or None.")
KORNIA_CHECK(
(pos_weight.shape[0] == num_of_classes and pos_weight.numel() == num_of_classes),
- f'pos_weight shape must be (num_of_classes,): ({num_of_classes},), got {pos_weight.shape}',
+ f"pos_weight shape must be (num_of_classes,): ({num_of_classes},), got {pos_weight.shape}",
)
KORNIA_CHECK(
pos_weight.device == pred.device,
@@ -243,7 +243,7 @@ def binary_focal_loss_with_logits(
KORNIA_CHECK_IS_TENSOR(weight, "weight must be Tensor or None.")
KORNIA_CHECK(
(weight.shape[0] == num_of_classes and weight.numel() == num_of_classes),
- f'weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}',
+ f"weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}",
)
KORNIA_CHECK(
weight.device == pred.device,
@@ -253,11 +253,11 @@ def binary_focal_loss_with_logits(
weight = weight.view(boradcast_dims)
loss_tmp = weight * loss_tmp
- if reduction == 'none':
+ if reduction == "none":
loss = loss_tmp
- elif reduction == 'mean':
+ elif reduction == "mean":
loss = torch.mean(loss_tmp)
- elif reduction == 'sum':
+ elif reduction == "sum":
loss = torch.sum(loss_tmp)
else:
raise NotImplementedError(f"Invalid reduction mode: {reduction}")
@@ -307,7 +307,7 @@ class BinaryFocalLossWithLogits(nn.Module):
self,
alpha: Optional[float],
gamma: float = 2.0,
- reduction: str = 'none',
+ reduction: str = "none",
pos_weight: Optional[Tensor] = None,
weight: Optional[Tensor] = None,
) -> None:
diff --git a/kornia/losses/geman_mcclure.py b/kornia/losses/geman_mcclure.py
index 5beaed5b0..28a768b71 100644
--- a/kornia/losses/geman_mcclure.py
+++ b/kornia/losses/geman_mcclure.py
@@ -64,7 +64,7 @@ def geman_mcclure_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> T
elif reduction == "none" or reduction is None:
pass
else:
- raise NotImplementedError('Invalid reduction option.')
+ raise NotImplementedError("Invalid reduction option.")
return loss
diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.py
index d3934bf33..7c9f3f80c 100644
--- a/kornia/losses/hausdorff.py
+++ b/kornia/losses/hausdorff.py
@@ -30,7 +30,7 @@ class _HausdorffERLossBase(Module):
conv: Callable[..., Tensor]
max_pool: Callable[..., Tensor]
- def __init__(self, alpha: float = 2.0, k: int = 10, reduction: str = 'mean') -> None:
+ def __init__(self, alpha: float = 2.0, k: int = 10, reduction: str = "mean") -> None:
super().__init__()
self.alpha = alpha
self.k = k
@@ -110,11 +110,11 @@ class _HausdorffERLossBase(Module):
]
)
- if self.reduction == 'mean':
+ if self.reduction == "mean":
out = out.mean()
- elif self.reduction == 'sum':
+ elif self.reduction == "sum":
out = out.sum()
- elif self.reduction == 'none':
+ elif self.reduction == "none":
pass
else:
raise NotImplementedError(f"reduction `{self.reduction}` has not been implemented yet.")
diff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.py
index 8d2378019..65c6049bc 100644
--- a/kornia/losses/ms_ssim.py
+++ b/kornia/losses/ms_ssim.py
@@ -61,7 +61,7 @@ class MS_SSIMLoss(nn.Module):
K: tuple[float, float] = (0.01, 0.03),
alpha: float = 0.025,
compensation: float = 200.0,
- reduction: str = 'mean',
+ reduction: str = "mean",
) -> None:
super().__init__()
self.DR: float = data_range
@@ -82,7 +82,7 @@ class MS_SSIMLoss(nn.Module):
g_masks[3 * idx + 1, 0, :, :] = self._fspecial_gauss_2d(filter_size, sigma)
g_masks[3 * idx + 2, 0, :, :] = self._fspecial_gauss_2d(filter_size, sigma)
- self.register_buffer('_g_masks', g_masks)
+ self.register_buffer("_g_masks", g_masks)
def _fspecial_gauss_1d(
self, size: int, sigma: float, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
@@ -159,7 +159,7 @@ class MS_SSIMLoss(nn.Module):
# TODO: pass pointer to function e.g. to make more custom with mse, cosine, etc.
# Compute L1 loss
- loss_l1 = F.l1_loss(img1, img2, reduction='none')
+ loss_l1 = F.l1_loss(img1, img2, reduction="none")
# Compute average l1 loss in 3 channels
gaussian_l1 = F.conv2d(loss_l1, g_masks[-CH:], groups=CH, padding=self.pad).mean(1)
diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.py
index 18d13f719..2abc1bcdc 100644
--- a/kornia/losses/ssim.py
+++ b/kornia/losses/ssim.py
@@ -12,8 +12,8 @@ def ssim_loss(
window_size: int,
max_val: float = 1.0,
eps: float = 1e-12,
- reduction: str = 'mean',
- padding: str = 'same',
+ reduction: str = "mean",
+ padding: str = "same",
) -> torch.Tensor:
r"""Function that computes a loss based on the SSIM measurement.
@@ -59,7 +59,7 @@ def ssim_loss(
elif reduction == "none":
pass
else:
- raise NotImplementedError('Invalid reduction option.')
+ raise NotImplementedError("Invalid reduction option.")
return loss
@@ -97,7 +97,7 @@ class SSIMLoss(nn.Module):
"""
def __init__(
- self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, reduction: str = 'mean', padding: str = 'same'
+ self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, reduction: str = "mean", padding: str = "same"
) -> None:
super().__init__()
self.window_size: int = window_size
diff --git a/kornia/losses/ssim3d.py b/kornia/losses/ssim3d.py
index e74f2fdfc..7d8a9860d 100644
--- a/kornia/losses/ssim3d.py
+++ b/kornia/losses/ssim3d.py
@@ -10,8 +10,8 @@ def ssim3d_loss(
window_size: int,
max_val: float = 1.0,
eps: float = 1e-12,
- reduction: str = 'mean',
- padding: str = 'same',
+ reduction: str = "mean",
+ padding: str = "same",
) -> Tensor:
r"""Function that computes a loss based on the SSIM measurement.
@@ -57,7 +57,7 @@ def ssim3d_loss(
elif reduction == "none":
pass
else:
- raise NotImplementedError('Invalid reduction option.')
+ raise NotImplementedError("Invalid reduction option.")
return loss
@@ -95,7 +95,7 @@ class SSIM3DLoss(Module):
"""
def __init__(
- self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, reduction: str = 'mean', padding: str = 'same'
+ self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, reduction: str = "mean", padding: str = "same"
) -> None:
super().__init__()
self.window_size: int = window_size
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index 96d0c55a6..9a2e8626a 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -55,7 +55,7 @@ def total_variation(img: Tensor, reduction: str = "sum") -> Tensor:
res1 = res1.sum(dim=reduce_axes)
res2 = res2.sum(dim=reduce_axes)
else:
- raise NotImplementedError('Invalid reduction option.')
+ raise NotImplementedError("Invalid reduction option.")
return res1 + res2
diff --git a/kornia/losses/welsch.py b/kornia/losses/welsch.py
index 11bf1584a..869bd99c9 100644
--- a/kornia/losses/welsch.py
+++ b/kornia/losses/welsch.py
@@ -63,7 +63,7 @@ def welsch_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
elif reduction == "none":
pass
else:
- raise NotImplementedError('Invalid reduction option.')
+ raise NotImplementedError("Invalid reduction option.")
return loss
diff --git a/kornia/metrics/endpoint_error.py b/kornia/metrics/endpoint_error.py
index 1188e5e94..d8d01a6b3 100644
--- a/kornia/metrics/endpoint_error.py
+++ b/kornia/metrics/endpoint_error.py
@@ -50,7 +50,7 @@ def aepe(input: torch.Tensor, target: torch.Tensor, reduction: str = "mean") ->
elif reduction == "none":
pass
else:
- raise NotImplementedError('Invalid reduction option.')
+ raise NotImplementedError("Invalid reduction option.")
return epe
@@ -83,7 +83,7 @@ class AEPE(nn.Module):
>>> epe = epe(input1, input2)
"""
- def __init__(self, reduction: str = 'mean') -> None:
+ def __init__(self, reduction: str = "mean") -> None:
super().__init__()
self.reduction: str = reduction
diff --git a/kornia/metrics/psnr.py b/kornia/metrics/psnr.py
index ba40e0748..a006bd0f9 100644
--- a/kornia/metrics/psnr.py
+++ b/kornia/metrics/psnr.py
@@ -46,4 +46,4 @@ def psnr(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Ten
if image.shape != target.shape:
raise TypeError(f"Expected tensors of equal shapes, but got {image.shape} and {target.shape}")
- return 10.0 * torch.log10(max_val**2 / mse(image, target, reduction='mean'))
+ return 10.0 * torch.log10(max_val**2 / mse(image, target, reduction="mean"))
diff --git a/kornia/metrics/ssim.py b/kornia/metrics/ssim.py
index 9cf8f682e..3887d2dac 100644
--- a/kornia/metrics/ssim.py
+++ b/kornia/metrics/ssim.py
@@ -20,7 +20,7 @@ def ssim(
window_size: int,
max_val: float = 1.0,
eps: float = 1e-12,
- padding: str = 'same',
+ padding: str = "same",
) -> torch.Tensor:
r"""Function that computes the Structural Similarity (SSIM) index map between two images.
@@ -86,12 +86,12 @@ def ssim(
mu2: torch.Tensor = filter2d_separable(img2, kernel, kernel)
cropping_shape: List[int] = []
- if padding == 'valid':
+ if padding == "valid":
height = width = kernel.shape[-1]
cropping_shape = _compute_padding([height, width])
mu1 = _crop(mu1, cropping_shape)
mu2 = _crop(mu2, cropping_shape)
- elif padding == 'same':
+ elif padding == "same":
pass
mu1_sq = mu1**2
@@ -102,11 +102,11 @@ def ssim(
mu_img2_sq = filter2d_separable(img2**2, kernel, kernel)
mu_img1_img2 = filter2d_separable(img1 * img2, kernel, kernel)
- if padding == 'valid':
+ if padding == "valid":
mu_img1_sq = _crop(mu_img1_sq, cropping_shape)
mu_img2_sq = _crop(mu_img2_sq, cropping_shape)
mu_img1_img2 = _crop(mu_img1_img2, cropping_shape)
- elif padding == 'same':
+ elif padding == "same":
pass
# compute local sigma per channel
@@ -158,7 +158,7 @@ class SSIM(nn.Module):
>>> ssim_map = ssim(input1, input2) # 1x4x5x5
"""
- def __init__(self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, padding: str = 'same') -> None:
+ def __init__(self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, padding: str = "same") -> None:
super().__init__()
self.window_size: int = window_size
self.max_val: float = max_val
diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.py
index cd7e9cfb3..840338f47 100644
--- a/kornia/metrics/ssim3d.py
+++ b/kornia/metrics/ssim3d.py
@@ -22,7 +22,7 @@ def _crop(img: Tensor, cropping_shape: List[int]) -> Tensor:
def ssim3d(
- img1: Tensor, img2: Tensor, window_size: int, max_val: float = 1.0, eps: float = 1e-12, padding: str = 'same'
+ img1: Tensor, img2: Tensor, window_size: int, max_val: float = 1.0, eps: float = 1e-12, padding: str = "same"
) -> Tensor:
r"""Function that computes the Structural Similarity (SSIM) index map between two images.
@@ -79,12 +79,12 @@ def ssim3d(
mu2: Tensor = filter3d(img2, kernel)
cropping_shape: List[int] = []
- if padding == 'valid':
+ if padding == "valid":
depth, height, width = kernel.shape[-3:]
cropping_shape = _compute_padding([depth, height, width])
mu1 = _crop(mu1, cropping_shape)
mu2 = _crop(mu2, cropping_shape)
- elif padding == 'same':
+ elif padding == "same":
pass
mu1_sq = mu1**2
@@ -95,11 +95,11 @@ def ssim3d(
mu_img2_sq = filter3d(img2**2, kernel)
mu_img1_img2 = filter3d(img1 * img2, kernel)
- if padding == 'valid':
+ if padding == "valid":
mu_img1_sq = _crop(mu_img1_sq, cropping_shape)
mu_img2_sq = _crop(mu_img2_sq, cropping_shape)
mu_img1_img2 = _crop(mu_img1_img2, cropping_shape)
- elif padding == 'same':
+ elif padding == "same":
pass
# compute local sigma per channel
@@ -151,7 +151,7 @@ class SSIM3D(Module):
>>> ssim_map = ssim(input1, input2) # 1x4x5x5x5
"""
- def __init__(self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, padding: str = 'same') -> None:
+ def __init__(self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, padding: str = "same") -> None:
super().__init__()
self.window_size: int = window_size
self.max_val: float = max_val
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index 0b91446ae..23431781c 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -17,10 +17,10 @@ def dilation(
kernel: torch.Tensor,
structuring_element: Optional[torch.Tensor] = None,
origin: Optional[List[int]] = None,
- border_type: str = 'geodesic',
+ border_type: str = "geodesic",
border_value: float = 0.0,
max_val: float = 1e4,
- engine: str = 'unfold',
+ engine: str = "unfold",
) -> torch.Tensor:
r"""Return the dilated image applying the same kernel in each channel.
@@ -75,9 +75,9 @@ def dilation(
# pad
pad_e: List[int] = [origin[1], se_w - origin[1] - 1, origin[0], se_h - origin[0] - 1]
- if border_type == 'geodesic':
+ if border_type == "geodesic":
border_value = -max_val
- border_type = 'constant'
+ border_type = "constant"
output: torch.Tensor = F.pad(tensor, pad_e, mode=border_type, value=border_value)
# computation
@@ -88,11 +88,11 @@ def dilation(
neighborhood = structuring_element.clone()
neighborhood[kernel == 0] = -max_val
- if engine == 'unfold':
+ if engine == "unfold":
output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)
output, _ = torch.max(output + neighborhood.flip((0, 1)), 4)
output, _ = torch.max(output, 4)
- elif engine == 'convolution':
+ elif engine == "convolution":
B, C, H, W = tensor.size()
h_pad, w_pad = output.shape[-2:]
reshape_kernel = _neight2channels_like_kernel(kernel)
@@ -110,10 +110,10 @@ def erosion(
kernel: torch.Tensor,
structuring_element: Optional[torch.Tensor] = None,
origin: Optional[List[int]] = None,
- border_type: str = 'geodesic',
+ border_type: str = "geodesic",
border_value: float = 0.0,
max_val: float = 1e4,
- engine: str = 'unfold',
+ engine: str = "unfold",
) -> torch.Tensor:
r"""Return the eroded image applying the same kernel in each channel.
@@ -168,9 +168,9 @@ def erosion(
# pad
pad_e: List[int] = [origin[1], se_w - origin[1] - 1, origin[0], se_h - origin[0] - 1]
- if border_type == 'geodesic':
+ if border_type == "geodesic":
border_value = max_val
- border_type = 'constant'
+ border_type = "constant"
output: torch.Tensor = F.pad(tensor, pad_e, mode=border_type, value=border_value)
# computation
@@ -181,11 +181,11 @@ def erosion(
neighborhood = structuring_element.clone()
neighborhood[kernel == 0] = -max_val
- if engine == 'unfold':
+ if engine == "unfold":
output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)
output, _ = torch.min(output - neighborhood, 4)
output, _ = torch.min(output, 4)
- elif engine == 'convolution':
+ elif engine == "convolution":
B, C, H, W = tensor.size()
Hpad, Wpad = output.shape[-2:]
reshape_kernel = _neight2channels_like_kernel(kernel)
@@ -204,10 +204,10 @@ def opening(
kernel: torch.Tensor,
structuring_element: Optional[torch.Tensor] = None,
origin: Optional[List[int]] = None,
- border_type: str = 'geodesic',
+ border_type: str = "geodesic",
border_value: float = 0.0,
max_val: float = 1e4,
- engine: str = 'unfold',
+ engine: str = "unfold",
) -> torch.Tensor:
r"""Return the opened image, (that means, dilation after an erosion) applying the same kernel in each channel.
@@ -281,10 +281,10 @@ def closing(
kernel: torch.Tensor,
structuring_element: Optional[torch.Tensor] = None,
origin: Optional[List[int]] = None,
- border_type: str = 'geodesic',
+ border_type: str = "geodesic",
border_value: float = 0.0,
max_val: float = 1e4,
- engine: str = 'unfold',
+ engine: str = "unfold",
) -> torch.Tensor:
r"""Return the closed image, (that means, erosion after a dilation) applying the same kernel in each channel.
@@ -359,10 +359,10 @@ def gradient(
kernel: torch.Tensor,
structuring_element: Optional[torch.Tensor] = None,
origin: Optional[List[int]] = None,
- border_type: str = 'geodesic',
+ border_type: str = "geodesic",
border_value: float = 0.0,
max_val: float = 1e4,
- engine: str = 'unfold',
+ engine: str = "unfold",
) -> torch.Tensor:
r"""Return the morphological gradient of an image.
@@ -425,10 +425,10 @@ def top_hat(
kernel: torch.Tensor,
structuring_element: Optional[torch.Tensor] = None,
origin: Optional[List[int]] = None,
- border_type: str = 'geodesic',
+ border_type: str = "geodesic",
border_value: float = 0.0,
max_val: float = 1e4,
- engine: str = 'unfold',
+ engine: str = "unfold",
) -> torch.Tensor:
r"""Return the top hat transformation of an image.
@@ -496,10 +496,10 @@ def bottom_hat(
kernel: torch.Tensor,
structuring_element: Optional[torch.Tensor] = None,
origin: Optional[List[int]] = None,
- border_type: str = 'geodesic',
+ border_type: str = "geodesic",
border_value: float = 0.0,
max_val: float = 1e4,
- engine: str = 'unfold',
+ engine: str = "unfold",
) -> torch.Tensor:
r"""Return the bottom hat transformation of an image.
diff --git a/kornia/nerf/camera_utils.py b/kornia/nerf/camera_utils.py
index f8e166f18..ea71ee2f0 100755
--- a/kornia/nerf/camera_utils.py
+++ b/kornia/nerf/camera_utils.py
@@ -29,16 +29,16 @@ def parse_colmap_output(
class CameraParams:
def __init__(self, line: str) -> None:
- split_line = line.split(' ')
+ split_line = line.split(" ")
model = split_line[1]
- if model == 'SIMPLE_PINHOLE':
+ if model == "SIMPLE_PINHOLE":
self._width = int(split_line[2])
self._height = int(split_line[3])
self._fx = float(split_line[4])
self._fy = self._fx
self._cx = int(split_line[5])
self._cy = int(split_line[6])
- elif model == 'PINHOLE':
+ elif model == "PINHOLE":
self._width = int(split_line[2])
self._height = int(split_line[3])
self._fx = float(split_line[4])
@@ -48,7 +48,7 @@ def parse_colmap_output(
cameras_params: List[CameraParams] = []
for line in lines:
- if line.startswith('#'):
+ if line.startswith("#"):
continue
camera_params = CameraParams(line)
cameras_params.append(camera_params)
@@ -62,13 +62,13 @@ def parse_colmap_output(
widths: List[int] = []
img_names: List[str] = []
for line in lines:
- if line.startswith('#'):
+ if line.startswith("#"):
continue
# Read line with camera quaternion
line = line.strip()
- if line.endswith(('jpg', 'png')):
- split_line = line.split(' ')
+ if line.endswith(("jpg", "png")):
+ split_line = line.split(" ")
qw = float(split_line[1])
qx = float(split_line[2])
qy = float(split_line[3])
diff --git a/kornia/nerf/data_utils.py b/kornia/nerf/data_utils.py
index 2d06a513b..e2deac41b 100755
--- a/kornia/nerf/data_utils.py
+++ b/kornia/nerf/data_utils.py
@@ -71,7 +71,7 @@ class RayDataset(Dataset[RayGroup]):
elif _is_list_of_tensors(imgs):
images = imgs # Take images provided on input
else:
- raise TypeError(f'Expected a list of image tensors or image paths. Gotcha {type(imgs)}.')
+ raise TypeError(f"Expected a list of image tensors or image paths. Gotcha {type(imgs)}.")
self._check_dimensions(images)
@@ -98,20 +98,20 @@ class RayDataset(Dataset[RayGroup]):
def _check_image_type_consistency(self, imgs: Images) -> None:
if not all(isinstance(img, str) for img in imgs) and not all(isinstance(img, Tensor) for img in imgs):
- raise ValueError('The list of input images can only be all paths or tensors')
+ raise ValueError("The list of input images can only be all paths or tensors")
def _check_dimensions(self, imgs: ImageTensors) -> None:
if len(imgs) != self._cameras.batch_size:
raise ValueError(
- f'Number of images {len(imgs)} does not match number of cameras {self._cameras.batch_size}'
+ f"Number of images {len(imgs)} does not match number of cameras {self._cameras.batch_size}"
)
if not all(img.shape[0] == 3 for img in imgs):
- raise ValueError('Not all input images have 3 channels')
+ raise ValueError("Not all input images have 3 channels")
for i, (img, height, width) in enumerate(zip(imgs, self._cameras.height, self._cameras.width)):
if img.shape[1:] != (height, width):
raise ValueError(
- f'Image index {i} dimensions {(img.shape[1], img.shape[2])} are inconsistent with equivalent '
- f'camera dimensions {(height.item(), width.item())}'
+ f"Image index {i} dimensions {(img.shape[1], img.shape[2])} are inconsistent with equivalent "
+ f"camera dimensions {(height.item(), width.item())}"
)
@staticmethod
@@ -137,7 +137,7 @@ class RayDataset(Dataset[RayGroup]):
coordinates: RayGroup
"""
if not isinstance(self._ray_sampler, RaySampler):
- raise TypeError('Ray sampler is not initiate yet, please run self.init_ray_dataset() before use it.')
+ raise TypeError("Ray sampler is not initiate yet, please run self.init_ray_dataset() before use it.")
origins = self._ray_sampler.origins[idxs]
directions = self._ray_sampler.directions[idxs]
diff --git a/kornia/nerf/nerf_solver.py b/kornia/nerf/nerf_solver.py
index 512416cad..650624c52 100755
--- a/kornia/nerf/nerf_solver.py
+++ b/kornia/nerf/nerf_solver.py
@@ -21,6 +21,7 @@ class NerfSolver:
device: device for class tensors: Union[str, Device]
dtype: type for all floating point calculations: torch.dtype
"""
+
_nerf_model: Module
_opt_nerf: optim.Optimizer
@@ -87,7 +88,7 @@ class NerfSolver:
elif torch.is_tensor(num_img_rays):
self._num_img_rays = num_img_rays
else:
- raise TypeError('num_img_rays can be either an int or a Tensor')
+ raise TypeError("num_img_rays can be either an int or a Tensor")
self._batch_size = batch_size
@@ -139,7 +140,7 @@ class NerfSolver:
Average psnr over all epoch rays
"""
if self._cameras is None:
- raise TypeError('The camera should be a PinholeCamera. Gotcha None. You init the training before train?')
+ raise TypeError("The camera should be a PinholeCamera. Gotcha None. You init the training before train?")
ray_dataset = RayDataset(
self._cameras, self._min_depth, self._max_depth, self._ndc, device=self._device, dtype=self._dtype
@@ -147,12 +148,12 @@ class NerfSolver:
if isinstance(self._num_img_rays, int):
raise TypeError(
- 'The number of images of Ray should be a tensor. Gotcha an integer. You init the training before train?'
+ "The number of images of Ray should be a tensor. Gotcha an integer. You init the training before train?"
)
ray_dataset.init_ray_dataset(self._num_img_rays)
if self._imgs is None:
- raise TypeError('Invalid image list object')
+ raise TypeError("Invalid image list object")
ray_dataset.init_images_for_training(self._imgs) # FIXME: Do we need to load the same images on each Epoch?
ray_data_loader = instantiate_ray_dataloader(ray_dataset, self._batch_size, shuffle=True)
@@ -179,7 +180,7 @@ class NerfSolver:
if i_epoch % 10 == 0:
current_time = datetime.now().strftime("%H:%M:%S") # noqa: DTZ005
- print(f'Epoch: {i_epoch}: epoch_psnr = {epoch_psnr}; time: {current_time}')
+ print(f"Epoch: {i_epoch}: epoch_psnr = {epoch_psnr}; time: {current_time}")
def render_views(self, cameras: PinholeCamera) -> ImageTensors:
r"""Renders a novel synthesis view of a trained NeRF model for given cameras.
diff --git a/kornia/nerf/positional_encoder.py b/kornia/nerf/positional_encoder.py
index eaa5dbb9c..45ef61341 100755
--- a/kornia/nerf/positional_encoder.py
+++ b/kornia/nerf/positional_encoder.py
@@ -56,10 +56,10 @@ class PositionalEncoder(nn.Module):
Tensor with encoded position/direction: Tensor
"""
if x.ndim < 1:
- raise ValueError('Input tensor represents a scalar')
+ raise ValueError("Input tensor represents a scalar")
if x.shape[-1] != self._num_dims:
raise ValueError(
- f'Input tensor number of dimensions {x.shape[-1]} does not match instantiated dimensionality '
- f'{self._num_dims}'
+ f"Input tensor number of dimensions {x.shape[-1]} does not match instantiated dimensionality "
+ f"{self._num_dims}"
)
return torch.cat([fn(x) for fn in self._embed_fns], dim=-1)
diff --git a/kornia/nerf/rays.py b/kornia/nerf/rays.py
index 6d08fba8c..b27c459fa 100755
--- a/kornia/nerf/rays.py
+++ b/kornia/nerf/rays.py
@@ -19,6 +19,7 @@ class RaySampler:
ndc: convert ray parameters to normalized device coordinates: bool
device: device for ray tensors: Union[str, torch.device]
"""
+
_origins: Tensor # Ray origins in world coordinates (*, 3)
_directions: Tensor # Ray directions in world coordinates (*, 3)
_directions_cam: Tensor # Ray directions in camera coordinates (*, 3)
@@ -283,8 +284,8 @@ class RandomRaySampler(RaySampler):
num_cams = cameras.batch_size
if num_cams != num_img_rays.shape[0]:
raise ValueError(
- f'Number of cameras {num_cams} does not match size of tensor to define number of rays to march from '
- f'each camera {num_img_rays.shape[0]}'
+ f"Number of cameras {num_cams} does not match size of tensor to define number of rays to march from "
+ f"each camera {num_img_rays.shape[0]}"
)
points_2d_camera = self.sample_points_2d(cameras.height, cameras.width, num_img_rays)
self._calc_ray_params(cameras, points_2d_camera)
@@ -325,7 +326,7 @@ class RandomGridRaySampler(RandomRaySampler):
n_sqrt = int(math.sqrt(n))
y_rand = torch.randperm(int(height), device=self._device, dtype=self._dtype)[: min(int(height), n_sqrt)]
x_rand = torch.randperm(int(width), device=self._device, dtype=self._dtype)[: min(int(width), n_sqrt)]
- y_grid, x_grid = torch_meshgrid([y_rand, x_rand], indexing='ij')
+ y_grid, x_grid = torch_meshgrid([y_rand, x_rand], indexing="ij")
RaySampler._add_points2d_as_flat_tensors_to_num_ray_dict(
n_sqrt * n_sqrt, x_grid, y_grid, camera_id, points2d_as_flat_tensors
)
@@ -369,7 +370,7 @@ class UniformRaySampler(RaySampler):
torch.arange(0, height, sampling_step, device=self._device, dtype=self._dtype),
torch.arange(0, width, sampling_step, device=self._device, dtype=self._dtype),
],
- indexing='ij',
+ indexing="ij",
)
RaySampler._add_points2d_as_flat_tensors_to_num_ray_dict(
n, x_grid, y_grid, camera_id, points2d_as_flat_tensors
@@ -385,7 +386,7 @@ def sample_lengths(
num_rays: int, num_ray_points: int, device: Device, dtype: torch.dtype, irregular: bool = False
) -> Tensor:
if num_ray_points <= 1:
- raise ValueError('Number of ray points must be greater than 1')
+ raise ValueError("Number of ray points must be greater than 1")
if not irregular:
zero_to_one = torch.linspace(0.0, 1.0, num_ray_points, device=device, dtype=dtype)
lengths = zero_to_one.repeat(num_rays, 1) # FIXME: Expand instead of repeat maybe?
diff --git a/kornia/nerf/renderer.py b/kornia/nerf/renderer.py
index 064c94fcd..f1d944583 100755
--- a/kornia/nerf/renderer.py
+++ b/kornia/nerf/renderer.py
@@ -11,6 +11,7 @@ class VolumeRenderer(torch.nn.Module):
Args:
shift: Size of far-field layer: int
"""
+
_huge = 1.0e10
_eps = 1.0e-10
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index f61a466d9..d1eb5eb45 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -24,7 +24,7 @@ def xla_is_available() -> bool:
def is_mps_tensor_safe(x: Tensor) -> bool:
"""Return whether tensor is on MPS device."""
- return 'mps' in str(x.device)
+ return "mps" in str(x.device)
# TODO: Isn't this function duplicated with eye_like?
@@ -52,7 +52,7 @@ def tensor_to_gradcheck_var(
return tensor.requires_grad_(requires_grad).type(dtype)
-T = TypeVar('T')
+T = TypeVar("T")
def dict_to(data: Dict[T, Any], device: Device, dtype: Dtype) -> Dict[T, Any]:
@@ -141,7 +141,7 @@ class BaseTester(ABC):
if hasattr(expected, "data"):
expected = expected.data
- if 'xla' in actual.device.type or 'xla' in expected.device.type:
+ if "xla" in actual.device.type or "xla" in expected.device.type:
rtol, atol = 1e-2, 1e-2
if rtol is None and atol is None:
@@ -178,20 +178,20 @@ def generate_two_view_random_scene(
scene: Dict[str, Tensor] = epi.generate_scene(num_views, num_points)
# internal parameters (same K)
- K1 = scene['K'].to(device, dtype)
+ K1 = scene["K"].to(device, dtype)
K2 = K1.clone()
# rotation
- R1 = scene['R'][0:1].to(device, dtype)
- R2 = scene['R'][1:2].to(device, dtype)
+ R1 = scene["R"][0:1].to(device, dtype)
+ R2 = scene["R"][1:2].to(device, dtype)
# translation
- t1 = scene['t'][0:1].to(device, dtype)
- t2 = scene['t'][1:2].to(device, dtype)
+ t1 = scene["t"][0:1].to(device, dtype)
+ t2 = scene["t"][1:2].to(device, dtype)
# projection matrix, P = K(R|t)
- P1 = scene['P'][0:1].to(device, dtype)
- P2 = scene['P'][1:2].to(device, dtype)
+ P1 = scene["P"][0:1].to(device, dtype)
+ P2 = scene["P"][1:2].to(device, dtype)
# fundamental matrix
F_mat = epi.fundamental_from_projections(P1[..., :3, :], P2[..., :3, :])
@@ -199,11 +199,11 @@ def generate_two_view_random_scene(
F_mat = epi.normalize_transformation(F_mat)
# points 3d
- X = scene['points3d'].to(device, dtype)
+ X = scene["points3d"].to(device, dtype)
# projected points
- x1 = scene['points2d'][0:1].to(device, dtype)
- x2 = scene['points2d'][1:2].to(device, dtype)
+ x1 = scene["points2d"][0:1].to(device, dtype)
+ x2 = scene["points2d"][1:2].to(device, dtype)
return {
"K1": K1,
@@ -242,7 +242,7 @@ def default_with_one_parameter_changed(*, default: Dict[str, Any] = {}, **possib
def _get_precision(device: torch.device, dtype: Dtype) -> float:
- if 'xla' in device.type:
+ if "xla" in device.type:
return 1e-2
if dtype == torch.float16:
return 1e-3
@@ -252,7 +252,7 @@ def _get_precision(device: torch.device, dtype: Dtype) -> float:
def _get_precision_by_name(
device: torch.device, device_target: str, tol_val: float, tol_val_default: float = 1e-4
) -> float:
- if device_target not in ['cpu', 'cuda', 'xla', 'mps']:
+ if device_target not in ["cpu", "cuda", "xla", "mps"]:
raise ValueError(f"Invalid device name: {device_target}.")
if device_target in device.type:
diff --git a/kornia/tracking/planar_tracker.py b/kornia/tracking/planar_tracker.py
index 80cbf93b9..70f976e02 100644
--- a/kornia/tracking/planar_tracker.py
+++ b/kornia/tracking/planar_tracker.py
@@ -32,10 +32,10 @@ class HomographyTracker(Module):
) -> None:
super().__init__()
self.initial_matcher = initial_matcher or (
- LocalFeatureMatcher(GFTTAffNetHardNet(3000), DescriptorMatcher('smnn', 0.95))
+ LocalFeatureMatcher(GFTTAffNetHardNet(3000), DescriptorMatcher("smnn", 0.95))
)
- self.fast_matcher = fast_matcher or LoFTR('outdoor')
- self.ransac = ransac or RANSAC('homography', inl_th=5.0, batch_size=4096, max_iter=10, max_lo_iters=10)
+ self.fast_matcher = fast_matcher or LoFTR("outdoor")
+ self.ransac = ransac or RANSAC("homography", inl_th=5.0, batch_size=4096, max_iter=10, max_lo_iters=10)
self.minimum_inliers_num = minimum_inliers_num
# placeholders
@@ -63,11 +63,11 @@ class HomographyTracker(Module):
self.target = target
self.target_initial_representation = {}
self.target_fast_representation = {}
- if hasattr(self.initial_matcher, 'extract_features') and isinstance(
+ if hasattr(self.initial_matcher, "extract_features") and isinstance(
self.initial_matcher.extract_features, Module
):
self.target_initial_representation = self.initial_matcher.extract_features(target)
- if hasattr(self.fast_matcher, 'extract_features') and isinstance(self.fast_matcher.extract_features, Module):
+ if hasattr(self.fast_matcher, "extract_features") and isinstance(self.fast_matcher.extract_features, Module):
self.target_fast_representation = self.fast_matcher.extract_features(target)
def reset_tracking(self) -> None:
@@ -84,11 +84,11 @@ class HomographyTracker(Module):
input_dict: Dict[str, Tensor] = {"image0": self.target, "image1": x}
for k, v in self.target_initial_representation.items():
- input_dict[f'{k}0'] = v
+ input_dict[f"{k}0"] = v
match_dict: Dict[str, Tensor] = self.initial_matcher(input_dict)
- keypoints0 = match_dict['keypoints0'][match_dict['batch_indexes'] == 0]
- keypoints1 = match_dict['keypoints1'][match_dict['batch_indexes'] == 0]
+ keypoints0 = match_dict["keypoints0"][match_dict["batch_indexes"] == 0]
+ keypoints1 = match_dict["keypoints1"][match_dict["batch_indexes"] == 0]
self.keypoints0_num = len(keypoints0)
self.keypoints1_num = len(keypoints1)
@@ -118,11 +118,11 @@ class HomographyTracker(Module):
frame_warped = warp_perspective(x, Hinv, (h, w))
input_dict: Dict[str, Tensor] = {"image0": self.target, "image1": frame_warped}
for k, v in self.target_fast_representation.items():
- input_dict[f'{k}0'] = v
+ input_dict[f"{k}0"] = v
match_dict = self.fast_matcher(input_dict)
- keypoints0 = match_dict['keypoints0'][match_dict['batch_indexes'] == 0]
- keypoints1 = match_dict['keypoints1'][match_dict['batch_indexes'] == 0]
+ keypoints0 = match_dict["keypoints0"][match_dict["batch_indexes"] == 0]
+ keypoints1 = match_dict["keypoints1"][match_dict["batch_indexes"] == 0]
keypoints1 = transform_points(Hwarp, keypoints1)
self.keypoints0_num = len(keypoints0)
diff --git a/kornia/utils/_compat.py b/kornia/utils/_compat.py
index 5e94f77a9..981773f3c 100644
--- a/kornia/utils/_compat.py
+++ b/kornia/utils/_compat.py
@@ -7,7 +7,7 @@ from torch import Tensor
def torch_version() -> str:
"""Parse the `torch.__version__` variable and removes +cu*/cpu."""
- return torch.__version__.split('+')[0]
+ return torch.__version__.split("+")[0]
def torch_version_lt(major: int, minor: int, patch: int) -> bool:
@@ -46,7 +46,7 @@ else:
if TYPE_CHECKING:
# TODO: remove this branch when kornia relies on torch >= 1.10.0
- _T = TypeVar('_T')
+ _T = TypeVar("_T")
torch_inference_mode: Callable[..., ContextManager[_T]]
elif torch_version_ge(1, 10, 0):
torch_inference_mode = torch.inference_mode
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 740ec8c6f..63904a6ea 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -22,9 +22,9 @@ def get_cuda_device_if_available(index: int = 0) -> torch.device:
torch.device
"""
if torch.cuda.is_available():
- return torch.device(f'cuda:{index}')
+ return torch.device(f"cuda:{index}")
- return torch.device('cpu')
+ return torch.device("cpu")
def get_mps_device_if_available() -> torch.device:
@@ -33,10 +33,10 @@ def get_mps_device_if_available() -> torch.device:
Returns:
torch.device
"""
- dev = 'cpu'
- if hasattr(torch.backends, 'mps'):
+ dev = "cpu"
+ if hasattr(torch.backends, "mps"):
if torch.backends.mps.is_available():
- dev = 'mps'
+ dev = "mps"
return torch.device(dev)
@@ -74,13 +74,13 @@ def deprecated(
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
name = ""
- beginning = f'Since kornia {version} the ' if version is not None else ''
+ beginning = f"Since kornia {version} the " if version is not None else ""
if isclass(func):
name = func.__class__.__name__
if isfunction(func):
name = func.__name__
- warnings.simplefilter('always', DeprecationWarning)
+ warnings.simplefilter("always", DeprecationWarning)
if replace_with is not None:
warnings.warn(
f"{beginning}`{name}` is deprecated in favor of `{replace_with}`.{extra_reason}",
@@ -93,7 +93,7 @@ def deprecated(
category=DeprecationWarning,
stacklevel=2,
)
- warnings.simplefilter('default', DeprecationWarning)
+ warnings.simplefilter("default", DeprecationWarning)
return func(*args, **kwargs)
return wrapper
@@ -126,7 +126,7 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devic
)
if device is None:
# TODO: update this when having torch.get_default_device()
- device = torch.device('cpu')
+ device = torch.device("cpu")
if dtype is None:
dtype = torch.get_default_dtype()
return (device, dtype)
@@ -230,7 +230,7 @@ def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
solution."""
if not torch_version_ge(1, 10):
sol = _torch_solve_cast(A, B)
- warnings.warn('PyTorch version < 1.10, solve validness mask maybe not correct', RuntimeWarning)
+ warnings.warn("PyTorch version < 1.10, solve validness mask maybe not correct", RuntimeWarning)
return sol, sol, torch.ones(len(A), dtype=torch.bool, device=A.device)
# Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622
if not isinstance(B, Tensor):
diff --git a/kornia/utils/image_print.py b/kornia/utils/image_print.py
index 2c170942f..b9a40211c 100644
--- a/kornia/utils/image_print.py
+++ b/kornia/utils/image_print.py
@@ -18,265 +18,265 @@ from kornia.io import ImageLoadType
# 8-bit, RGB hex
CLUT = [
# Primary 3-bit (8 colors). Unique representation!
- ('00', '000000'),
- ('01', '800000'),
- ('02', '008000'),
- ('03', '808000'),
- ('04', '000080'),
- ('05', '800080'),
- ('06', '008080'),
- ('07', 'c0c0c0'),
+ ("00", "000000"),
+ ("01", "800000"),
+ ("02", "008000"),
+ ("03", "808000"),
+ ("04", "000080"),
+ ("05", "800080"),
+ ("06", "008080"),
+ ("07", "c0c0c0"),
# Equivalent "bright" versions of original 8 colors.
- ('08', '808080'),
- ('09', 'ff0000'),
- ('10', '00ff00'),
- ('11', 'ffff00'),
- ('12', '0000ff'),
- ('13', 'ff00ff'),
- ('14', '00ffff'),
- ('15', 'ffffff'),
+ ("08", "808080"),
+ ("09", "ff0000"),
+ ("10", "00ff00"),
+ ("11", "ffff00"),
+ ("12", "0000ff"),
+ ("13", "ff00ff"),
+ ("14", "00ffff"),
+ ("15", "ffffff"),
# Strictly ascending.
- ('16', '000000'),
- ('17', '00005f'),
- ('18', '000087'),
- ('19', '0000af'),
- ('20', '0000d7'),
- ('21', '0000ff'),
- ('22', '005f00'),
- ('23', '005f5f'),
- ('24', '005f87'),
- ('25', '005faf'),
- ('26', '005fd7'),
- ('27', '005fff'),
- ('28', '008700'),
- ('29', '00875f'),
- ('30', '008787'),
- ('31', '0087af'),
- ('32', '0087d7'),
- ('33', '0087ff'),
- ('34', '00af00'),
- ('35', '00af5f'),
- ('36', '00af87'),
- ('37', '00afaf'),
- ('38', '00afd7'),
- ('39', '00afff'),
- ('40', '00d700'),
- ('41', '00d75f'),
- ('42', '00d787'),
- ('43', '00d7af'),
- ('44', '00d7d7'),
- ('45', '00d7ff'),
- ('46', '00ff00'),
- ('47', '00ff5f'),
- ('48', '00ff87'),
- ('49', '00ffaf'),
- ('50', '00ffd7'),
- ('51', '00ffff'),
- ('52', '5f0000'),
- ('53', '5f005f'),
- ('54', '5f0087'),
- ('55', '5f00af'),
- ('56', '5f00d7'),
- ('57', '5f00ff'),
- ('58', '5f5f00'),
- ('59', '5f5f5f'),
- ('60', '5f5f87'),
- ('61', '5f5faf'),
- ('62', '5f5fd7'),
- ('63', '5f5fff'),
- ('64', '5f8700'),
- ('65', '5f875f'),
- ('66', '5f8787'),
- ('67', '5f87af'),
- ('68', '5f87d7'),
- ('69', '5f87ff'),
- ('70', '5faf00'),
- ('71', '5faf5f'),
- ('72', '5faf87'),
- ('73', '5fafaf'),
- ('74', '5fafd7'),
- ('75', '5fafff'),
- ('76', '5fd700'),
- ('77', '5fd75f'),
- ('78', '5fd787'),
- ('79', '5fd7af'),
- ('80', '5fd7d7'),
- ('81', '5fd7ff'),
- ('82', '5fff00'),
- ('83', '5fff5f'),
- ('84', '5fff87'),
- ('85', '5fffaf'),
- ('86', '5fffd7'),
- ('87', '5fffff'),
- ('88', '870000'),
- ('89', '87005f'),
- ('90', '870087'),
- ('91', '8700af'),
- ('92', '8700d7'),
- ('93', '8700ff'),
- ('94', '875f00'),
- ('95', '875f5f'),
- ('96', '875f87'),
- ('97', '875faf'),
- ('98', '875fd7'),
- ('99', '875fff'),
- ('100', '878700'),
- ('101', '87875f'),
- ('102', '878787'),
- ('103', '8787af'),
- ('104', '8787d7'),
- ('105', '8787ff'),
- ('106', '87af00'),
- ('107', '87af5f'),
- ('108', '87af87'),
- ('109', '87afaf'),
- ('110', '87afd7'),
- ('111', '87afff'),
- ('112', '87d700'),
- ('113', '87d75f'),
- ('114', '87d787'),
- ('115', '87d7af'),
- ('116', '87d7d7'),
- ('117', '87d7ff'),
- ('118', '87ff00'),
- ('119', '87ff5f'),
- ('120', '87ff87'),
- ('121', '87ffaf'),
- ('122', '87ffd7'),
- ('123', '87ffff'),
- ('124', 'af0000'),
- ('125', 'af005f'),
- ('126', 'af0087'),
- ('127', 'af00af'),
- ('128', 'af00d7'),
- ('129', 'af00ff'),
- ('130', 'af5f00'),
- ('131', 'af5f5f'),
- ('132', 'af5f87'),
- ('133', 'af5faf'),
- ('134', 'af5fd7'),
- ('135', 'af5fff'),
- ('136', 'af8700'),
- ('137', 'af875f'),
- ('138', 'af8787'),
- ('139', 'af87af'),
- ('140', 'af87d7'),
- ('141', 'af87ff'),
- ('142', 'afaf00'),
- ('143', 'afaf5f'),
- ('144', 'afaf87'),
- ('145', 'afafaf'),
- ('146', 'afafd7'),
- ('147', 'afafff'),
- ('148', 'afd700'),
- ('149', 'afd75f'),
- ('150', 'afd787'),
- ('151', 'afd7af'),
- ('152', 'afd7d7'),
- ('153', 'afd7ff'),
- ('154', 'afff00'),
- ('155', 'afff5f'),
- ('156', 'afff87'),
- ('157', 'afffaf'),
- ('158', 'afffd7'),
- ('159', 'afffff'),
- ('160', 'd70000'),
- ('161', 'd7005f'),
- ('162', 'd70087'),
- ('163', 'd700af'),
- ('164', 'd700d7'),
- ('165', 'd700ff'),
- ('166', 'd75f00'),
- ('167', 'd75f5f'),
- ('168', 'd75f87'),
- ('169', 'd75faf'),
- ('170', 'd75fd7'),
- ('171', 'd75fff'),
- ('172', 'd78700'),
- ('173', 'd7875f'),
- ('174', 'd78787'),
- ('175', 'd787af'),
- ('176', 'd787d7'),
- ('177', 'd787ff'),
- ('178', 'd7af00'),
- ('179', 'd7af5f'),
- ('180', 'd7af87'),
- ('181', 'd7afaf'),
- ('182', 'd7afd7'),
- ('183', 'd7afff'),
- ('184', 'd7d700'),
- ('185', 'd7d75f'),
- ('186', 'd7d787'),
- ('187', 'd7d7af'),
- ('188', 'd7d7d7'),
- ('189', 'd7d7ff'),
- ('190', 'd7ff00'),
- ('191', 'd7ff5f'),
- ('192', 'd7ff87'),
- ('193', 'd7ffaf'),
- ('194', 'd7ffd7'),
- ('195', 'd7ffff'),
- ('196', 'ff0000'),
- ('197', 'ff005f'),
- ('198', 'ff0087'),
- ('199', 'ff00af'),
- ('200', 'ff00d7'),
- ('201', 'ff00ff'),
- ('202', 'ff5f00'),
- ('203', 'ff5f5f'),
- ('204', 'ff5f87'),
- ('205', 'ff5faf'),
- ('206', 'ff5fd7'),
- ('207', 'ff5fff'),
- ('208', 'ff8700'),
- ('209', 'ff875f'),
- ('210', 'ff8787'),
- ('211', 'ff87af'),
- ('212', 'ff87d7'),
- ('213', 'ff87ff'),
- ('214', 'ffaf00'),
- ('215', 'ffaf5f'),
- ('216', 'ffaf87'),
- ('217', 'ffafaf'),
- ('218', 'ffafd7'),
- ('219', 'ffafff'),
- ('220', 'ffd700'),
- ('221', 'ffd75f'),
- ('222', 'ffd787'),
- ('223', 'ffd7af'),
- ('224', 'ffd7d7'),
- ('225', 'ffd7ff'),
- ('226', 'ffff00'),
- ('227', 'ffff5f'),
- ('228', 'ffff87'),
- ('229', 'ffffaf'),
- ('230', 'ffffd7'),
- ('231', 'ffffff'),
+ ("16", "000000"),
+ ("17", "00005f"),
+ ("18", "000087"),
+ ("19", "0000af"),
+ ("20", "0000d7"),
+ ("21", "0000ff"),
+ ("22", "005f00"),
+ ("23", "005f5f"),
+ ("24", "005f87"),
+ ("25", "005faf"),
+ ("26", "005fd7"),
+ ("27", "005fff"),
+ ("28", "008700"),
+ ("29", "00875f"),
+ ("30", "008787"),
+ ("31", "0087af"),
+ ("32", "0087d7"),
+ ("33", "0087ff"),
+ ("34", "00af00"),
+ ("35", "00af5f"),
+ ("36", "00af87"),
+ ("37", "00afaf"),
+ ("38", "00afd7"),
+ ("39", "00afff"),
+ ("40", "00d700"),
+ ("41", "00d75f"),
+ ("42", "00d787"),
+ ("43", "00d7af"),
+ ("44", "00d7d7"),
+ ("45", "00d7ff"),
+ ("46", "00ff00"),
+ ("47", "00ff5f"),
+ ("48", "00ff87"),
+ ("49", "00ffaf"),
+ ("50", "00ffd7"),
+ ("51", "00ffff"),
+ ("52", "5f0000"),
+ ("53", "5f005f"),
+ ("54", "5f0087"),
+ ("55", "5f00af"),
+ ("56", "5f00d7"),
+ ("57", "5f00ff"),
+ ("58", "5f5f00"),
+ ("59", "5f5f5f"),
+ ("60", "5f5f87"),
+ ("61", "5f5faf"),
+ ("62", "5f5fd7"),
+ ("63", "5f5fff"),
+ ("64", "5f8700"),
+ ("65", "5f875f"),
+ ("66", "5f8787"),
+ ("67", "5f87af"),
+ ("68", "5f87d7"),
+ ("69", "5f87ff"),
+ ("70", "5faf00"),
+ ("71", "5faf5f"),
+ ("72", "5faf87"),
+ ("73", "5fafaf"),
+ ("74", "5fafd7"),
+ ("75", "5fafff"),
+ ("76", "5fd700"),
+ ("77", "5fd75f"),
+ ("78", "5fd787"),
+ ("79", "5fd7af"),
+ ("80", "5fd7d7"),
+ ("81", "5fd7ff"),
+ ("82", "5fff00"),
+ ("83", "5fff5f"),
+ ("84", "5fff87"),
+ ("85", "5fffaf"),
+ ("86", "5fffd7"),
+ ("87", "5fffff"),
+ ("88", "870000"),
+ ("89", "87005f"),
+ ("90", "870087"),
+ ("91", "8700af"),
+ ("92", "8700d7"),
+ ("93", "8700ff"),
+ ("94", "875f00"),
+ ("95", "875f5f"),
+ ("96", "875f87"),
+ ("97", "875faf"),
+ ("98", "875fd7"),
+ ("99", "875fff"),
+ ("100", "878700"),
+ ("101", "87875f"),
+ ("102", "878787"),
+ ("103", "8787af"),
+ ("104", "8787d7"),
+ ("105", "8787ff"),
+ ("106", "87af00"),
+ ("107", "87af5f"),
+ ("108", "87af87"),
+ ("109", "87afaf"),
+ ("110", "87afd7"),
+ ("111", "87afff"),
+ ("112", "87d700"),
+ ("113", "87d75f"),
+ ("114", "87d787"),
+ ("115", "87d7af"),
+ ("116", "87d7d7"),
+ ("117", "87d7ff"),
+ ("118", "87ff00"),
+ ("119", "87ff5f"),
+ ("120", "87ff87"),
+ ("121", "87ffaf"),
+ ("122", "87ffd7"),
+ ("123", "87ffff"),
+ ("124", "af0000"),
+ ("125", "af005f"),
+ ("126", "af0087"),
+ ("127", "af00af"),
+ ("128", "af00d7"),
+ ("129", "af00ff"),
+ ("130", "af5f00"),
+ ("131", "af5f5f"),
+ ("132", "af5f87"),
+ ("133", "af5faf"),
+ ("134", "af5fd7"),
+ ("135", "af5fff"),
+ ("136", "af8700"),
+ ("137", "af875f"),
+ ("138", "af8787"),
+ ("139", "af87af"),
+ ("140", "af87d7"),
+ ("141", "af87ff"),
+ ("142", "afaf00"),
+ ("143", "afaf5f"),
+ ("144", "afaf87"),
+ ("145", "afafaf"),
+ ("146", "afafd7"),
+ ("147", "afafff"),
+ ("148", "afd700"),
+ ("149", "afd75f"),
+ ("150", "afd787"),
+ ("151", "afd7af"),
+ ("152", "afd7d7"),
+ ("153", "afd7ff"),
+ ("154", "afff00"),
+ ("155", "afff5f"),
+ ("156", "afff87"),
+ ("157", "afffaf"),
+ ("158", "afffd7"),
+ ("159", "afffff"),
+ ("160", "d70000"),
+ ("161", "d7005f"),
+ ("162", "d70087"),
+ ("163", "d700af"),
+ ("164", "d700d7"),
+ ("165", "d700ff"),
+ ("166", "d75f00"),
+ ("167", "d75f5f"),
+ ("168", "d75f87"),
+ ("169", "d75faf"),
+ ("170", "d75fd7"),
+ ("171", "d75fff"),
+ ("172", "d78700"),
+ ("173", "d7875f"),
+ ("174", "d78787"),
+ ("175", "d787af"),
+ ("176", "d787d7"),
+ ("177", "d787ff"),
+ ("178", "d7af00"),
+ ("179", "d7af5f"),
+ ("180", "d7af87"),
+ ("181", "d7afaf"),
+ ("182", "d7afd7"),
+ ("183", "d7afff"),
+ ("184", "d7d700"),
+ ("185", "d7d75f"),
+ ("186", "d7d787"),
+ ("187", "d7d7af"),
+ ("188", "d7d7d7"),
+ ("189", "d7d7ff"),
+ ("190", "d7ff00"),
+ ("191", "d7ff5f"),
+ ("192", "d7ff87"),
+ ("193", "d7ffaf"),
+ ("194", "d7ffd7"),
+ ("195", "d7ffff"),
+ ("196", "ff0000"),
+ ("197", "ff005f"),
+ ("198", "ff0087"),
+ ("199", "ff00af"),
+ ("200", "ff00d7"),
+ ("201", "ff00ff"),
+ ("202", "ff5f00"),
+ ("203", "ff5f5f"),
+ ("204", "ff5f87"),
+ ("205", "ff5faf"),
+ ("206", "ff5fd7"),
+ ("207", "ff5fff"),
+ ("208", "ff8700"),
+ ("209", "ff875f"),
+ ("210", "ff8787"),
+ ("211", "ff87af"),
+ ("212", "ff87d7"),
+ ("213", "ff87ff"),
+ ("214", "ffaf00"),
+ ("215", "ffaf5f"),
+ ("216", "ffaf87"),
+ ("217", "ffafaf"),
+ ("218", "ffafd7"),
+ ("219", "ffafff"),
+ ("220", "ffd700"),
+ ("221", "ffd75f"),
+ ("222", "ffd787"),
+ ("223", "ffd7af"),
+ ("224", "ffd7d7"),
+ ("225", "ffd7ff"),
+ ("226", "ffff00"),
+ ("227", "ffff5f"),
+ ("228", "ffff87"),
+ ("229", "ffffaf"),
+ ("230", "ffffd7"),
+ ("231", "ffffff"),
# Gray-scale range.
- ('232', '080808'),
- ('233', '121212'),
- ('234', '1c1c1c'),
- ('235', '262626'),
- ('236', '303030'),
- ('237', '3a3a3a'),
- ('238', '444444'),
- ('239', '4e4e4e'),
- ('240', '585858'),
- ('241', '626262'),
- ('242', '6c6c6c'),
- ('243', '767676'),
- ('244', '808080'),
- ('245', '8a8a8a'),
- ('246', '949494'),
- ('247', '9e9e9e'),
- ('248', 'a8a8a8'),
- ('249', 'b2b2b2'),
- ('250', 'bcbcbc'),
- ('251', 'c6c6c6'),
- ('252', 'd0d0d0'),
- ('253', 'dadada'),
- ('254', 'e4e4e4'),
- ('255', 'eeeeee'),
+ ("232", "080808"),
+ ("233", "121212"),
+ ("234", "1c1c1c"),
+ ("235", "262626"),
+ ("236", "303030"),
+ ("237", "3a3a3a"),
+ ("238", "444444"),
+ ("239", "4e4e4e"),
+ ("240", "585858"),
+ ("241", "626262"),
+ ("242", "6c6c6c"),
+ ("243", "767676"),
+ ("244", "808080"),
+ ("245", "8a8a8a"),
+ ("246", "949494"),
+ ("247", "9e9e9e"),
+ ("248", "a8a8a8"),
+ ("249", "b2b2b2"),
+ ("250", "bcbcbc"),
+ ("251", "c6c6c6"),
+ ("252", "d0d0d0"),
+ ("253", "dadada"),
+ ("254", "e4e4e4"),
+ ("255", "eeeeee"),
]
SHORT2RGB_DICT = dict(CLUT)
RGB2SHORT_DICT = {v: k for k, v in SHORT2RGB_DICT.items()}
@@ -288,8 +288,8 @@ def _str2hex(hexstr: str) -> int:
def _strip_hash(rgb: str) -> str:
# Strip leading `#` if exists.
- if rgb.startswith('#'):
- rgb = rgb.lstrip('#')
+ if rgb.startswith("#"):
+ rgb = rgb.lstrip("#")
return rgb
@@ -317,7 +317,7 @@ def rgb2short(rgb: str) -> Tuple[str, str]:
rgb = _strip_hash(rgb)
incs = (0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF)
# Break 6-char RGB code into 3 integer vals.
- parts = [int(h, 16) for h in re.split(r'(..)(..)(..)', rgb)[1:4]]
+ parts = [int(h, 16) for h in re.split(r"(..)(..)(..)", rgb)[1:4]]
res = []
for part in parts:
i = 0
@@ -333,7 +333,7 @@ def rgb2short(rgb: str) -> Tuple[str, str]:
res.append(closest)
break
i += 1
- _res = ''.join([('%02.x' % i) for i in res])
+ _res = "".join([("%02.x" % i) for i in res])
equiv = RGB2SHORT_DICT[_res]
return equiv, _res
diff --git a/kornia/utils/pointcloud_io.py b/kornia/utils/pointcloud_io.py
index ac38b5282..b4fe103d3 100644
--- a/kornia/utils/pointcloud_io.py
+++ b/kornia/utils/pointcloud_io.py
@@ -12,7 +12,7 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:
The tensor must be in the shape of :math:`(*, 3)` where the last
component is assumed to be a 3d point coordinate :math:`(X, Y, Z)`.
"""
- if not isinstance(filename, str) and filename[-3:] == '.ply':
+ if not isinstance(filename, str) and filename[-3:] == ".ply":
raise TypeError(f"Input filename must be a string in with the .ply extension. Got {filename}")
if not torch.is_tensor(pointcloud):
@@ -24,8 +24,8 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:
# flatten the input pointcloud in a vector to iterate points
xyz_vec: torch.Tensor = pointcloud.reshape(-1, 3)
- with open(filename, 'w') as f:
- data_str: str = ''
+ with open(filename, "w") as f:
+ data_str: str = ""
num_points: int = xyz_vec.shape[0]
for idx in range(num_points):
xyz = xyz_vec[idx]
@@ -35,7 +35,7 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:
x: float = float(xyz[0])
y: float = float(xyz[1])
z: float = float(xyz[2])
- data_str += f'{x} {y} {z}\n'
+ data_str += f"{x} {y} {z}\n"
f.write("ply\n")
f.write("format ascii 1.0\n")
@@ -60,7 +60,7 @@ def load_pointcloud_ply(filename: str, header_size: int = 8) -> torch.Tensor:
tensor containing the loaded point with shape :math:`(*, 3)` where
:math:`*` represents the number of points.
"""
- if not isinstance(filename, str) and filename[-3:] == '.ply':
+ if not isinstance(filename, str) and filename[-3:] == ".ply":
raise TypeError(f"Input filename must be a string in with the .ply extension. Got {filename}")
if not os.path.isfile(filename):
raise ValueError("Input filename is not an existing file.")
diff --git a/kornia/x/trainer.py b/kornia/x/trainer.py
index e5ec9bcec..6857bd886 100644
--- a/kornia/x/trainer.py
+++ b/kornia/x/trainer.py
@@ -96,7 +96,7 @@ class Trainer:
self.state = TrainerState.STARTING
- self._logger = logging.getLogger('train')
+ self._logger = logging.getLogger("train")
@property
def device(self) -> torch.device:
@@ -177,8 +177,8 @@ class Trainer:
# Loss computation
if self.criterion is not None:
val_loss = self.compute_loss(out, sample["target"])
- stats.update('losses', val_loss.item(), batch_size)
- stats.update_from_dict(self.compute_metrics(out, sample['target']), batch_size)
+ stats.update("losses", val_loss.item(), batch_size)
+ stats.update_from_dict(self.compute_metrics(out, sample["target"]), batch_size)
if sample_id % 10 == 0:
self._logger.info(f"Test: {sample_id}/{len(self.valid_dataloader)} {stats}")
diff --git a/kornia/x/trainers.py b/kornia/x/trainers.py
index 72fcf4da2..f7c91b531 100644
--- a/kornia/x/trainers.py
+++ b/kornia/x/trainers.py
@@ -106,13 +106,13 @@ class ObjectDetectionTrainer(Trainer):
and "labels" in args[1]
):
mAP, _ = mean_average_precision(
- [a['boxes'] for a in args[0]],
- [a['labels'] for a in args[0]],
- [a['scores'] for a in args[0]],
- [a['boxes'] for a in args[1]],
- [a['labels'] for a in args[1]],
+ [a["boxes"] for a in args[0]],
+ [a["labels"] for a in args[0]],
+ [a["scores"] for a in args[0]],
+ [a["boxes"] for a in args[1]],
+ [a["labels"] for a in args[1]],
n_classes=self.num_classes,
threshold=0.000001,
)
- return {'mAP': mAP.item()}
+ return {"mAP": mAP.item()}
return super().compute_metrics(*args)
diff --git a/pyproject.toml b/pyproject.toml
index cb5cd7df0..6139b0efd 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -71,11 +71,6 @@ requires = [
[tool.setuptools.package-data]
kornia = ["py.typed"]
-[tool.black]
- line-length = 120
- skip-magic-trailing-comma = true
- skip-string-normalization = true
-
[tool.ruff]
line-length = 120
target-version = "py38"
@@ -143,8 +138,12 @@ requires = [
"UP007", # Prefer Optional[], Union[] over | due to torch jit scripting
]
+ [tool.ruff.format]
+ skip-magic-trailing-comma = false
+
[tool.ruff.isort]
known-first-party = ["examples", "kornia", "test"]
+ split-on-trailing-comma = true
[tool.ruff.mccabe]
max-complexity = 20
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 47fbfcce5..7254d232c 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -171,7 +171,7 @@ class CommonTests(BaseTester):
assert isinstance(generated_params, dict)
# compute_transformation can be called and returns the correct shaped transformation matrix
- to_apply = generated_params['batch_prob'] > 0.5
+ to_apply = generated_params["batch_prob"] > 0.5
expected_transformation_shape = torch.Size((to_apply.sum(), 3, 3))
test_input = torch.ones(batch_shape, device=self.device, dtype=self.dtype)
transformation = augmentation.compute_transformation(test_input[to_apply], generated_params, augmentation.flags)
@@ -593,7 +593,7 @@ class TestRandomRotationAlternative(CommonTests):
def test_batch(self):
if self.dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
torch.manual_seed(12)
@@ -1275,7 +1275,7 @@ class TestColorJiggle(BaseTester):
def test_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
f = AugmentationSequential(ColorJiggle(), ColorJiggle())
@@ -1290,7 +1290,7 @@ class TestColorJiggle(BaseTester):
def test_color_jitter_batch_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
f = AugmentationSequential(ColorJiggle(), ColorJiggle())
@@ -1341,7 +1341,7 @@ class TestColorJitter(BaseTester):
def test_color_jitter(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
f = ColorJitter()
@@ -1355,7 +1355,7 @@ class TestColorJitter(BaseTester):
def test_color_jitter_batch(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
f = ColorJitter()
@@ -1603,7 +1603,7 @@ class TestColorJitter(BaseTester):
def test_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
f = AugmentationSequential(ColorJiggle(), ColorJiggle())
@@ -1618,7 +1618,7 @@ class TestColorJitter(BaseTester):
def test_color_jitter_batch_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
f = AugmentationSequential(ColorJitter(), ColorJitter())
@@ -1713,7 +1713,7 @@ class TestRandomBrightness(BaseTester):
def test_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
torch.manual_seed(27)
f = AugmentationSequential(RandomBrightness())
@@ -1726,7 +1726,7 @@ class TestRandomBrightness(BaseTester):
def test_random_brightness_batch_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
f = AugmentationSequential(RandomBrightness(), RandomBrightness())
@@ -1815,7 +1815,7 @@ class TestRandomContrast(BaseTester):
def test_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
torch.manual_seed(27)
f = AugmentationSequential(RandomContrast())
@@ -1828,7 +1828,7 @@ class TestRandomContrast(BaseTester):
def test_random_contrast_batch_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
f = AugmentationSequential(RandomContrast(), RandomContrast())
@@ -1925,7 +1925,7 @@ class TestRandomHue(BaseTester):
def test_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
torch.manual_seed(27)
f = AugmentationSequential(RandomHue())
@@ -1938,7 +1938,7 @@ class TestRandomHue(BaseTester):
def test_random_hue_batch_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
f = AugmentationSequential(RandomHue(), RandomHue())
@@ -2035,7 +2035,7 @@ class TestRandomSaturation(BaseTester):
def test_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
torch.manual_seed(27)
f = AugmentationSequential(RandomSaturation())
@@ -2048,7 +2048,7 @@ class TestRandomSaturation(BaseTester):
def test_random_saturation_batch_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
f = AugmentationSequential(RandomSaturation(), RandomSaturation())
@@ -2223,7 +2223,7 @@ class TestRandomGamma(BaseTester):
def test_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
torch.manual_seed(27)
f = AugmentationSequential(RandomGamma(gamma=(0.5, 0.5)), RandomGamma(gamma=(2.0, 2.0)))
@@ -2236,7 +2236,7 @@ class TestRandomGamma(BaseTester):
def test_random_gamma_batch_sequential(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
f = AugmentationSequential(RandomGamma(gamma=(0.5, 0.5)), RandomGamma(gamma=(2.0, 2.0)))
@@ -2562,10 +2562,10 @@ class TestCenterCrop(BaseTester):
torch.manual_seed(0)
img = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)
- op1 = CenterCrop(size=(2, 2), cropping_mode='resample')
+ op1 = CenterCrop(size=(2, 2), cropping_mode="resample")
out = op1(img)
- op2 = CenterCrop(size=(2, 2), cropping_mode='slice')
+ op2 = CenterCrop(size=(2, 2), cropping_mode="slice")
self.assert_close(out, op2(img, op1._params))
@@ -2831,7 +2831,7 @@ class TestRandomCrop(BaseTester):
torch.manual_seed(42)
inp = torch.tensor([[[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]], device=device, dtype=dtype)
expected = torch.tensor([[[[7.0, 8.0, 7.0], [4.0, 5.0, 4.0]]]], device=device, dtype=dtype)
- rc = RandomCrop(size=(2, 3), padding=1, padding_mode='reflect', align_corners=True, p=1.0)
+ rc = RandomCrop(size=(2, 3), padding=1, padding_mode="reflect", align_corners=True, p=1.0)
out = rc(inp)
torch.manual_seed(42)
@@ -2842,7 +2842,7 @@ class TestRandomCrop(BaseTester):
torch.manual_seed(42)
inversed = torch.tensor([[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 7.0, 8.0]]]], device=device, dtype=dtype)
aug = RandomCrop(
- size=(2, 3), padding=1, padding_mode='reflect', align_corners=True, p=1.0, cropping_mode="resample"
+ size=(2, 3), padding=1, padding_mode="reflect", align_corners=True, p=1.0, cropping_mode="resample"
)
out = aug(inp)
self.assert_close(out, expected)
@@ -2889,8 +2889,8 @@ class TestRandomCrop(BaseTester):
rc = RandomCrop(size=(2, 3), padding=padding, fill=10, align_corners=True, p=1.0)
out = rc(inp)
- assert rc._params['input_size'][0][0] == (inp.shape[-2] + 2 * padding[1]) # height + top + bottom
- assert rc._params['input_size'][0][1] == (inp.shape[-1] + 2 * padding[0]) # height + left + right
+ assert rc._params["input_size"][0][0] == (inp.shape[-2] + 2 * padding[1]) # height + top + bottom
+ assert rc._params["input_size"][0][1] == (inp.shape[-1] + 2 * padding[0]) # height + left + right
self.assert_close(out, expected)
torch.manual_seed(42)
inversed = torch.tensor(
@@ -2919,8 +2919,8 @@ class TestRandomCrop(BaseTester):
rc = RandomCrop(size=(2, 3), padding=padding, fill=8, align_corners=True, p=1.0)
out = rc(inp)
- assert rc._params['input_size'][0][0] == (inp.shape[-2] + padding[1] + padding[3]) # height + top + bottom
- assert rc._params['input_size'][0][1] == (inp.shape[-1] + padding[0] + padding[2]) # height + left + right
+ assert rc._params["input_size"][0][0] == (inp.shape[-2] + padding[1] + padding[3]) # height + top + bottom
+ assert rc._params["input_size"][0][1] == (inp.shape[-1] + padding[0] + padding[2]) # height + left + right
self.assert_close(out, expected, low_tolerance=True)
torch.manual_seed(0)
@@ -3006,10 +3006,10 @@ class TestRandomCrop(BaseTester):
torch.manual_seed(0)
img = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], device=device, dtype=dtype)
- op1 = RandomCrop(size=(2, 2), cropping_mode='resample')
+ op1 = RandomCrop(size=(2, 2), cropping_mode="resample")
out = op1(img)
- op2 = RandomCrop(size=(2, 2), cropping_mode='slice')
+ op2 = RandomCrop(size=(2, 2), cropping_mode="slice")
self.assert_close(out, op2(img, op1._params))
@@ -3200,10 +3200,10 @@ class TestRandomResizedCrop(BaseTester):
torch.manual_seed(0)
img = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], device=device, dtype=dtype)
- op1 = RandomResizedCrop(size=(4, 4), cropping_mode='resample')
+ op1 = RandomResizedCrop(size=(4, 4), cropping_mode="resample")
out = op1(img)
- op2 = RandomResizedCrop(size=(4, 4), cropping_mode='slice')
+ op2 = RandomResizedCrop(size=(4, 4), cropping_mode="slice")
self.assert_close(out, op2(img, op1._params))
@@ -3342,7 +3342,7 @@ class TestRandomEqualize(BaseTester):
assert gradcheck(RandomEqualize(p=0.5), (input,), raise_exception=True, fast_mode=True)
@staticmethod
- def build_input(channels, height, width, bs=1, row=None, device='cpu', dtype=torch.float32):
+ def build_input(channels, height, width, bs=1, row=None, device="cpu", dtype=torch.float32):
if row is None:
row = torch.arange(width, device=device, dtype=dtype) / float(width)
@@ -3779,7 +3779,7 @@ class TestRandomElasticTransform:
# Make sure the transformation works correctly even if only applied to some images in the batch
to_apply = torch.tensor(batch_prob, device=device)
- with patch.object(aug_list[0], '__batch_prob_generator__', return_value=to_apply):
+ with patch.object(aug_list[0], "__batch_prob_generator__", return_value=to_apply):
features_transformed, labels_transformed = aug_list(features, labels, data_keys=["input", "mask"])
assert_close(aug_list._params[0].data["batch_prob"], to_apply)
@@ -4071,7 +4071,7 @@ class TestPlanckianJitter(BaseTester):
def test_planckian_jitter_cied(self, device, dtype):
torch.manual_seed(0)
- f = RandomPlanckianJitter(mode='CIED', select_from=1)
+ f = RandomPlanckianJitter(mode="CIED", select_from=1)
input = self._get_input(device, dtype)
expected = self._get_expected_output_cied(device, dtype)
self.assert_close(f(input), expected, low_tolerance=True)
@@ -4212,10 +4212,10 @@ class TestRandomSnow(BaseTester):
torch.manual_seed(0) # for random reproductibility
def _get_exception_test_data(self, device, dtype):
- err_msg_sw_coef = 'Snow coefficient values must be between 0 and 1.'
- err_msg_brght_coef = 'Brightness values must be greater than 1.'
- err_msg_wrong_ch = 'Number of color channels should be 3.'
- err_msg_wrong_sh = 'Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W).'
+ err_msg_sw_coef = "Snow coefficient values must be between 0 and 1."
+ err_msg_brght_coef = "Brightness values must be greater than 1."
+ err_msg_wrong_ch = "Number of color channels should be 3."
+ err_msg_wrong_sh = "Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W)."
return [
(err_msg_sw_coef, (-0.3, 0.6), (1.2, 3.4), torch.rand(1, 3, 3, device=device, dtype=dtype)),
@@ -4287,8 +4287,8 @@ class TestRandomRain(BaseTester):
def _get_exception_test_data(self, device, dtype):
err_msg_height_bigger = "Height of drop should be greater than zero and less than image height."
- err_msg_width_bigger = 'Width of drop should be less than image width'
- err_msg_wrong_ch = 'Number of color channels should be 1 or 3.'
+ err_msg_width_bigger = "Width of drop should be less than image width"
+ err_msg_wrong_ch = "Number of color channels should be 1 or 3."
return [
(err_msg_height_bigger, (-2, 0), (2, 3), torch.rand(1, 5, 5, device=device, dtype=dtype)),
@@ -4355,7 +4355,7 @@ class DummyMPDataset(torch.utils.data.Dataset):
RandomRotation3D(degrees=15),
]
- if context != 'fork':
+ if context != "fork":
# random planckian jitter auto selects a GPU. But it is not possible
# to init a CUDA context in a forked process.
# So we skip it in this case.
@@ -4390,7 +4390,7 @@ class TestMultiprocessing:
torch.manual_seed(0) # for random reproductibility
@pytest.mark.slow
- @pytest.mark.parametrize('context', ['spawn', 'forkserver', 'fork'] if os.name != 'nt' else ['spawn'])
+ @pytest.mark.parametrize("context", ["spawn", "forkserver", "fork"] if os.name != "nt" else ["spawn"])
def test_spawn_multiprocessing_context(self, context: str):
dataset = DummyMPDataset(context=context)
dataloader = torch.utils.data.DataLoader(
diff --git a/test/augmentation/test_augmentation_3d.py b/test/augmentation/test_augmentation_3d.py
index 65b017e26..b1b8b55ea 100644
--- a/test/augmentation/test_augmentation_3d.py
+++ b/test/augmentation/test_augmentation_3d.py
@@ -879,7 +879,7 @@ class TestRandomEqualize3D:
assert gradcheck(RandomEqualize3D(p=0.5), (inputs3d,), raise_exception=True, fast_mode=True)
@staticmethod
- def build_input(channels, depth, height, width, bs=1, row=None, device='cpu', dtype=torch.float32):
+ def build_input(channels, depth, height, width, bs=1, row=None, device="cpu", dtype=torch.float32):
if row is None:
row = torch.arange(width, device=device, dtype=dtype) / float(width)
diff --git a/test/augmentation/test_auto_operation.py b/test/augmentation/test_auto_operation.py
index bef29ef33..5c1848694 100644
--- a/test/augmentation/test_auto_operation.py
+++ b/test/augmentation/test_auto_operation.py
@@ -111,8 +111,8 @@ class TestRandAugment:
aug(in_tensor)
@pytest.mark.xfail(
- torch_version() in {'1.10.2', '1.11.0', '1.12.1', '1.13.1'},
- reason='randomness failing into some torch versions',
+ torch_version() in {"1.10.2", "1.11.0", "1.12.1", "1.13.1"},
+ reason="randomness failing into some torch versions",
)
def test_transform_mat(self, device, dtype):
aug = RandAugment(n=3, m=15)
diff --git a/test/augmentation/test_backward.py b/test/augmentation/test_backward.py
index fa74e5630..c1db083e3 100644
--- a/test/augmentation/test_backward.py
+++ b/test/augmentation/test_backward.py
@@ -134,7 +134,7 @@ class TestRandomAffineBackward:
@pytest.mark.parametrize(
"shear", [[10.0, 20.0], [10.0, 20.0, 30.0, 40.0], torch.tensor([10, 20]), torch.tensor([10, 20, 30, 40])]
)
- @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
+ @pytest.mark.parametrize("resample", ["bilinear"]) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, degrees, translate, scale, shear, resample, align_corners, same_on_batch, device, dtype):
@@ -187,10 +187,10 @@ class TestRandomAffineBackward:
if not isinstance(degrees, (int, float, list, tuple)):
assert isinstance(aug._param_generator.degrees, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug._param_generator.degrees.is_cuda:
+ if resample == "nearest" and aug._param_generator.degrees.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug._param_generator.degrees._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug._param_generator.degrees._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (degrees.to(device=device, dtype=dtype) - aug._param_generator.degrees.data).sum() == 0
@@ -199,10 +199,10 @@ class TestRandomAffineBackward:
if not isinstance(translate, (int, float, list, tuple)):
assert isinstance(aug._param_generator.translate, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug._param_generator.translate.is_cuda:
+ if resample == "nearest" and aug._param_generator.translate.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug._param_generator.translate._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug._param_generator.translate._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (translate.to(device=device, dtype=dtype) - aug._param_generator.translate.data).sum() == 0
@@ -211,10 +211,10 @@ class TestRandomAffineBackward:
if not isinstance(scale, (int, float, list, tuple)):
assert isinstance(aug._param_generator.scale, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug._param_generator.scale.is_cuda:
+ if resample == "nearest" and aug._param_generator.scale.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug._param_generator.scale._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug._param_generator.scale._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (scale.to(device=device, dtype=dtype) - aug._param_generator.scale.data).sum() == 0
@@ -223,10 +223,10 @@ class TestRandomAffineBackward:
if not isinstance(shear, (int, float, list, tuple)):
assert isinstance(aug._param_generator.shear, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug._param_generator.shear.is_cuda:
+ if resample == "nearest" and aug._param_generator.shear.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug._param_generator.shear._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug._param_generator.shear._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (shear.to(device=device, dtype=dtype) - aug._param_generator.shear.data).sum() == 0
@@ -236,7 +236,7 @@ class TestRandomAffineBackward:
class TestRandomRotationBackward:
@pytest.mark.parametrize("degrees", [10, [10.0, 20.0], (10, 20), torch.tensor(10.0), torch.tensor([10, 20])])
- @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
+ @pytest.mark.parametrize("resample", ["bilinear"]) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, degrees, resample, align_corners, same_on_batch, device, dtype):
@@ -262,10 +262,10 @@ class TestRandomRotationBackward:
if not isinstance(degrees, (int, float, list, tuple)):
assert isinstance(aug._param_generator.degrees, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug._param_generator.degrees.is_cuda:
+ if resample == "nearest" and aug._param_generator.degrees.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug._param_generator.degrees._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug._param_generator.degrees._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (degrees.to(device=device, dtype=dtype) - aug._param_generator.degrees.data).sum() == 0
@@ -275,7 +275,7 @@ class TestRandomRotationBackward:
class TestRandomPerspectiveBackward:
@pytest.mark.parametrize("distortion_scale", [0.5, torch.tensor(0.5)])
- @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
+ @pytest.mark.parametrize("resample", ["bilinear"]) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, distortion_scale, resample, align_corners, same_on_batch, device, dtype):
@@ -303,10 +303,10 @@ class TestRandomPerspectiveBackward:
if not isinstance(distortion_scale, (float, int)):
assert isinstance(aug._param_generator.distortion_scale, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug._param_generator.distortion_scale.is_cuda:
+ if resample == "nearest" and aug._param_generator.distortion_scale.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug._param_generator.distortion_scale._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug._param_generator.distortion_scale._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (
@@ -321,8 +321,8 @@ class TestRandomPerspectiveBackward:
class TestRandomMotionBlurBackward:
@pytest.mark.parametrize("angle", [20.0, torch.tensor([-20.0, 20.0])])
@pytest.mark.parametrize("direction", [[-0.5, 0.5], torch.tensor([-0.5, 0.5])])
- @pytest.mark.parametrize("border_type", ['constant', 'reflect', 'replicate', 'circular'])
- @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
+ @pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])
+ @pytest.mark.parametrize("resample", ["bilinear"]) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, angle, direction, border_type, resample, same_on_batch, device, dtype):
_angle = (
@@ -351,10 +351,10 @@ class TestRandomMotionBlurBackward:
if not isinstance(angle, (float, int, list, tuple)):
assert isinstance(aug._param_generator.angle, torch.Tensor)
- if resample == 'nearest' and aug._param_generator.angle.is_cuda:
+ if resample == "nearest" and aug._param_generator.angle.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug._param_generator.angle._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug._param_generator.angle._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (angle.to(device=device, dtype=dtype) - aug._param_generator.angle.data).sum() == 0
@@ -405,7 +405,7 @@ class TestRandomResizedCropBackward:
@pytest.mark.skip("Param gen is probably breaking grads.")
@pytest.mark.parametrize("scale", [[0.08, 1.0], torch.tensor([0.08, 1.0])])
@pytest.mark.parametrize("ratio", [[3.0 / 4.0, 4.0 / 3.0], torch.tensor([3.0 / 4.0, 4.0 / 3.0])])
- @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
+ @pytest.mark.parametrize("resample", ["bilinear"]) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, scale, ratio, resample, align_corners, same_on_batch, device, dtype):
diff --git a/test/augmentation/test_backward_3d.py b/test/augmentation/test_backward_3d.py
index 163864d58..1594eccb7 100644
--- a/test/augmentation/test_backward_3d.py
+++ b/test/augmentation/test_backward_3d.py
@@ -42,7 +42,7 @@ class TestRandomAffine3DBackward:
torch.tensor([(-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0)]),
],
)
- @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
+ @pytest.mark.parametrize("resample", ["bilinear"]) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, degrees, translate, scale, shear, resample, align_corners, same_on_batch, device, dtype):
@@ -92,10 +92,10 @@ class TestRandomAffine3DBackward:
if not isinstance(degrees, (int, float, list, tuple)):
assert isinstance(aug.degrees, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug.degrees.is_cuda:
+ if resample == "nearest" and aug.degrees.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug.degrees._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() == 0
@@ -104,10 +104,10 @@ class TestRandomAffine3DBackward:
if not isinstance(translate, (int, float, list, tuple)):
assert isinstance(aug.translate, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug.translate.is_cuda:
+ if resample == "nearest" and aug.translate.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.translate._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug.translate._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (translate.to(device=device, dtype=dtype) - aug.translate.data).sum() == 0
@@ -116,10 +116,10 @@ class TestRandomAffine3DBackward:
if not isinstance(scale, (int, float, list, tuple)):
assert isinstance(aug.scale, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug.scale.is_cuda:
+ if resample == "nearest" and aug.scale.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.scale._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug.scale._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() == 0
@@ -128,10 +128,10 @@ class TestRandomAffine3DBackward:
if not isinstance(shear, (int, float, list, tuple)):
assert isinstance(aug.shears, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug.shears.is_cuda:
+ if resample == "nearest" and aug.shears.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.shears._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug.shears._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (shear.to(device=device, dtype=dtype) - aug.shears.data).sum() == 0
@@ -153,7 +153,7 @@ class TestRandomRotation3DBackward:
torch.tensor([(10, 20), (10, 20), (10, 20)]),
],
)
- @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
+ @pytest.mark.parametrize("resample", ["bilinear"]) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, degrees, resample, align_corners, same_on_batch, device, dtype):
@@ -179,10 +179,10 @@ class TestRandomRotation3DBackward:
if not isinstance(degrees, (int, float, list, tuple)):
assert isinstance(aug._param_generator.degrees, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug._param_generator.degrees.is_cuda:
+ if resample == "nearest" and aug._param_generator.degrees.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug._param_generator.degrees._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug._param_generator.degrees._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (degrees.to(device=device, dtype=dtype) - aug._param_generator.degrees.data).sum() == 0
@@ -192,7 +192,7 @@ class TestRandomRotation3DBackward:
class TestRandomPerspective3DBackward:
@pytest.mark.parametrize("distortion_scale", [0.5, torch.tensor(0.5)])
- @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
+ @pytest.mark.parametrize("resample", ["bilinear"]) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, distortion_scale, resample, align_corners, same_on_batch, device, dtype):
@@ -220,10 +220,10 @@ class TestRandomPerspective3DBackward:
if not isinstance(distortion_scale, (float, int)):
assert isinstance(aug._param_generator.distortion_scale, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug._param_generator.distortion_scale.is_cuda:
+ if resample == "nearest" and aug._param_generator.distortion_scale.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug._param_generator.distortion_scale._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug._param_generator.distortion_scale._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (
@@ -239,8 +239,8 @@ class TestRandomMotionBlur3DBackward:
@pytest.mark.parametrize("angle", [20.0, torch.tensor(20.0), torch.tensor([20.0])])
@pytest.mark.parametrize("direction", [[-0.5, 0.5], torch.tensor([-0.5, 0.5])])
# 'reflect' is not implemented by torch.
- @pytest.mark.parametrize("border_type", ['constant', 'replicate', 'circular'])
- @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
+ @pytest.mark.parametrize("border_type", ["constant", "replicate", "circular"])
+ @pytest.mark.parametrize("resample", ["bilinear"]) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, angle, direction, border_type, resample, same_on_batch, device, dtype):
_angle = (
@@ -269,10 +269,10 @@ class TestRandomMotionBlur3DBackward:
if not isinstance(angle, (float, int, list, tuple)):
assert isinstance(aug._param_generator.angle, torch.Tensor)
- if resample == 'nearest' and aug._param_generator.angle.is_cuda:
+ if resample == "nearest" and aug._param_generator.angle.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug._param_generator.angle._grad == 0.0):
+ elif resample == "nearest" or torch.all(aug._param_generator.angle._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (angle.to(device=device, dtype=dtype) - aug._param_generator.angle.data).sum() == 0
diff --git a/test/augmentation/test_base.py b/test/augmentation/test_base.py
index 7a1082938..276fcedba 100644
--- a/test/augmentation/test_base.py
+++ b/test/augmentation/test_base.py
@@ -48,13 +48,13 @@ class TestBasicAugmentationBase:
augmentation = _BasicAugmentationBase(p, p_batch, same_on_batch)
with patch.object(augmentation, "generate_parameters", autospec=True) as generate_parameters:
generate_parameters.side_effect = lambda shape: {
- 'degrees': torch.arange(0, shape[0], device=device, dtype=dtype)
+ "degrees": torch.arange(0, shape[0], device=device, dtype=dtype)
}
output = augmentation.forward_parameters(input_shape)
assert "batch_prob" in output
- assert len(output['degrees']) == output['batch_prob'].sum().item() == num
+ assert len(output["degrees"]) == output["batch_prob"].sum().item() == num
- @pytest.mark.parametrize('keepdim', (True, False))
+ @pytest.mark.parametrize("keepdim", (True, False))
def test_forward(self, device, dtype, keepdim):
torch.manual_seed(42)
input = torch.rand((12, 3, 4, 5), device=device, dtype=dtype)
@@ -68,7 +68,7 @@ class TestBasicAugmentationBase:
augmentation, "transform_output_tensor", autospec=True
) as transform_output_tensor:
generate_parameters.side_effect = lambda shape: {
- 'degrees': torch.arange(0, shape[0], device=device, dtype=dtype)
+ "degrees": torch.arange(0, shape[0], device=device, dtype=dtype)
}
transform_tensor.side_effect = lambda x: x.unsqueeze(dim=0)
transform_output_tensor.side_effect = lambda x, y: x.squeeze()
@@ -91,7 +91,7 @@ class TestAugmentationBase2D:
augmentation, "generate_parameters", autospec=True
) as generate_parameters:
# Calling the augmentation with a single tensor shall return the expected tensor using the generated params.
- params = {'params': {}, 'flags': {'foo': 0}}
+ params = {"params": {}, "flags": {"foo": 0}}
generate_parameters.return_value = params
apply_transform.return_value = expected_output
output = augmentation(input)
@@ -107,7 +107,7 @@ class TestAugmentationBase2D:
assert output is expected_output
# Calling the augmentation with a tensor and params shall return the expected tensor using the given params.
- params = {'params': {}, 'flags': {'bar': 1}}
+ params = {"params": {}, "flags": {"bar": 1}}
apply_transform.reset_mock()
generate_parameters.return_value = None
output = augmentation(input, params=params)
@@ -137,7 +137,7 @@ class TestAugmentationBase2D:
output = utils.tensor_to_gradcheck_var(output) # to var
other_transform = utils.tensor_to_gradcheck_var(other_transform) # to var
- input_param = {'batch_prob': torch.tensor([True]), 'x': input_transform, 'y': {}}
+ input_param = {"batch_prob": torch.tensor([True]), "x": input_transform, "y": {}}
augmentation = AugmentationBase2D(p=1.0)
@@ -158,7 +158,7 @@ class TestGeometricAugmentationBase2D:
x = torch.rand(len(batch_prob), 5, 10, 7, dtype=dtype, device=device)
to_apply = torch.tensor(batch_prob, device=device)
- with patch.object(aug, '__batch_prob_generator__', return_value=to_apply):
+ with patch.object(aug, "__batch_prob_generator__", return_value=to_apply):
params = aug.forward_parameters(x.shape)
with torch.autocast(device.type):
@@ -179,7 +179,7 @@ class TestIntensityAugmentationBase2D:
x = torch.rand(len(batch_prob), 5, 10, 7, dtype=dtype, device=device)
to_apply = torch.tensor(batch_prob, device=device)
- with patch.object(aug, '__batch_prob_generator__', return_value=to_apply):
+ with patch.object(aug, "__batch_prob_generator__", return_value=to_apply):
params = aug.forward_parameters(x.shape)
with torch.autocast(device.type):
@@ -200,7 +200,7 @@ class TestIntensityAugmentationBase3D:
x = torch.rand(len(batch_prob), 1, 3, 10, 7, dtype=dtype, device=device)
to_apply = torch.tensor(batch_prob, device=device)
- with patch.object(aug, '__batch_prob_generator__', return_value=to_apply):
+ with patch.object(aug, "__batch_prob_generator__", return_value=to_apply):
params = aug.forward_parameters(x.shape)
with torch.autocast(device.type):
@@ -221,7 +221,7 @@ class TestGeometricAugmentationBase3D:
x = torch.rand(len(batch_prob), 1, 3, 10, 7, dtype=dtype, device=device)
to_apply = torch.tensor(batch_prob, device=device)
- with patch.object(aug, '__batch_prob_generator__', return_value=to_apply):
+ with patch.object(aug, "__batch_prob_generator__", return_value=to_apply):
params = aug.forward_parameters(x.shape)
with torch.autocast(device.type):
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index 5dfa2f6be..7a97c647c 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -45,8 +45,8 @@ class TestVideoSequential:
aug_list(input_1)
aug_list(input_2)
- @pytest.mark.parametrize('shape', [(3, 4), (2, 3, 4), (2, 3, 5, 6), (2, 3, 4, 5, 6, 7)])
- @pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
+ @pytest.mark.parametrize("shape", [(3, 4), (2, 3, 4), (2, 3, 5, 6), (2, 3, 4, 5, 6, 7)])
+ @pytest.mark.parametrize("data_format", ["BCTHW", "BTCHW"])
def test_exception(self, shape, data_format, device, dtype):
aug_list = K.VideoSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1), data_format=data_format, same_on_frame=True)
with pytest.raises(AssertionError):
@@ -54,7 +54,7 @@ class TestVideoSequential:
aug_list(img)
@pytest.mark.parametrize(
- 'augmentation',
+ "augmentation",
[
K.RandomAffine(360, p=1.0),
K.CenterCrop((3, 3), p=1.0),
@@ -79,7 +79,7 @@ class TestVideoSequential:
K.RandomTranslate((0.5, 0.5), p=1.0),
],
)
- @pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
+ @pytest.mark.parametrize("data_format", ["BCTHW", "BTCHW"])
def test_augmentation(self, augmentation, data_format, device, dtype):
input = torch.randint(255, (1, 3, 3, 5, 6), device=device, dtype=dtype).repeat(2, 1, 1, 1, 1) / 255.0
torch.manual_seed(21)
@@ -87,7 +87,7 @@ class TestVideoSequential:
reproducibility_test(input, aug_list)
@pytest.mark.parametrize(
- 'augmentations',
+ "augmentations",
[
[K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)],
[K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)],
@@ -99,20 +99,20 @@ class TestVideoSequential:
# [K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0), K.RandomMixUpV2(p=1.0)],
],
)
- @pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
- @pytest.mark.parametrize('random_apply', [1, (1, 1), (1,), 10, True, False])
+ @pytest.mark.parametrize("data_format", ["BCTHW", "BTCHW"])
+ @pytest.mark.parametrize("random_apply", [1, (1, 1), (1,), 10, True, False])
def test_same_on_frame(self, augmentations, data_format, random_apply, device, dtype):
aug_list = K.VideoSequential(
*augmentations, data_format=data_format, same_on_frame=True, random_apply=random_apply
)
- if data_format == 'BCTHW':
+ if data_format == "BCTHW":
input = torch.randn(2, 3, 1, 5, 6, device=device, dtype=dtype).repeat(1, 1, 4, 1, 1)
output = aug_list(input)
assert_close(output[:, :, 0], output[:, :, 1])
assert_close(output[:, :, 1], output[:, :, 2])
assert_close(output[:, :, 2], output[:, :, 3])
- if data_format == 'BTCHW':
+ if data_format == "BTCHW":
input = torch.randn(2, 1, 3, 5, 6, device=device, dtype=dtype).repeat(1, 4, 1, 1, 1)
output = aug_list(input)
assert_close(output[:, 0], output[:, 1])
@@ -121,7 +121,7 @@ class TestVideoSequential:
reproducibility_test(input, aug_list)
@pytest.mark.parametrize(
- 'augmentations',
+ "augmentations",
[
[K.RandomAffine(360, p=1.0)],
[K.RandomCrop((2, 2), padding=2)],
@@ -129,28 +129,28 @@ class TestVideoSequential:
[K.RandomAffine(360, p=0.0), K.ImageSequential(K.RandomAffine(360, p=0.0))],
],
)
- @pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
+ @pytest.mark.parametrize("data_format", ["BCTHW", "BTCHW"])
def test_against_sequential(self, augmentations, data_format, device, dtype):
aug_list_1 = K.VideoSequential(*augmentations, data_format=data_format, same_on_frame=False)
aug_list_2 = torch.nn.Sequential(*augmentations)
- if data_format == 'BCTHW':
+ if data_format == "BCTHW":
input = torch.randn(2, 3, 1, 5, 6, device=device, dtype=dtype).repeat(1, 1, 4, 1, 1)
- if data_format == 'BTCHW':
+ if data_format == "BTCHW":
input = torch.randn(2, 1, 3, 5, 6, device=device, dtype=dtype).repeat(1, 4, 1, 1, 1)
torch.manual_seed(0)
output_1 = aug_list_1(input)
torch.manual_seed(0)
- if data_format == 'BCTHW':
+ if data_format == "BCTHW":
input = input.transpose(1, 2)
output_2 = aug_list_2(input.reshape(-1, 3, 5, 6))
if any(isinstance(a, K.RandomCrop) for a in augmentations):
output_2 = output_2.view(2, 4, 3, 2, 2)
else:
output_2 = output_2.view(2, 4, 3, 5, 6)
- if data_format == 'BCTHW':
+ if data_format == "BCTHW":
output_2 = output_2.transpose(1, 2)
assert_close(output_1, output_2)
@@ -163,26 +163,26 @@ class TestVideoSequential:
op_jit = torch.jit.script(op)
assert_close(op(img), op_jit(img))
- @pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
+ @pytest.mark.parametrize("data_format", ["BCTHW", "BTCHW"])
def test_autocast(self, data_format, device, dtype):
if not hasattr(torch, "autocast"):
pytest.skip("PyTorch version without autocast support")
tfs = (K.RandomAffine(0.5, (0.1, 0.5), (0.5, 1.5), 1.2, p=1.0), K.RandomGaussianBlur((3, 3), (0.1, 3), p=1))
aug = K.VideoSequential(*tfs, data_format=data_format, random_apply=True)
- if data_format == 'BCTHW':
+ if data_format == "BCTHW":
imgs = torch.randn(2, 3, 1, 5, 6, device=device, dtype=dtype).repeat(1, 1, 4, 1, 1)
- elif data_format == 'BTCHW':
+ elif data_format == "BTCHW":
imgs = torch.randn(2, 1, 3, 5, 6, device=device, dtype=dtype).repeat(1, 4, 1, 1, 1)
with torch.autocast(device.type):
output = aug(imgs)
- assert output.dtype == dtype, 'Output image dtype should match the input dtype'
+ assert output.dtype == dtype, "Output image dtype should match the input dtype"
class TestSequential:
- @pytest.mark.parametrize('random_apply_weights', [None, [0.8, 0.9]])
+ @pytest.mark.parametrize("random_apply_weights", [None, [0.8, 0.9]])
def test_exception(self, random_apply_weights, device, dtype):
inp = torch.randn(1, 3, 30, 30, device=device, dtype=dtype)
with pytest.raises(Exception): # AssertError and NotImplementedError
@@ -190,9 +190,9 @@ class TestSequential:
K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), random_apply_weights=random_apply_weights
).inverse(inp)
- @pytest.mark.parametrize('same_on_batch', [True, False, None])
+ @pytest.mark.parametrize("same_on_batch", [True, False, None])
@pytest.mark.parametrize("keepdim", [True, False, None])
- @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 20, True, False])
+ @pytest.mark.parametrize("random_apply", [1, (2, 2), (1, 2), (2,), 20, True, False])
def test_construction(self, same_on_batch, keepdim, random_apply):
aug = K.ImageSequential(
K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
@@ -208,7 +208,7 @@ class TestSequential:
assert m.same_on_batch is True, m.same_on_batch
assert m.keepdim is True, m.keepdim
- @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
+ @pytest.mark.parametrize("random_apply", [1, (2, 2), (1, 2), (2,), 10, True, False])
def test_forward(self, random_apply, device, dtype):
inp = torch.randn(1, 3, 30, 30, device=device, dtype=dtype)
aug = K.ImageSequential(
@@ -229,7 +229,7 @@ class TestSequential:
class TestAugmentationSequential:
@pytest.mark.parametrize(
- 'data_keys', ["input", "image", ["mask", "input"], ["input", "bbox_yxyx"], [0, 10], [BorderType.REFLECT]]
+ "data_keys", ["input", "image", ["mask", "input"], ["input", "bbox_yxyx"], [0, 10], [BorderType.REFLECT]]
)
@pytest.mark.parametrize("augmentation_list", [K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)])
def test_exception(self, augmentation_list, data_keys, device, dtype):
@@ -237,9 +237,9 @@ class TestAugmentationSequential:
K.AugmentationSequential(augmentation_list, data_keys=data_keys)
@pytest.mark.slow
- @pytest.mark.parametrize('same_on_batch', [True, False])
- @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
- @pytest.mark.parametrize('inp', [torch.randn(1, 3, 1000, 500), torch.randn(3, 1000, 500)])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
+ @pytest.mark.parametrize("random_apply", [1, (2, 2), (1, 2), (2,), 10, True, False])
+ @pytest.mark.parametrize("inp", [torch.randn(1, 3, 1000, 500), torch.randn(3, 1000, 500)])
def test_mixup(self, inp, random_apply, same_on_batch, device, dtype):
inp = torch.as_tensor(inp, device=device, dtype=dtype)
aug = K.AugmentationSequential(
@@ -320,7 +320,7 @@ class TestAugmentationSequential:
[[[1.0, 1.0, 2.0, 2.0], [0.0, 0.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0]]], device=device, dtype=dtype
).expand(3, -1, -1)
aug = K.AugmentationSequential(
- K.RandomCrop((crop_width, crop_height), padding=1, cropping_mode='resample', fill=0),
+ K.RandomCrop((crop_width, crop_height), padding=1, cropping_mode="resample", fill=0),
K.RandomHorizontalFlip(p=1.0),
K.RandomMosaic(p=1.0),
data_keys=["input", "bbox_xyxy"],
@@ -336,7 +336,7 @@ class TestAugmentationSequential:
[[[1.0, 1.0, 2.0, 2.0], [0.0, 0.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0]]], device=device, dtype=dtype
).expand(3, -1, -1)
aug = K.AugmentationSequential(
- K.RandomCrop((crop_width, crop_height), padding=1, cropping_mode='resample', fill=0),
+ K.RandomCrop((crop_width, crop_height), padding=1, cropping_mode="resample", fill=0),
K.RandomHorizontalFlip(p=1.0),
data_keys=["input", "bbox_xyxy"],
)
@@ -347,13 +347,13 @@ class TestAugmentationSequential:
# specifying the crop locations allows us to compute by hand the expected outputs
crop_locations = torch.tensor(
[[1.0, 2.0], [1.0, 1.0], [2.0, 0.0]],
- device=_params[0].data['src'].device,
- dtype=_params[0].data['src'].dtype,
+ device=_params[0].data["src"].device,
+ dtype=_params[0].data["src"].dtype,
)
crops = crop_locations.expand(4, -1, -1).permute(1, 0, 2).clone()
crops[:, 1:3, 0] += crop_width - 1
crops[:, 2:4, 1] += crop_height - 1
- _params[0].data['src'] = crops
+ _params[0].data["src"] = crops
# expected output bboxes after crop for specified crop locations and crop size (3,3)
expected_out_bbox = torch.tensor(
@@ -409,7 +409,7 @@ class TestAugmentationSequential:
).expand(3, -1, -1)
points = torch.tensor([[[0.0, 0.0], [1.0, 1.0]]], device=device, dtype=dtype).expand(3, -1, -1)
aug = K.AugmentationSequential(
- K.RandomCrop((3, 3), padding=1, cropping_mode='resample', fill=0),
+ K.RandomCrop((3, 3), padding=1, cropping_mode="resample", fill=0),
K.RandomAffine((360.0, 360.0), p=1.0),
data_keys=["input", "mask", "bbox_xyxy", "keypoints"],
extra_args={},
@@ -419,14 +419,14 @@ class TestAugmentationSequential:
_params = aug.forward_parameters(input.shape)
# specifying the crops allows us to compute by hand the expected outputs
- _params[0].data['src'] = torch.tensor(
+ _params[0].data["src"] = torch.tensor(
[
[[1.0, 2.0], [3.0, 2.0], [3.0, 4.0], [1.0, 4.0]],
[[1.0, 1.0], [3.0, 1.0], [3.0, 3.0], [1.0, 3.0]],
[[2.0, 0.0], [4.0, 0.0], [4.0, 2.0], [2.0, 2.0]],
],
- device=_params[0].data['src'].device,
- dtype=_params[0].data['src'].dtype,
+ device=_params[0].data["src"].device,
+ dtype=_params[0].data["src"].dtype,
)
expected_out_bbox = torch.tensor(
@@ -471,7 +471,7 @@ class TestAugmentationSequential:
assert out[1].shape == (3, 1, size, size)
@pytest.mark.parametrize(
- 'bbox',
+ "bbox",
[
[
torch.tensor([[1, 5, 2, 7], [0, 3, 9, 9]]),
@@ -483,7 +483,7 @@ class TestAugmentationSequential:
],
)
@pytest.mark.parametrize(
- 'augmentation', [K.RandomCrop((30, 30), padding=1, cropping_mode='resample', fill=0), K.Resize((30, 30))]
+ "augmentation", [K.RandomCrop((30, 30), padding=1, cropping_mode="resample", fill=0), K.Resize((30, 30))]
)
def test_bbox(self, bbox, augmentation, device, dtype):
img = torch.rand((3, 3, 10, 10), device=device, dtype=dtype)
@@ -495,7 +495,7 @@ class TestAugmentationSequential:
inputs = [img, bbox]
- aug = K.AugmentationSequential(augmentation, data_keys=['input', 'bbox_xyxy'])
+ aug = K.AugmentationSequential(augmentation, data_keys=["input", "bbox_xyxy"])
transformed = aug(*inputs)
@@ -509,13 +509,13 @@ class TestAugmentationSequential:
def test_class(self, device, dtype):
img = torch.zeros((5, 1, 5, 5))
labels = torch.randint(0, 10, size=(5, 1))
- aug = K.AugmentationSequential(K.RandomCrop((3, 3), pad_if_needed=True), data_keys=['input', 'class'])
+ aug = K.AugmentationSequential(K.RandomCrop((3, 3), pad_if_needed=True), data_keys=["input", "class"])
_, out_labels = aug(img, labels)
assert labels is out_labels
@pytest.mark.slow
- @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
+ @pytest.mark.parametrize("random_apply", [1, (2, 2), (1, 2), (2,), 10, True, False])
def test_forward_and_inverse(self, random_apply, device, dtype):
inp = torch.randn(1, 3, 1000, 500, device=device, dtype=dtype)
bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
@@ -567,8 +567,8 @@ class TestAugmentationSequential:
K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
K.AugmentationSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
K.RandomAffine(360, p=1.0),
- K.RandomCrop(crop_size, padding=1, cropping_mode='resample', fill=0),
- data_keys=['input', 'mask', 'bbox', 'keypoints'],
+ K.RandomCrop(crop_size, padding=1, cropping_mode="resample", fill=0),
+ data_keys=["input", "mask", "bbox", "keypoints"],
extra_args={},
)
# NOTE: Mask data with nearest not passing reproducibility check under float64.
@@ -587,18 +587,18 @@ class TestAugmentationSequential:
assert out_inv[3].shape == keypoints.shape
aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0))
- assert aug(inp, data_keys=['input']).shape == inp.shape
+ assert aug(inp, data_keys=["input"]).shape == inp.shape
aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0))
- assert aug(inp, data_keys=['input']).shape == inp.shape
- assert aug(mask, data_keys=['mask'], params=aug._params).shape == mask.shape
+ assert aug(inp, data_keys=["input"]).shape == inp.shape
+ assert aug(mask, data_keys=["mask"], params=aug._params).shape == mask.shape
- assert aug.inverse(inp, data_keys=['input']).shape == inp.shape
- assert aug.inverse(bbox, data_keys=['bbox']).shape == bbox.shape
- assert aug.inverse(keypoints, data_keys=['keypoints']).shape == keypoints.shape
- assert aug.inverse(mask, data_keys=['mask']).shape == mask.shape
+ assert aug.inverse(inp, data_keys=["input"]).shape == inp.shape
+ assert aug.inverse(bbox, data_keys=["bbox"]).shape == bbox.shape
+ assert aug.inverse(keypoints, data_keys=["keypoints"]).shape == keypoints.shape
+ assert aug.inverse(mask, data_keys=["mask"]).shape == mask.shape
@pytest.mark.slow
- @pytest.mark.parametrize('random_apply', [2, (1, 1), (2,), 10, True, False])
+ @pytest.mark.parametrize("random_apply", [2, (1, 1), (2,), 10, True, False])
def test_forward_and_inverse_return_transform(self, random_apply, device, dtype):
inp = torch.randn(1, 3, 1000, 500, device=device, dtype=dtype)
bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
@@ -630,7 +630,7 @@ class TestAugmentationSequential:
assert out_inv[3].shape == keypoints.shape
@pytest.mark.slow
- @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
+ @pytest.mark.parametrize("random_apply", [1, (2, 2), (1, 2), (2,), 10, True, False])
def test_inverse_and_forward_return_transform(self, random_apply, device, dtype):
inp = torch.randn(1, 3, 1000, 500, device=device, dtype=dtype)
bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
@@ -683,7 +683,7 @@ class TestAugmentationSequential:
assert_close(op(img), op_jit(img))
@pytest.mark.parametrize("batch_prob", [[True, True], [False, True], [False, False]])
- @pytest.mark.parametrize("box", ['bbox', 'bbox_xyxy', 'bbox_xywh'])
+ @pytest.mark.parametrize("box", ["bbox", "bbox_xyxy", "bbox_xywh"])
def test_autocast(self, batch_prob, box, device, dtype):
if not hasattr(torch, "autocast"):
pytest.skip("PyTorch version without autocast support")
@@ -693,7 +693,7 @@ class TestAugmentationSequential:
params = []
for name, module in named_modules:
if isinstance(module, (K.base._AugmentationBase, K.MixAugmentationBaseV2, K.ImageSequential)):
- with patch.object(module, '__batch_prob_generator__', return_value=batch_prob):
+ with patch.object(module, "__batch_prob_generator__", return_value=batch_prob):
mod_param = module.forward_parameters(batch_shape)
param = ParamItem(name, mod_param)
@@ -704,11 +704,11 @@ class TestAugmentationSequential:
return params
tfs = (K.RandomAffine(0.5, (0.1, 0.5), (0.5, 1.5), 1.2, p=1.0), K.RandomGaussianBlur((3, 3), (0.1, 3), p=1))
- data_keys = ['input', 'mask', box, 'keypoints']
+ data_keys = ["input", "mask", box, "keypoints"]
aug = K.AugmentationSequential(*tfs, data_keys=data_keys, random_apply=True)
bs = len(batch_prob)
imgs = torch.rand(bs, 3, 7, 4, dtype=dtype, device=device)
- if box == 'bbox':
+ if box == "bbox":
bb = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], dtype=dtype, device=device).expand(
bs, 1, -1, -1
)
@@ -722,21 +722,21 @@ class TestAugmentationSequential:
to_apply = torch.tensor(batch_prob, device=device)
fwd_params = partial(mock_forward_parameters_sequential, cls=aug, batch_prob=to_apply)
- with patch.object(aug, 'forward_parameters', fwd_params):
+ with patch.object(aug, "forward_parameters", fwd_params):
params = aug.forward_parameters(imgs.shape)
with torch.autocast(device.type):
outputs = aug(imgs, msk, bb, points, params=params)
- assert outputs[0].dtype == dtype, 'Output image dtype should match the input dtype'
- assert outputs[1].dtype == dtype, 'Output mask dtype should match the input dtype'
- assert outputs[2].dtype == dtype, 'Output box dtype should match the input dtype'
- assert outputs[3].dtype == dtype, 'Output keypoints dtype should match the input dtype'
+ assert outputs[0].dtype == dtype, "Output image dtype should match the input dtype"
+ assert outputs[1].dtype == dtype, "Output mask dtype should match the input dtype"
+ assert outputs[2].dtype == dtype, "Output box dtype should match the input dtype"
+ assert outputs[3].dtype == dtype, "Output keypoints dtype should match the input dtype"
class TestPatchSequential:
@pytest.mark.parametrize(
- 'error_param',
+ "error_param",
[
{"random_apply": False, "patchwise_apply": True, "grid_size": (2, 3)},
{"random_apply": 2, "patchwise_apply": True},
@@ -761,12 +761,12 @@ class TestPatchSequential:
**error_param,
)
- @pytest.mark.parametrize('shape', [(2, 3, 24, 24)])
- @pytest.mark.parametrize('padding', ["same", "valid"])
- @pytest.mark.parametrize('patchwise_apply', [True, False])
- @pytest.mark.parametrize('same_on_batch', [True, False, None])
- @pytest.mark.parametrize('keepdim', [True, False, None])
- @pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
+ @pytest.mark.parametrize("shape", [(2, 3, 24, 24)])
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ @pytest.mark.parametrize("patchwise_apply", [True, False])
+ @pytest.mark.parametrize("same_on_batch", [True, False, None])
+ @pytest.mark.parametrize("keepdim", [True, False, None])
+ @pytest.mark.parametrize("random_apply", [1, (2, 2), (1, 2), (2,), 10, True, False])
def test_forward(self, shape, padding, patchwise_apply, same_on_batch, keepdim, random_apply, device, dtype):
torch.manual_seed(11)
try: # skip wrong param settings.
@@ -834,7 +834,7 @@ class TestPatchSequential:
with torch.autocast(device.type):
output = aug(imgs)
- assert output.dtype == dtype, 'Output image dtype should match the input dtype'
+ assert output.dtype == dtype, "Output image dtype should match the input dtype"
class TestDispatcher:
@@ -862,7 +862,7 @@ class TestDispatcher:
assert output[0][1].shape == mask_1.shape
assert output[1][1].shape == mask_2.shape
- @pytest.mark.parametrize('strict', [True, False])
+ @pytest.mark.parametrize("strict", [True, False])
def test_many_to_one(self, strict, device, dtype):
input = torch.randn(2, 3, 5, 6, device=device, dtype=dtype)
mask = torch.ones(2, 1, 5, 6, device=device, dtype=dtype)
@@ -886,7 +886,7 @@ class TestDispatcher:
assert output[0][1].shape == mask.shape
assert output[1][1].shape == mask.shape
- @pytest.mark.parametrize('strict', [True, False])
+ @pytest.mark.parametrize("strict", [True, False])
def test_many_to_one_strict_mode(self, strict):
def _init_many_to_one(strict):
K.ManyToOneAugmentationDispather(
diff --git a/test/augmentation/test_motionblur.py b/test/augmentation/test_motionblur.py
index 91da2df49..004325710 100644
--- a/test/augmentation/test_motionblur.py
+++ b/test/augmentation/test_motionblur.py
@@ -49,10 +49,10 @@ class TestRandomMotionBlur:
expected = motion_blur(
input,
- f._params['ksize_factor'].unique().item(),
- f._params['angle_factor'],
- f._params['direction_factor'],
- f.flags['border_type'].name.lower(),
+ f._params["ksize_factor"].unique().item(),
+ f._params["angle_factor"],
+ f._params["direction_factor"],
+ f.flags["border_type"].name.lower(),
)
assert_close(output, expected, rtol=1e-4, atol=1e-4)
@@ -64,12 +64,12 @@ class TestRandomMotionBlur:
inp = tensor_to_gradcheck_var(inp) # to var
# TODO: Gradcheck for param random gen failed. Suspect get_motion_kernel2d issue.
params = {
- 'batch_prob': torch.tensor([True]),
- 'ksize_factor': torch.tensor([31]),
- 'angle_factor': torch.tensor([30.0]),
- 'direction_factor': torch.tensor([-0.5]),
- 'border_type': torch.tensor([0]),
- 'idx': torch.tensor([0]),
+ "batch_prob": torch.tensor([True]),
+ "ksize_factor": torch.tensor([31]),
+ "angle_factor": torch.tensor([30.0]),
+ "direction_factor": torch.tensor([-0.5]),
+ "border_type": torch.tensor([0]),
+ "idx": torch.tensor([0]),
}
assert gradcheck(
RandomMotionBlur(kernel_size=3, angle=(10, 30), direction=(-0.5, 0.5), p=1.0),
@@ -119,10 +119,10 @@ class TestRandomMotionBlur3D:
expected = motion_blur3d(
input,
- f._params['ksize_factor'].unique().item(),
- f._params['angle_factor'],
- f._params['direction_factor'],
- f.flags['border_type'].name.lower(),
+ f._params["ksize_factor"].unique().item(),
+ f._params["angle_factor"],
+ f._params["direction_factor"],
+ f.flags["border_type"].name.lower(),
)
assert_close(output, expected, rtol=1e-4, atol=1e-4)
@@ -133,12 +133,12 @@ class TestRandomMotionBlur3D:
inp = torch.rand((1, 3, 6, 7), device=device, dtype=dtype)
inp = tensor_to_gradcheck_var(inp) # to var
params = {
- 'batch_prob': torch.tensor([True]),
- 'ksize_factor': torch.tensor([31]),
- 'angle_factor': torch.tensor([[30.0, 30.0, 30.0]]),
- 'direction_factor': torch.tensor([-0.5]),
- 'border_type': torch.tensor([0]),
- 'idx': torch.tensor([0]),
+ "batch_prob": torch.tensor([True]),
+ "ksize_factor": torch.tensor([31]),
+ "angle_factor": torch.tensor([[30.0, 30.0, 30.0]]),
+ "direction_factor": torch.tensor([-0.5]),
+ "border_type": torch.tensor([0]),
+ "idx": torch.tensor([0]),
}
assert gradcheck(
RandomMotionBlur3D(kernel_size=3, angle=(10, 30), direction=(-0.5, 0.5), p=1.0),
diff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.py
index 7a64b4986..451526c1e 100644
--- a/test/augmentation/test_random_generator.py
+++ b/test/augmentation/test_random_generator.py
@@ -37,14 +37,14 @@ class RandomGeneratorBaseTests:
class TestRandomProbGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('p', [0.0, 0.5, 1.0])
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("p", [0.0, 0.5, 1.0])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(self, p, batch_size, same_on_batch):
ProbabilityGenerator(p)(torch.Size([batch_size]), same_on_batch)
@pytest.mark.parametrize(
- 'p',
+ "p",
[
# Should be failed if p > 1. or p < 0.
(-1.0),
@@ -56,30 +56,30 @@ class TestRandomProbGen(RandomGeneratorBaseTests):
ProbabilityGenerator(p)(torch.Size([8]))
@pytest.mark.parametrize(
- 'p,expected',
+ "p,expected",
[(0.0, [False] * 8), (0.5, [False, False, True, False, True, False, True, False]), (1.0, [True] * 8)],
)
def test_random_gen(self, p, expected, device, dtype):
torch.manual_seed(42)
batch_size = 8
res = ProbabilityGenerator(p)(torch.Size([batch_size]))
- assert (res['probs'] == torch.tensor(expected)).long().sum() == batch_size
+ assert (res["probs"] == torch.tensor(expected)).long().sum() == batch_size
@pytest.mark.parametrize("seed,expected", [(42, [False] * 8), (0, [True] * 8)])
def test_same_on_batch(self, seed, expected, device, dtype):
torch.manual_seed(seed)
batch_size = 8
res = ProbabilityGenerator(0.5)(torch.Size([batch_size]), True)
- assert (res['probs'] == torch.tensor(expected)).long().sum() == batch_size
+ assert (res["probs"] == torch.tensor(expected)).long().sum() == batch_size
class TestColorJiggleGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('brightness', [None, torch.tensor([0.8, 1.2])])
- @pytest.mark.parametrize('contrast', [None, torch.tensor([0.8, 1.2])])
- @pytest.mark.parametrize('saturation', [None, torch.tensor([0.8, 1.2])])
- @pytest.mark.parametrize('hue', [None, torch.tensor([-0.1, 0.1])])
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("brightness", [None, torch.tensor([0.8, 1.2])])
+ @pytest.mark.parametrize("contrast", [None, torch.tensor([0.8, 1.2])])
+ @pytest.mark.parametrize("saturation", [None, torch.tensor([0.8, 1.2])])
+ @pytest.mark.parametrize("hue", [None, torch.tensor([-0.1, 0.1])])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(
self, brightness, contrast, saturation, hue, batch_size, same_on_batch, device, dtype
):
@@ -95,7 +95,7 @@ class TestColorJiggleGen(RandomGeneratorBaseTests):
)(torch.Size([batch_size]), same_on_batch)
@pytest.mark.parametrize(
- 'brightness,contrast,saturation,hue',
+ "brightness,contrast,saturation,hue",
[
# Should be failed if value out of bounds or tensor.shape != [1, 2]
(torch.tensor([-1.0, 2.0]), None, None, None),
@@ -140,39 +140,39 @@ class TestColorJiggleGen(RandomGeneratorBaseTests):
)(torch.Size([batch_size]))
expected_jitter_params = {
- 'brightness_factor': torch.tensor(
+ "brightness_factor": torch.tensor(
[1.1529, 1.1660, 0.9531, 1.1837, 0.9562, 1.0404, 0.9026, 1.1175], device=device, dtype=dtype
),
- 'contrast_factor': torch.tensor(
+ "contrast_factor": torch.tensor(
[1.2645, 0.7799, 1.2608, 1.0561, 1.2216, 1.0406, 1.1447, 0.9576], device=device, dtype=dtype
),
- 'hue_factor': torch.tensor(
+ "hue_factor": torch.tensor(
[0.0771, 0.0148, -0.0467, 0.0255, -0.0461, -0.0117, -0.0406, 0.0663], device=device, dtype=dtype
),
- 'saturation_factor': torch.tensor(
+ "saturation_factor": torch.tensor(
[0.6843, 0.8156, 0.8871, 0.7595, 1.0378, 0.6049, 1.3612, 0.6602], device=device, dtype=dtype
),
- 'order': torch.tensor([3, 2, 0, 1], device=device, dtype=dtype),
+ "order": torch.tensor([3, 2, 0, 1], device=device, dtype=dtype),
}
assert set(jitter_params.keys()) == {
- 'brightness_factor',
- 'contrast_factor',
- 'hue_factor',
- 'saturation_factor',
- 'order',
+ "brightness_factor",
+ "contrast_factor",
+ "hue_factor",
+ "saturation_factor",
+ "order",
}, "Redundant keys found apart from \
'brightness_factor', 'contrast_factor', 'hue_factor', 'saturation_factor', 'order'"
assert_close(
- jitter_params['brightness_factor'], expected_jitter_params['brightness_factor'], rtol=1e-4, atol=1e-4
+ jitter_params["brightness_factor"], expected_jitter_params["brightness_factor"], rtol=1e-4, atol=1e-4
)
- assert_close(jitter_params['contrast_factor'], expected_jitter_params['contrast_factor'], rtol=1e-4, atol=1e-4)
- assert_close(jitter_params['hue_factor'], expected_jitter_params['hue_factor'], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["contrast_factor"], expected_jitter_params["contrast_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["hue_factor"], expected_jitter_params["hue_factor"], rtol=1e-4, atol=1e-4)
assert_close(
- jitter_params['saturation_factor'], expected_jitter_params['saturation_factor'], rtol=1e-4, atol=1e-4
+ jitter_params["saturation_factor"], expected_jitter_params["saturation_factor"], rtol=1e-4, atol=1e-4
)
- assert_close(jitter_params['order'].to(dtype), expected_jitter_params['order'], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["order"].to(dtype), expected_jitter_params["order"], rtol=1e-4, atol=1e-4)
def test_random_gen_accumulative_additive_additive(self, device, dtype):
torch.manual_seed(42)
@@ -185,39 +185,39 @@ class TestColorJiggleGen(RandomGeneratorBaseTests):
)(torch.Size([batch_size]))
expected_jitter_params = {
- 'brightness_factor': torch.tensor(
+ "brightness_factor": torch.tensor(
[1.1529, 1.1660, 0.9531, 1.1837, 0.9562, 1.0404, 0.9026, 1.1175], device=device, dtype=dtype
),
- 'contrast_factor': torch.tensor(
+ "contrast_factor": torch.tensor(
[1.2645, 0.7799, 1.2608, 1.0561, 1.2216, 1.0406, 1.1447, 0.9576], device=device, dtype=dtype
),
- 'hue_factor': torch.tensor(
+ "hue_factor": torch.tensor(
[0.0771, 0.0148, -0.0467, 0.0255, -0.0461, -0.0117, -0.0406, 0.0663], device=device, dtype=dtype
),
- 'saturation_factor': torch.tensor(
+ "saturation_factor": torch.tensor(
[0.6843, 0.8156, 0.8871, 0.7595, 1.0378, 0.6049, 1.3612, 0.6602], device=device, dtype=dtype
),
- 'order': torch.tensor([3, 2, 0, 1], device=device, dtype=dtype),
+ "order": torch.tensor([3, 2, 0, 1], device=device, dtype=dtype),
}
assert set(jitter_params.keys()) == {
- 'brightness_factor',
- 'contrast_factor',
- 'hue_factor',
- 'saturation_factor',
- 'order',
+ "brightness_factor",
+ "contrast_factor",
+ "hue_factor",
+ "saturation_factor",
+ "order",
}, "Redundant keys found apart from \
'brightness_factor', 'contrast_factor', 'hue_factor', 'saturation_factor', 'order'"
assert_close(
- jitter_params['brightness_factor'], expected_jitter_params['brightness_factor'], rtol=1e-4, atol=1e-4
+ jitter_params["brightness_factor"], expected_jitter_params["brightness_factor"], rtol=1e-4, atol=1e-4
)
- assert_close(jitter_params['contrast_factor'], expected_jitter_params['contrast_factor'], rtol=1e-4, atol=1e-4)
- assert_close(jitter_params['hue_factor'], expected_jitter_params['hue_factor'], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["contrast_factor"], expected_jitter_params["contrast_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["hue_factor"], expected_jitter_params["hue_factor"], rtol=1e-4, atol=1e-4)
assert_close(
- jitter_params['saturation_factor'], expected_jitter_params['saturation_factor'], rtol=1e-4, atol=1e-4
+ jitter_params["saturation_factor"], expected_jitter_params["saturation_factor"], rtol=1e-4, atol=1e-4
)
- assert_close(jitter_params['order'].to(dtype), expected_jitter_params['order'], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["order"].to(dtype), expected_jitter_params["order"], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -230,27 +230,27 @@ class TestColorJiggleGen(RandomGeneratorBaseTests):
)(torch.Size([batch_size]), same_on_batch=True)
expected_res = {
- 'brightness_factor': torch.tensor([1.1529] * batch_size, device=device, dtype=dtype),
- 'contrast_factor': torch.tensor([1.2490] * batch_size, device=device, dtype=dtype),
- 'hue_factor': torch.tensor([-0.0234] * batch_size, device=device, dtype=dtype),
- 'saturation_factor': torch.tensor([1.3674] * batch_size, device=device, dtype=dtype),
- 'order': torch.tensor([2, 3, 0, 1], device=device, dtype=dtype),
+ "brightness_factor": torch.tensor([1.1529] * batch_size, device=device, dtype=dtype),
+ "contrast_factor": torch.tensor([1.2490] * batch_size, device=device, dtype=dtype),
+ "hue_factor": torch.tensor([-0.0234] * batch_size, device=device, dtype=dtype),
+ "saturation_factor": torch.tensor([1.3674] * batch_size, device=device, dtype=dtype),
+ "order": torch.tensor([2, 3, 0, 1], device=device, dtype=dtype),
}
- assert_close(jitter_params['brightness_factor'], expected_res['brightness_factor'], rtol=1e-4, atol=1e-4)
- assert_close(jitter_params['contrast_factor'], expected_res['contrast_factor'], rtol=1e-4, atol=1e-4)
- assert_close(jitter_params['hue_factor'], expected_res['hue_factor'], rtol=1e-4, atol=1e-4)
- assert_close(jitter_params['saturation_factor'], expected_res['saturation_factor'], rtol=1e-4, atol=1e-4)
- assert_close(jitter_params['order'].to(dtype), expected_res['order'], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["brightness_factor"], expected_res["brightness_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["contrast_factor"], expected_res["contrast_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["hue_factor"], expected_res["hue_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["saturation_factor"], expected_res["saturation_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["order"].to(dtype), expected_res["order"], rtol=1e-4, atol=1e-4)
class TestColorJitterGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('brightness', [None, torch.tensor([0.8, 1.2])])
- @pytest.mark.parametrize('contrast', [None, torch.tensor([0.8, 1.2])])
- @pytest.mark.parametrize('saturation', [None, torch.tensor([0.8, 1.2])])
- @pytest.mark.parametrize('hue', [None, torch.tensor([-0.1, 0.1])])
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("brightness", [None, torch.tensor([0.8, 1.2])])
+ @pytest.mark.parametrize("contrast", [None, torch.tensor([0.8, 1.2])])
+ @pytest.mark.parametrize("saturation", [None, torch.tensor([0.8, 1.2])])
+ @pytest.mark.parametrize("hue", [None, torch.tensor([-0.1, 0.1])])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(
self, brightness, contrast, saturation, hue, batch_size, same_on_batch, device, dtype
):
@@ -266,7 +266,7 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
)(torch.Size([batch_size]), same_on_batch)
@pytest.mark.parametrize(
- 'brightness,contrast,saturation,hue',
+ "brightness,contrast,saturation,hue",
[
# Should be failed if value out of bounds or tensor.shape != [1, 2]
(torch.tensor([-1.0, 2.0]), None, None, None),
@@ -313,39 +313,39 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
)(torch.Size([batch_size]))
expected_jitter_params = {
- 'brightness_factor': torch.tensor(
+ "brightness_factor": torch.tensor(
[1.1529, 1.1660, 0.9531, 1.1837, 0.9562, 1.0404, 0.9026, 1.1175], device=device, dtype=dtype
),
- 'contrast_factor': torch.tensor(
+ "contrast_factor": torch.tensor(
[1.2645, 0.7799, 1.2608, 1.0561, 1.2216, 1.0406, 1.1447, 0.9576], device=device, dtype=dtype
),
- 'hue_factor': torch.tensor(
+ "hue_factor": torch.tensor(
[0.0771, 0.0148, -0.0467, 0.0255, -0.0461, -0.0117, -0.0406, 0.0663], device=device, dtype=dtype
),
- 'saturation_factor': torch.tensor(
+ "saturation_factor": torch.tensor(
[0.6843, 0.8156, 0.8871, 0.7595, 1.0378, 0.6049, 1.3612, 0.6602], device=device, dtype=dtype
),
- 'order': torch.tensor([3, 2, 0, 1], device=device, dtype=dtype),
+ "order": torch.tensor([3, 2, 0, 1], device=device, dtype=dtype),
}
assert set(jitter_params.keys()) == {
- 'brightness_factor',
- 'contrast_factor',
- 'hue_factor',
- 'saturation_factor',
- 'order',
+ "brightness_factor",
+ "contrast_factor",
+ "hue_factor",
+ "saturation_factor",
+ "order",
}, "Redundant keys found apart from \
'brightness_factor', 'contrast_factor', 'hue_factor', 'saturation_factor', 'order'"
assert_close(
- jitter_params['brightness_factor'], expected_jitter_params['brightness_factor'], rtol=1e-4, atol=1e-4
+ jitter_params["brightness_factor"], expected_jitter_params["brightness_factor"], rtol=1e-4, atol=1e-4
)
- assert_close(jitter_params['contrast_factor'], expected_jitter_params['contrast_factor'], rtol=1e-4, atol=1e-4)
- assert_close(jitter_params['hue_factor'], expected_jitter_params['hue_factor'], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["contrast_factor"], expected_jitter_params["contrast_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["hue_factor"], expected_jitter_params["hue_factor"], rtol=1e-4, atol=1e-4)
assert_close(
- jitter_params['saturation_factor'], expected_jitter_params['saturation_factor'], rtol=1e-4, atol=1e-4
+ jitter_params["saturation_factor"], expected_jitter_params["saturation_factor"], rtol=1e-4, atol=1e-4
)
- assert_close(jitter_params['order'].to(dtype), expected_jitter_params['order'], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["order"].to(dtype), expected_jitter_params["order"], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -358,32 +358,32 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
)(torch.Size([batch_size]), same_on_batch=True)
expected_res = {
- 'brightness_factor': torch.tensor([1.1529] * batch_size, device=device, dtype=dtype),
- 'contrast_factor': torch.tensor([1.2490] * batch_size, device=device, dtype=dtype),
- 'hue_factor': torch.tensor([-0.0234] * batch_size, device=device, dtype=dtype),
- 'saturation_factor': torch.tensor([1.3674] * batch_size, device=device, dtype=dtype),
- 'order': torch.tensor([2, 3, 0, 1], device=device, dtype=dtype),
+ "brightness_factor": torch.tensor([1.1529] * batch_size, device=device, dtype=dtype),
+ "contrast_factor": torch.tensor([1.2490] * batch_size, device=device, dtype=dtype),
+ "hue_factor": torch.tensor([-0.0234] * batch_size, device=device, dtype=dtype),
+ "saturation_factor": torch.tensor([1.3674] * batch_size, device=device, dtype=dtype),
+ "order": torch.tensor([2, 3, 0, 1], device=device, dtype=dtype),
}
- assert_close(jitter_params['brightness_factor'], expected_res['brightness_factor'], rtol=1e-4, atol=1e-4)
- assert_close(jitter_params['contrast_factor'], expected_res['contrast_factor'], rtol=1e-4, atol=1e-4)
- assert_close(jitter_params['hue_factor'], expected_res['hue_factor'], rtol=1e-4, atol=1e-4)
- assert_close(jitter_params['saturation_factor'], expected_res['saturation_factor'], rtol=1e-4, atol=1e-4)
- assert_close(jitter_params['order'].to(dtype), expected_res['order'], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["brightness_factor"], expected_res["brightness_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["contrast_factor"], expected_res["contrast_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["hue_factor"], expected_res["hue_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["saturation_factor"], expected_res["saturation_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(jitter_params["order"].to(dtype), expected_res["order"], rtol=1e-4, atol=1e-4)
class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('height,width', [(200, 200)])
- @pytest.mark.parametrize('distortion_scale', [torch.tensor(0.0), torch.tensor(0.5), torch.tensor(1.0)])
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("height,width", [(200, 200)])
+ @pytest.mark.parametrize("distortion_scale", [torch.tensor(0.0), torch.tensor(0.5), torch.tensor(1.0)])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(self, height, width, distortion_scale, batch_size, same_on_batch, device, dtype):
PerspectiveGenerator(distortion_scale.to(device=device, dtype=dtype))(
torch.Size([batch_size, 1, height, width]), same_on_batch
)
@pytest.mark.parametrize(
- 'height,width,distortion_scale',
+ "height,width,distortion_scale",
[
# Should be failed if distortion_scale > 1. or distortion_scale < 0.
(-100, 100, torch.tensor(0.5)),
@@ -403,7 +403,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
res = PerspectiveGenerator(torch.tensor(0.5, device=device, dtype=dtype))(torch.Size([batch_size, 1, 200, 200]))
expected = {
- 'start_points': torch.tensor(
+ "start_points": torch.tensor(
[
[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]],
[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]],
@@ -411,7 +411,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
device=device,
dtype=dtype,
),
- 'end_points': torch.tensor(
+ "end_points": torch.tensor(
[
[[44.1135, 45.7502], [179.8568, 47.9653], [179.4776, 168.9552], [12.8286, 159.3179]],
[[47.0386, 6.6593], [152.2701, 29.6790], [155.5298, 170.6142], [37.0547, 177.5298]],
@@ -421,8 +421,8 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
),
}
assert res.keys() == expected.keys()
- assert_close(res['start_points'], expected['start_points'])
- assert_close(res['end_points'], expected['end_points'])
+ assert_close(res["start_points"], expected["start_points"])
+ assert_close(res["end_points"], expected["end_points"])
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -431,18 +431,18 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
torch.Size([batch_size, 1, 200, 200]), same_on_batch=True
)
expected = {
- 'start_points': torch.tensor(
+ "start_points": torch.tensor(
[[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]]], device=device, dtype=dtype
).repeat(2, 1, 1),
- 'end_points': torch.tensor(
+ "end_points": torch.tensor(
[[[44.1135, 45.7502], [179.8568, 47.9653], [179.4776, 168.9552], [12.8286, 159.3179]]],
device=device,
dtype=dtype,
).repeat(2, 1, 1),
}
assert res.keys() == expected.keys()
- assert_close(res['start_points'], expected['start_points'])
- assert_close(res['end_points'], expected['end_points'])
+ assert_close(res["start_points"], expected["start_points"])
+ assert_close(res["end_points"], expected["end_points"])
def test_sampling_method(self, device, dtype):
torch.manual_seed(42)
@@ -452,7 +452,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
)
expected = {
- 'start_points': torch.tensor(
+ "start_points": torch.tensor(
[
[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]],
[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]],
@@ -460,7 +460,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
device=device,
dtype=dtype,
),
- 'end_points': torch.tensor(
+ "end_points": torch.tensor(
[
[[38.2269, 41.5004], [187.2864, 45.9306], [188.0448, 209.0895], [-24.3428, 228.3641]],
[[44.0771, -36.6814], [242.4598, 9.3580], [235.9404, 205.7715], [24.1094, 191.9404]],
@@ -470,8 +470,8 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
),
}
assert res.keys() == expected.keys()
- assert_close(res['start_points'], expected['start_points'])
- assert_close(res['end_points'], expected['end_points'])
+ assert_close(res["start_points"], expected["start_points"])
+ assert_close(res["end_points"], expected["end_points"])
def test_not_implemented_sampling_method(self, device, dtype):
batch_size = 2
@@ -482,14 +482,14 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
class TestRandomAffineGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 4])
- @pytest.mark.parametrize('height', [200])
- @pytest.mark.parametrize('width', [300])
- @pytest.mark.parametrize('degrees', [torch.tensor([0, 30])])
- @pytest.mark.parametrize('translate', [None, torch.tensor([0.1, 0.1])])
- @pytest.mark.parametrize('scale', [None, torch.tensor([0.7, 1.2])])
- @pytest.mark.parametrize('shear', [None, torch.tensor([[0, 20], [0, 20]])])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("batch_size", [0, 1, 4])
+ @pytest.mark.parametrize("height", [200])
+ @pytest.mark.parametrize("width", [300])
+ @pytest.mark.parametrize("degrees", [torch.tensor([0, 30])])
+ @pytest.mark.parametrize("translate", [None, torch.tensor([0.1, 0.1])])
+ @pytest.mark.parametrize("scale", [None, torch.tensor([0.7, 1.2])])
+ @pytest.mark.parametrize("shear", [None, torch.tensor([[0, 20], [0, 20]])])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(
self, batch_size, height, width, degrees, translate, scale, shear, same_on_batch, device, dtype
):
@@ -501,7 +501,7 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
)(torch.Size([batch_size, 1, height, width]), same_on_batch)
@pytest.mark.parametrize(
- 'height,width,degrees,translate,scale,shear',
+ "height,width,degrees,translate,scale,shear",
[
(-100, 100, torch.tensor([10, 20]), None, None, None),
(100, -100, torch.tensor([10, 20]), None, None, None),
@@ -538,20 +538,20 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
shear=shear.to(device=device, dtype=dtype) if shear is not None else None,
)(torch.Size([2, 1, 200, 200]))
expected = {
- 'translations': torch.tensor([[-4.3821, -9.7371], [4.0358, 11.7457]], device=device, dtype=dtype),
- 'center': torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),
- 'scale': torch.tensor([[0.8914, 0.8914], [1.1797, 1.1797]], device=device, dtype=dtype),
- 'angle': torch.tensor([18.8227, 19.1500], device=device, dtype=dtype),
- 'shear_x': torch.tensor([19.4077, 11.3319], device=device, dtype=dtype),
- 'shear_y': torch.tensor([19.3460, 15.9358], device=device, dtype=dtype),
+ "translations": torch.tensor([[-4.3821, -9.7371], [4.0358, 11.7457]], device=device, dtype=dtype),
+ "center": torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),
+ "scale": torch.tensor([[0.8914, 0.8914], [1.1797, 1.1797]], device=device, dtype=dtype),
+ "angle": torch.tensor([18.8227, 19.1500], device=device, dtype=dtype),
+ "shear_x": torch.tensor([19.4077, 11.3319], device=device, dtype=dtype),
+ "shear_y": torch.tensor([19.3460, 15.9358], device=device, dtype=dtype),
}
assert res.keys() == expected.keys()
- assert_close(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)
- assert_close(res['center'], expected['center'], rtol=1e-4, atol=1e-4)
- assert_close(res['scale'], expected['scale'], rtol=1e-4, atol=1e-4)
- assert_close(res['angle'], expected['angle'], rtol=1e-4, atol=1e-4)
- assert_close(res['shear_x'], expected['shear_x'], rtol=1e-4, atol=1e-4)
- assert_close(res['shear_y'], expected['shear_y'], rtol=1e-4, atol=1e-4)
+ assert_close(res["translations"], expected["translations"], rtol=1e-4, atol=1e-4)
+ assert_close(res["center"], expected["center"], rtol=1e-4, atol=1e-4)
+ assert_close(res["scale"], expected["scale"], rtol=1e-4, atol=1e-4)
+ assert_close(res["angle"], expected["angle"], rtol=1e-4, atol=1e-4)
+ assert_close(res["shear_x"], expected["shear_x"], rtol=1e-4, atol=1e-4)
+ assert_close(res["shear_y"], expected["shear_y"], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -566,35 +566,35 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
shear=shear.to(device=device, dtype=dtype) if shear is not None else None,
)(torch.Size([2, 1, 200, 200]), True)
expected = {
- 'translations': torch.tensor([[-4.6854, 18.3722], [-4.6854, 18.3722]], device=device, dtype=dtype),
- 'center': torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),
- 'scale': torch.tensor([[1.1575, 1.1575], [1.1575, 1.1575]], device=device, dtype=dtype),
- 'angle': torch.tensor([18.8227, 18.8227], device=device, dtype=dtype),
- 'shear_x': torch.tensor([13.9045, 13.9045], device=device, dtype=dtype),
- 'shear_y': torch.tensor([16.0090, 16.0090], device=device, dtype=dtype),
+ "translations": torch.tensor([[-4.6854, 18.3722], [-4.6854, 18.3722]], device=device, dtype=dtype),
+ "center": torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),
+ "scale": torch.tensor([[1.1575, 1.1575], [1.1575, 1.1575]], device=device, dtype=dtype),
+ "angle": torch.tensor([18.8227, 18.8227], device=device, dtype=dtype),
+ "shear_x": torch.tensor([13.9045, 13.9045], device=device, dtype=dtype),
+ "shear_y": torch.tensor([16.0090, 16.0090], device=device, dtype=dtype),
}
assert res.keys() == expected.keys()
- assert_close(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)
- assert_close(res['center'], expected['center'], rtol=1e-4, atol=1e-4)
- assert_close(res['scale'], expected['scale'], rtol=1e-4, atol=1e-4)
- assert_close(res['angle'], expected['angle'], rtol=1e-4, atol=1e-4)
- assert_close(res['shear_x'], expected['shear_x'], rtol=1e-4, atol=1e-4)
- assert_close(res['shear_y'], expected['shear_y'], rtol=1e-4, atol=1e-4)
+ assert_close(res["translations"], expected["translations"], rtol=1e-4, atol=1e-4)
+ assert_close(res["center"], expected["center"], rtol=1e-4, atol=1e-4)
+ assert_close(res["scale"], expected["scale"], rtol=1e-4, atol=1e-4)
+ assert_close(res["angle"], expected["angle"], rtol=1e-4, atol=1e-4)
+ assert_close(res["shear_x"], expected["shear_x"], rtol=1e-4, atol=1e-4)
+ assert_close(res["shear_y"], expected["shear_y"], rtol=1e-4, atol=1e-4)
class TestRandomCropGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 2])
- @pytest.mark.parametrize('input_size', [(200, 200)])
- @pytest.mark.parametrize('size', [(100, 100), torch.tensor([50, 50])])
- @pytest.mark.parametrize('resize_to', [None, (100, 100)])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("batch_size", [0, 2])
+ @pytest.mark.parametrize("input_size", [(200, 200)])
+ @pytest.mark.parametrize("size", [(100, 100), torch.tensor([50, 50])])
+ @pytest.mark.parametrize("resize_to", [None, (100, 100)])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(self, batch_size, input_size, size, resize_to, same_on_batch, device, dtype):
if isinstance(size, Tensor):
size = size.repeat(batch_size, 1).to(device=device, dtype=dtype)
CropGenerator(size, resize_to)(torch.Size([batch_size, 1, *input_size]), same_on_batch)
@pytest.mark.parametrize(
- 'input_size,size,resize_to',
+ "input_size,size,resize_to",
[((-300, 300), (200, 200), (100, 100)), ((200, 200), torch.tensor([50, 50]), (100, 100))],
)
def test_invalid_param_combinations(self, input_size, size, resize_to, device, dtype):
@@ -610,22 +610,22 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
torch.Size([2, 1, 100, 100])
)
expected = {
- 'src': torch.tensor(
+ "src": torch.tensor(
[[[36, 19], [95, 19], [95, 68], [36, 68]], [[19, 29], [98, 29], [98, 98], [19, 98]]],
device=device,
dtype=dtype,
),
- 'dst': torch.tensor(
+ "dst": torch.tensor(
[[[0, 0], [199, 0], [199, 199], [0, 199]], [[0, 0], [199, 0], [199, 199], [0, 199]]],
device=device,
dtype=dtype,
),
- 'input_size': torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
- 'output_size': torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),
+ "input_size": torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
+ "output_size": torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),
}
assert res.keys() == expected.keys()
- assert_close(res['src'], expected['src'])
- assert_close(res['dst'], expected['dst'])
+ assert_close(res["src"], expected["src"])
+ assert_close(res["dst"], expected["dst"])
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -633,37 +633,37 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
torch.Size([2, 1, 100, 100]), True
)
expected = {
- 'src': torch.tensor(
+ "src": torch.tensor(
[[[36, 46], [95, 46], [95, 95], [36, 95]], [[36, 46], [115, 46], [115, 115], [36, 115]]],
device=device,
dtype=dtype,
),
- 'dst': torch.tensor(
+ "dst": torch.tensor(
[[[0, 0], [199, 0], [199, 199], [0, 199]], [[0, 0], [199, 0], [199, 199], [0, 199]]],
device=device,
dtype=dtype,
),
- 'input_size': torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
- 'output_size': torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),
+ "input_size": torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
+ "output_size": torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),
}
assert res.keys() == expected.keys()
- assert_close(res['src'], expected['src'])
- assert_close(res['dst'], expected['dst'])
+ assert_close(res["src"], expected["src"])
+ assert_close(res["dst"], expected["dst"])
class TestRandomCropSizeGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('size', [(200, 200)])
- @pytest.mark.parametrize('scale', [torch.tensor([0.7, 1.3])])
- @pytest.mark.parametrize('ratio', [torch.tensor([0.9, 1.1])])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("size", [(200, 200)])
+ @pytest.mark.parametrize("scale", [torch.tensor([0.7, 1.3])])
+ @pytest.mark.parametrize("ratio", [torch.tensor([0.9, 1.1])])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(self, batch_size, size, scale, ratio, same_on_batch, device, dtype):
ResizedCropGenerator(
size, torch.as_tensor(scale, device=device, dtype=dtype), torch.as_tensor(ratio, device=device, dtype=dtype)
)(torch.Size([batch_size, 1, 300, 300]), same_on_batch)
@pytest.mark.parametrize(
- 'size,scale,ratio',
+ "size,scale,ratio",
[
((100), torch.tensor([0.7, 1.3]), torch.tensor([0.9, 1.1])),
((100, 100, 100), torch.tensor([0.7, 1.3]), torch.tensor([0.9, 1.1])),
@@ -690,7 +690,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
torch.tensor([0.9, 1.1], device=device, dtype=dtype),
)(torch.Size([2, 1, 300, 300]))
expected = {
- 'src': torch.tensor(
+ "src": torch.tensor(
[
[[3.0, 12.0], [298.0, 12.0], [298.0, 294.0], [3.0, 294.0]],
[[8.0, 20.0], [284.0, 20.0], [284.0, 298.0], [8.0, 298.0]],
@@ -698,7 +698,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
device=device,
dtype=dtype,
),
- 'dst': torch.tensor(
+ "dst": torch.tensor(
[
[[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]],
[[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]],
@@ -706,13 +706,13 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
device=device,
dtype=dtype,
),
- 'input_size': torch.tensor([[300, 300], [300, 300]], device=device, dtype=torch.int64),
- 'output_size': torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
+ "input_size": torch.tensor([[300, 300], [300, 300]], device=device, dtype=torch.int64),
+ "output_size": torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
}
assert res.keys() == expected.keys()
- assert_close(res['src'], expected['src'])
- assert_close(res['dst'], expected['dst'])
- assert_close(res['input_size'], expected['input_size'])
+ assert_close(res["src"], expected["src"])
+ assert_close(res["dst"], expected["dst"])
+ assert_close(res["input_size"], expected["input_size"])
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -722,7 +722,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
torch.tensor([0.9, 1.1], device=device, dtype=dtype),
)(torch.Size([2, 1, 300, 300]), same_on_batch=True)
expected = {
- 'src': torch.tensor(
+ "src": torch.tensor(
[
[[5.0, 0.0], [283.0, 0.0], [283.0, 298.0], [5.0, 298.0]],
[[5.0, 0.0], [283.0, 0.0], [283.0, 298.0], [5.0, 298.0]],
@@ -730,7 +730,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
device=device,
dtype=dtype,
),
- 'dst': torch.tensor(
+ "dst": torch.tensor(
[
[[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]],
[[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]],
@@ -738,23 +738,23 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
device=device,
dtype=dtype,
),
- 'input_size': torch.tensor([[300, 300], [300, 300]], device=device, dtype=torch.int64),
- 'output_size': torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
+ "input_size": torch.tensor([[300, 300], [300, 300]], device=device, dtype=torch.int64),
+ "output_size": torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
}
assert res.keys() == expected.keys()
- assert_close(res['src'], expected['src'])
- assert_close(res['dst'], expected['dst'])
- assert_close(res['input_size'], expected['input_size'])
+ assert_close(res["src"], expected["src"])
+ assert_close(res["dst"], expected["dst"])
+ assert_close(res["input_size"], expected["input_size"])
class TestRandomRectangleGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('height', [200])
- @pytest.mark.parametrize('width', [300])
- @pytest.mark.parametrize('scale', [torch.tensor([0.7, 1.1])])
- @pytest.mark.parametrize('ratio', [torch.tensor([0.7, 1.1])])
- @pytest.mark.parametrize('value', [0])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("height", [200])
+ @pytest.mark.parametrize("width", [300])
+ @pytest.mark.parametrize("scale", [torch.tensor([0.7, 1.1])])
+ @pytest.mark.parametrize("ratio", [torch.tensor([0.7, 1.1])])
+ @pytest.mark.parametrize("value", [0])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(
self, batch_size, height, width, scale, ratio, value, same_on_batch, device, dtype
):
@@ -763,7 +763,7 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
)(torch.Size([batch_size, 1, height, width]), same_on_batch)
@pytest.mark.parametrize(
- 'height,width,scale,ratio,value',
+ "height,width,scale,ratio,value",
[
(-100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 0),
(100, -100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 0),
@@ -793,18 +793,18 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
scale=scale.to(device=device, dtype=dtype), ratio=ratio.to(device=device, dtype=dtype), value=value
)(torch.Size([2, 1, height, width]))
expected = {
- 'widths': torch.tensor([100, 100], device=device, dtype=dtype),
- 'heights': torch.tensor([0, 0], device=device, dtype=dtype),
- 'xs': torch.tensor([0, 0], device=device, dtype=dtype),
- 'ys': torch.tensor([6, 8], device=device, dtype=dtype),
- 'values': torch.tensor([0.5000, 0.5000], device=device, dtype=dtype),
+ "widths": torch.tensor([100, 100], device=device, dtype=dtype),
+ "heights": torch.tensor([0, 0], device=device, dtype=dtype),
+ "xs": torch.tensor([0, 0], device=device, dtype=dtype),
+ "ys": torch.tensor([6, 8], device=device, dtype=dtype),
+ "values": torch.tensor([0.5000, 0.5000], device=device, dtype=dtype),
}
assert res.keys() == expected.keys()
- assert_close(res['widths'], expected['widths'])
- assert_close(res['widths'], expected['widths'])
- assert_close(res['xs'], expected['xs'])
- assert_close(res['ys'], expected['ys'])
- assert_close(res['values'], expected['values'])
+ assert_close(res["widths"], expected["widths"])
+ assert_close(res["widths"], expected["widths"])
+ assert_close(res["xs"], expected["xs"])
+ assert_close(res["ys"], expected["ys"])
+ assert_close(res["values"], expected["values"])
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -816,30 +816,30 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
scale=scale.to(device=device, dtype=dtype), ratio=ratio.to(device=device, dtype=dtype), value=value
)(torch.Size([2, 1, height, width]), True)
expected = {
- 'widths': torch.tensor([100, 100], device=device, dtype=dtype),
- 'heights': torch.tensor([0, 0], device=device, dtype=dtype),
- 'xs': torch.tensor([0, 0], device=device, dtype=dtype),
- 'ys': torch.tensor([10, 10], device=device, dtype=dtype),
- 'values': torch.tensor([0.5000, 0.5000], device=device, dtype=dtype),
+ "widths": torch.tensor([100, 100], device=device, dtype=dtype),
+ "heights": torch.tensor([0, 0], device=device, dtype=dtype),
+ "xs": torch.tensor([0, 0], device=device, dtype=dtype),
+ "ys": torch.tensor([10, 10], device=device, dtype=dtype),
+ "values": torch.tensor([0.5000, 0.5000], device=device, dtype=dtype),
}
assert res.keys() == expected.keys()
- assert_close(res['widths'], expected['widths'])
- assert_close(res['widths'], expected['widths'])
- assert_close(res['xs'], expected['xs'])
- assert_close(res['ys'], expected['ys'])
- assert_close(res['values'], expected['values'])
+ assert_close(res["widths"], expected["widths"])
+ assert_close(res["widths"], expected["widths"])
+ assert_close(res["xs"], expected["xs"])
+ assert_close(res["ys"], expected["ys"])
+ assert_close(res["values"], expected["values"])
class TestCenterCropGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 2])
- @pytest.mark.parametrize('height', [200])
- @pytest.mark.parametrize('width', [200])
- @pytest.mark.parametrize('size', [(100, 100)])
+ @pytest.mark.parametrize("batch_size", [0, 2])
+ @pytest.mark.parametrize("height", [200])
+ @pytest.mark.parametrize("width", [200])
+ @pytest.mark.parametrize("size", [(100, 100)])
def test_valid_param_combinations(self, batch_size, height, width, size, device, dtype):
center_crop_generator(batch_size=batch_size, height=height, width=width, size=size)
@pytest.mark.parametrize(
- 'height,width,size',
+ "height,width,size",
[
(200, -200, (100, 100)),
(-200, 200, (100, 100)),
@@ -857,33 +857,33 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
torch.manual_seed(42)
res = center_crop_generator(batch_size=2, height=200, width=200, size=(120, 150))
expected = {
- 'src': torch.tensor(
+ "src": torch.tensor(
[[[25, 40], [174, 40], [174, 159], [25, 159]], [[25, 40], [174, 40], [174, 159], [25, 159]]],
device=device,
dtype=torch.long,
),
- 'dst': torch.tensor(
+ "dst": torch.tensor(
[[[0, 0], [149, 0], [149, 119], [0, 119]], [[0, 0], [149, 0], [149, 119], [0, 119]]],
device=device,
dtype=torch.long,
),
- 'input_size': torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),
- 'output_size': torch.tensor([[120, 150], [120, 150]], device=device, dtype=torch.long),
+ "input_size": torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),
+ "output_size": torch.tensor([[120, 150], [120, 150]], device=device, dtype=torch.long),
}
assert res.keys() == expected.keys()
- assert_close(res['src'].to(device=device), expected['src'])
- assert_close(res['dst'].to(device=device), expected['dst'])
+ assert_close(res["src"].to(device=device), expected["src"])
+ assert_close(res["dst"].to(device=device), expected["dst"])
def test_same_on_batch(self, device, dtype):
pass
class TestRandomMotionBlur(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('kernel_size', [3, (3, 5)])
- @pytest.mark.parametrize('angle', [torch.tensor([10, 30])])
- @pytest.mark.parametrize('direction', [torch.tensor([-1, -1]), torch.tensor([1, 1])])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("kernel_size", [3, (3, 5)])
+ @pytest.mark.parametrize("angle", [torch.tensor([10, 30])])
+ @pytest.mark.parametrize("direction", [torch.tensor([-1, -1]), torch.tensor([1, 1])])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(self, batch_size, kernel_size, angle, direction, same_on_batch, device, dtype):
MotionBlurGenerator(
kernel_size=kernel_size,
@@ -892,7 +892,7 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
)(torch.Size([batch_size]), same_on_batch)
@pytest.mark.parametrize(
- 'kernel_size,angle,direction',
+ "kernel_size,angle,direction",
[
(4, torch.tensor([30, 100]), torch.tensor([-1, 1])),
(1, torch.tensor([30, 100]), torch.tensor([-1, 1])),
@@ -919,14 +919,14 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
direction=direction.to(device=device, dtype=dtype),
)(torch.Size([2]))
expected = {
- 'ksize_factor': torch.tensor([3, 3], device=device, dtype=torch.int32),
- 'angle_factor': torch.tensor([82.9362, 84.9002], device=device, dtype=dtype),
- 'direction_factor': torch.tensor([-0.2343, 0.9186], device=device, dtype=dtype),
+ "ksize_factor": torch.tensor([3, 3], device=device, dtype=torch.int32),
+ "angle_factor": torch.tensor([82.9362, 84.9002], device=device, dtype=dtype),
+ "direction_factor": torch.tensor([-0.2343, 0.9186], device=device, dtype=dtype),
}
assert res.keys() == expected.keys()
- assert_close(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)
- assert_close(res['angle_factor'], expected['angle_factor'], rtol=1e-4, atol=1e-4)
- assert_close(res['direction_factor'], expected['direction_factor'], rtol=1e-4, atol=1e-4)
+ assert_close(res["ksize_factor"], expected["ksize_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(res["angle_factor"], expected["angle_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(res["direction_factor"], expected["direction_factor"], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -938,24 +938,24 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
direction=direction.to(device=device, dtype=dtype),
)(torch.Size([2]), True)
expected = {
- 'ksize_factor': torch.tensor([3, 3], device=device, dtype=torch.int32),
- 'angle_factor': torch.tensor([82.9362, 82.9362], device=device, dtype=dtype),
- 'direction_factor': torch.tensor([0.8300, 0.8300], device=device, dtype=dtype),
+ "ksize_factor": torch.tensor([3, 3], device=device, dtype=torch.int32),
+ "angle_factor": torch.tensor([82.9362, 82.9362], device=device, dtype=dtype),
+ "direction_factor": torch.tensor([0.8300, 0.8300], device=device, dtype=dtype),
}
assert res.keys() == expected.keys()
- assert_close(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)
- assert_close(res['angle_factor'], expected['angle_factor'], rtol=1e-4, atol=1e-4)
- assert_close(res['direction_factor'], expected['direction_factor'], rtol=1e-4, atol=1e-4)
+ assert_close(res["ksize_factor"], expected["ksize_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(res["angle_factor"], expected["angle_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(res["direction_factor"], expected["direction_factor"], rtol=1e-4, atol=1e-4)
class TestRandomPosterizeGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('bits', [torch.tensor([0, 8])])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("bits", [torch.tensor([0, 8])])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(self, batch_size, bits, same_on_batch, device, dtype):
PosterizeGenerator(bits)(torch.Size([batch_size]), same_on_batch)
- @pytest.mark.parametrize('bits', [(torch.tensor([-1, 1])), (torch.tensor([0, 9])), (torch.tensor([3])), ([0, 8],)])
+ @pytest.mark.parametrize("bits", [(torch.tensor([-1, 1])), (torch.tensor([0, 9])), (torch.tensor([3])), ([0, 8],)])
def test_invalid_param_combinations(self, bits, device, dtype):
with pytest.raises(Exception):
if isinstance(bits, Tensor):
@@ -967,9 +967,9 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
torch.manual_seed(9)
batch_size = 8
res = PosterizeGenerator(bits=torch.tensor([0, 8], device=device, dtype=dtype))(torch.Size([batch_size]))
- expected = {'bits_factor': torch.tensor([5, 2, 4, 6, 7, 7, 2, 8], device=device, dtype=torch.int32)}
+ expected = {"bits_factor": torch.tensor([5, 2, 4, 6, 7, 7, 2, 8], device=device, dtype=torch.int32)}
assert res.keys() == expected.keys()
- assert_close(res['bits_factor'], expected['bits_factor'], rtol=1e-4, atol=1e-4)
+ assert_close(res["bits_factor"], expected["bits_factor"], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(9)
@@ -977,22 +977,22 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
res = PosterizeGenerator(bits=torch.tensor([0, 8], device=device, dtype=dtype))(
torch.Size([batch_size]), same_on_batch=True
)
- expected = {'bits_factor': torch.tensor([5, 5, 5, 5, 5, 5, 5, 5], device=device, dtype=torch.int32)}
+ expected = {"bits_factor": torch.tensor([5, 5, 5, 5, 5, 5, 5, 5], device=device, dtype=torch.int32)}
assert res.keys() == expected.keys()
- assert_close(res['bits_factor'], expected['bits_factor'], rtol=1e-4, atol=1e-4)
+ assert_close(res["bits_factor"], expected["bits_factor"], rtol=1e-4, atol=1e-4)
class TestPlainUniformGenerator(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('sharpness', [torch.tensor([0.0, 1.0])])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("sharpness", [torch.tensor([0.0, 1.0])])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(self, batch_size, sharpness, same_on_batch, device, dtype):
PlainUniformGenerator(
(sharpness.to(device=device, dtype=dtype), "sharpness", None, None),
(sharpness.to(device=device, dtype=dtype), "sharpness_xx", 0.0, (0.0, 1.0)),
)(torch.Size([batch_size, 1]), same_on_batch)
- @pytest.mark.parametrize('sharpness', [(torch.tensor([-1, 5])), (torch.tensor([3])), ([0, 1.0])])
+ @pytest.mark.parametrize("sharpness", [(torch.tensor([-1, 5])), (torch.tensor([3])), ([0, 1.0])])
def test_invalid_param_combinations(self, sharpness, device, dtype):
with pytest.raises(Exception):
PlainUniformGenerator(
@@ -1007,12 +1007,12 @@ class TestPlainUniformGenerator(RandomGeneratorBaseTests):
(torch.tensor([0.0, 1.0], device=device, dtype=dtype), "sharpness_factor", None, None)
)(torch.Size([batch_size, 1]))
expected = {
- 'sharpness_factor': torch.tensor(
+ "sharpness_factor": torch.tensor(
[0.8823, 0.9150, 0.3829, 0.9593, 0.3904, 0.6009, 0.2566, 0.7936], device=device, dtype=dtype
)
}
assert res.keys() == expected.keys()
- assert_close(res['sharpness_factor'], expected['sharpness_factor'], rtol=1e-4, atol=1e-4)
+ assert_close(res["sharpness_factor"], expected["sharpness_factor"], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -1021,19 +1021,19 @@ class TestPlainUniformGenerator(RandomGeneratorBaseTests):
(torch.tensor([0.0, 1.0], device=device, dtype=dtype), "sharpness_factor", None, None)
)(torch.Size([batch_size, 1]), True)
expected = {
- 'sharpness_factor': torch.tensor(
+ "sharpness_factor": torch.tensor(
[0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823], device=device, dtype=dtype
)
}
assert res.keys() == expected.keys()
- assert_close(res['sharpness_factor'], expected['sharpness_factor'], rtol=1e-4, atol=1e-4)
+ assert_close(res["sharpness_factor"], expected["sharpness_factor"], rtol=1e-4, atol=1e-4)
class TestRandomMixUpGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('p', [0.0, 0.5, 1.0])
- @pytest.mark.parametrize('lambda_val', [None, torch.tensor([0.0, 1.0])])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("p", [0.0, 0.5, 1.0])
+ @pytest.mark.parametrize("lambda_val", [None, torch.tensor([0.0, 1.0])])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(self, batch_size, p, lambda_val, same_on_batch, device, dtype):
MixupGenerator(
p=p,
@@ -1041,7 +1041,7 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
)(torch.Size([batch_size, 3, 200, 200]), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
- 'lambda_val', [(torch.tensor([-1, 1])), (torch.tensor([0, 2])), (torch.tensor([0, 0.5, 1])), ([0.0, 1.0])]
+ "lambda_val", [(torch.tensor([-1, 1])), (torch.tensor([0, 2])), (torch.tensor([0, 0.5, 1])), ([0.0, 1.0])]
)
def test_invalid_param_combinations(self, lambda_val, device, dtype):
with pytest.raises(Exception):
@@ -1056,14 +1056,14 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
torch.Size([batch_size, 3, 200, 200]), same_on_batch=False
)
expected = {
- 'mixup_pairs': torch.tensor([6, 1, 0, 7, 2, 5, 3, 4], device=device, dtype=torch.long),
- 'mixup_lambdas': torch.tensor(
+ "mixup_pairs": torch.tensor([6, 1, 0, 7, 2, 5, 3, 4], device=device, dtype=torch.long),
+ "mixup_lambdas": torch.tensor(
[0.0000, 0.0000, 0.5739, 0.0000, 0.6274, 0.0000, 0.4414, 0.0000], device=device, dtype=dtype
),
}
assert res.keys() == expected.keys()
- assert_close(res['mixup_pairs'], expected['mixup_pairs'], rtol=1e-4, atol=1e-4)
- assert_close(res['mixup_lambdas'], expected['mixup_lambdas'], rtol=1e-4, atol=1e-4)
+ assert_close(res["mixup_pairs"], expected["mixup_pairs"], rtol=1e-4, atol=1e-4)
+ assert_close(res["mixup_lambdas"], expected["mixup_lambdas"], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(9)
@@ -1072,24 +1072,24 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
torch.Size([batch_size, 3, 200, 200]), same_on_batch=True
)
expected = {
- 'mixup_pairs': torch.tensor([4, 6, 7, 5, 0, 1, 3, 2], device=device, dtype=torch.long),
- 'mixup_lambdas': torch.tensor(
+ "mixup_pairs": torch.tensor([4, 6, 7, 5, 0, 1, 3, 2], device=device, dtype=torch.long),
+ "mixup_lambdas": torch.tensor(
[0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804], device=device, dtype=dtype
),
}
assert res.keys() == expected.keys()
- assert_close(res['mixup_pairs'], expected['mixup_pairs'], rtol=1e-4, atol=1e-4)
- assert_close(res['mixup_lambdas'], expected['mixup_lambdas'], rtol=1e-4, atol=1e-4)
+ assert_close(res["mixup_pairs"], expected["mixup_pairs"], rtol=1e-4, atol=1e-4)
+ assert_close(res["mixup_lambdas"], expected["mixup_lambdas"], rtol=1e-4, atol=1e-4)
class TestRandomCutMixGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('p', [0, 0.5, 1.0])
- @pytest.mark.parametrize('width,height', [(200, 200)])
- @pytest.mark.parametrize('num_mix', [1, 3])
- @pytest.mark.parametrize('beta', [None, torch.tensor(1e-15), torch.tensor(1.0)])
- @pytest.mark.parametrize('cut_size', [None, torch.tensor([0.0, 1.0]), torch.tensor([0.3, 0.6])])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("p", [0, 0.5, 1.0])
+ @pytest.mark.parametrize("width,height", [(200, 200)])
+ @pytest.mark.parametrize("num_mix", [1, 3])
+ @pytest.mark.parametrize("beta", [None, torch.tensor(1e-15), torch.tensor(1.0)])
+ @pytest.mark.parametrize("cut_size", [None, torch.tensor([0.0, 1.0]), torch.tensor([0.3, 0.6])])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(
self, batch_size, p, width, height, num_mix, beta, cut_size, same_on_batch, device, dtype
):
@@ -1101,7 +1101,7 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
)(torch.Size([batch_size, 3, height, width]), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
- 'width,height,num_mix,beta,cut_size',
+ "width,height,num_mix,beta,cut_size",
[
(200, -200, 1, None, None),
(-200, 200, 1, None, None),
@@ -1112,7 +1112,7 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
(200, 200, 1, None, torch.tensor([0.0, 2.0])),
],
)
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_invalid_param_combinations(self, width, height, num_mix, beta, cut_size, same_on_batch, device, dtype):
with pytest.raises(Exception):
CutmixGenerator(
@@ -1133,8 +1133,8 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
)(image_shape, same_on_batch=False)
expected = {
- 'mix_pairs': torch.tensor([[1, 7, 5, 3, 6, 4, 2, 0]], device=device, dtype=torch.long),
- 'crop_src': torch.tensor(
+ "mix_pairs": torch.tensor([[1, 7, 5, 3, 6, 4, 2, 0]], device=device, dtype=torch.long),
+ "crop_src": torch.tensor(
[
[
[[48.0, 31.0], [47.0, 31.0], [47.0, 30.0], [48.0, 30.0]],
@@ -1150,11 +1150,11 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
device=device,
dtype=dtype,
),
- 'image_shape': image_shape,
+ "image_shape": image_shape,
}
assert res.keys() == expected.keys(), res.keys()
- assert_close(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)
- assert_close(res['crop_src'], expected['crop_src'], rtol=1e-4, atol=1e-4)
+ assert_close(res["mix_pairs"], expected["mix_pairs"], rtol=1e-4, atol=1e-4)
+ assert_close(res["crop_src"], expected["crop_src"], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -1166,14 +1166,14 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
cut_size=torch.tensor([0.0, 1.0], device=device, dtype=dtype),
)(image_shape, same_on_batch=True)
expected = {
- 'mix_pairs': torch.tensor([[1, 0]], device=device, dtype=torch.long),
- 'crop_src': torch.tensor(
+ "mix_pairs": torch.tensor([[1, 0]], device=device, dtype=torch.long),
+ "crop_src": torch.tensor(
[[[[114, 53], [113, 53], [113, 52], [114, 52]], [[114, 53], [113, 53], [113, 52], [114, 52]]]],
device=device,
dtype=dtype,
),
- 'image_shape': image_shape,
+ "image_shape": image_shape,
}
assert res.keys() == expected.keys(), res.keys()
- assert_close(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)
- assert_close(res['crop_src'], expected['crop_src'], rtol=1e-4, atol=1e-4)
+ assert_close(res["mix_pairs"], expected["mix_pairs"], rtol=1e-4, atol=1e-4)
+ assert_close(res["crop_src"], expected["crop_src"], rtol=1e-4, atol=1e-4)
diff --git a/test/augmentation/test_random_generator_3d.py b/test/augmentation/test_random_generator_3d.py
index f033a5480..013a5e8c0 100644
--- a/test/augmentation/test_random_generator_3d.py
+++ b/test/augmentation/test_random_generator_3d.py
@@ -27,10 +27,10 @@ class RandomGeneratorBaseTests:
class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('depth,height,width', [(200, 200, 200)])
- @pytest.mark.parametrize('distortion_scale', [torch.tensor(0.0), torch.tensor(0.5), torch.tensor(1.0)])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("depth,height,width", [(200, 200, 200)])
+ @pytest.mark.parametrize("distortion_scale", [torch.tensor(0.0), torch.tensor(0.5), torch.tensor(1.0)])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(
self, depth, height, width, distortion_scale, batch_size, same_on_batch, device, dtype
):
@@ -38,7 +38,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
param_gen(batch_shape=torch.Size((batch_size, depth, height, width)), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
- 'depth,height,width,distortion_scale',
+ "depth,height,width,distortion_scale",
[
# Should be failed if distortion_scale > 1. or distortion_scale < 0.
(100, 100, -100, torch.tensor(-0.5)),
@@ -59,7 +59,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
res = param_gen(batch_shape=torch.Size((batch_size, 200, 200, 200)))
expected = {
- 'start_points': torch.tensor(
+ "start_points": torch.tensor(
[
[
[0.0, 0.0, 0.0],
@@ -85,7 +85,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
device=device,
dtype=dtype,
),
- 'end_points': torch.tensor(
+ "end_points": torch.tensor(
[
[
[44.1135, 45.7502, 19.1432],
@@ -113,8 +113,8 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
),
}
assert res.keys() == expected.keys()
- assert_close(res['start_points'], expected['start_points'], atol=1e-4, rtol=1e-4)
- assert_close(res['end_points'], expected['end_points'], atol=1e-4, rtol=1e-4)
+ assert_close(res["start_points"], expected["start_points"], atol=1e-4, rtol=1e-4)
+ assert_close(res["end_points"], expected["end_points"], atol=1e-4, rtol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -124,7 +124,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
res = param_gen(batch_shape=torch.Size((batch_size, 200, 200, 200)), same_on_batch=True)
expected = {
- 'start_points': torch.tensor(
+ "start_points": torch.tensor(
[
[
[0.0, 0.0, 0.0],
@@ -150,7 +150,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
device=device,
dtype=dtype,
),
- 'end_points': torch.tensor(
+ "end_points": torch.tensor(
[
[
[44.1135, 45.7502, 19.1432],
@@ -178,21 +178,21 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
),
}
assert res.keys() == expected.keys()
- assert_close(res['start_points'], expected['start_points'], atol=1e-4, rtol=1e-4)
- assert_close(res['end_points'], expected['end_points'], atol=1e-4, rtol=1e-4)
+ assert_close(res["start_points"], expected["start_points"], atol=1e-4, rtol=1e-4)
+ assert_close(res["end_points"], expected["end_points"], atol=1e-4, rtol=1e-4)
class TestRandomAffineGen3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_shape', [(0, 200, 300, 400), (1, 200, 300, 400), (8, 200, 300, 400)])
- @pytest.mark.parametrize('degrees', [torch.tensor([(0.0, 30.0), (0.0, 30.0), (0.0, 30.0)])])
- @pytest.mark.parametrize('translate', [None, torch.tensor([0.1, 0.1, 0.1])])
+ @pytest.mark.parametrize("batch_shape", [(0, 200, 300, 400), (1, 200, 300, 400), (8, 200, 300, 400)])
+ @pytest.mark.parametrize("degrees", [torch.tensor([(0.0, 30.0), (0.0, 30.0), (0.0, 30.0)])])
+ @pytest.mark.parametrize("translate", [None, torch.tensor([0.1, 0.1, 0.1])])
@pytest.mark.parametrize(
- 'scale', [None, torch.tensor([[0.7, 1.2], [0.7, 1.2], [0.7, 1.2]]), torch.tensor([0.7, 1.2])]
+ "scale", [None, torch.tensor([[0.7, 1.2], [0.7, 1.2], [0.7, 1.2]]), torch.tensor([0.7, 1.2])]
)
@pytest.mark.parametrize(
- 'shear', [None, torch.tensor([[0.0, 20.0], [0.0, 20.0], [0.0, 20.0], [0.0, 20.0], [0.0, 20.0], [0.0, 20.0]])]
+ "shear", [None, torch.tensor([[0.0, 20.0], [0.0, 20.0], [0.0, 20.0], [0.0, 20.0], [0.0, 20.0], [0.0, 20.0]])]
)
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(
self, batch_shape, degrees, translate, scale, shear, same_on_batch, device, dtype
):
@@ -209,7 +209,7 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
param_gen(batch_shape=torch.Size(batch_shape), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
- 'depth,height,width,degrees,translate,scale,shear',
+ "depth,height,width,degrees,translate,scale,shear",
[
(-100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None),
(100, -100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None),
@@ -249,34 +249,34 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
res = param_gen(batch_shape=torch.Size((2, 200, 200, 200)))
expected = {
- 'translations': torch.tensor(
+ "translations": torch.tensor(
[[14.7762, 9.6438, 15.4177], [2.7086, -2.8238, 2.9562]], device=device, dtype=dtype
),
- 'center': torch.tensor(
+ "center": torch.tensor(
[[99.5000, 99.5000, 99.5000], [99.5000, 99.5000, 99.5000]], device=device, dtype=dtype
),
- 'scale': torch.tensor([[0.8283, 1.1704, 1.1673], [1.0968, 0.7666, 0.9968]], device=device, dtype=dtype),
- 'angles': torch.tensor(
+ "scale": torch.tensor([[0.8283, 1.1704, 1.1673], [1.0968, 0.7666, 0.9968]], device=device, dtype=dtype),
+ "angles": torch.tensor(
[[18.8227, 13.8286, 13.9045], [19.1500, 19.5931, 16.0090]], device=device, dtype=dtype
),
- 'sxy': torch.tensor([5.3316, 12.5490], device=device, dtype=dtype),
- 'sxz': torch.tensor([5.3926, 8.8273], device=device, dtype=dtype),
- 'syx': torch.tensor([5.9384, 16.6337], device=device, dtype=dtype),
- 'syz': torch.tensor([2.1063, 5.3899], device=device, dtype=dtype),
- 'szx': torch.tensor([7.1763, 3.9873], device=device, dtype=dtype),
- 'szy': torch.tensor([10.9438, 0.1232], device=device, dtype=dtype),
+ "sxy": torch.tensor([5.3316, 12.5490], device=device, dtype=dtype),
+ "sxz": torch.tensor([5.3926, 8.8273], device=device, dtype=dtype),
+ "syx": torch.tensor([5.9384, 16.6337], device=device, dtype=dtype),
+ "syz": torch.tensor([2.1063, 5.3899], device=device, dtype=dtype),
+ "szx": torch.tensor([7.1763, 3.9873], device=device, dtype=dtype),
+ "szy": torch.tensor([10.9438, 0.1232], device=device, dtype=dtype),
}
assert res.keys() == expected.keys()
- assert_close(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)
- assert_close(res['center'], expected['center'], rtol=1e-4, atol=1e-4)
- assert_close(res['scale'], expected['scale'], rtol=1e-4, atol=1e-4)
- assert_close(res['angles'], expected['angles'], rtol=1e-4, atol=1e-4)
- assert_close(res['sxy'], expected['sxy'], rtol=1e-4, atol=1e-4)
- assert_close(res['sxz'], expected['sxz'], rtol=1e-4, atol=1e-4)
- assert_close(res['syx'], expected['syx'], rtol=1e-4, atol=1e-4)
- assert_close(res['syz'], expected['syz'], rtol=1e-4, atol=1e-4)
- assert_close(res['szx'], expected['szx'], rtol=1e-4, atol=1e-4)
- assert_close(res['szy'], expected['szy'], rtol=1e-4, atol=1e-4)
+ assert_close(res["translations"], expected["translations"], rtol=1e-4, atol=1e-4)
+ assert_close(res["center"], expected["center"], rtol=1e-4, atol=1e-4)
+ assert_close(res["scale"], expected["scale"], rtol=1e-4, atol=1e-4)
+ assert_close(res["angles"], expected["angles"], rtol=1e-4, atol=1e-4)
+ assert_close(res["sxy"], expected["sxy"], rtol=1e-4, atol=1e-4)
+ assert_close(res["sxz"], expected["sxz"], rtol=1e-4, atol=1e-4)
+ assert_close(res["syx"], expected["syx"], rtol=1e-4, atol=1e-4)
+ assert_close(res["syz"], expected["syz"], rtol=1e-4, atol=1e-4)
+ assert_close(res["szx"], expected["szx"], rtol=1e-4, atol=1e-4)
+ assert_close(res["szy"], expected["szy"], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -289,46 +289,46 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
res = param_gen(batch_shape=torch.Size((2, 200, 200, 200)), same_on_batch=True)
expected = {
- 'translations': torch.tensor(
+ "translations": torch.tensor(
[[-9.7371, 11.7457, 17.6309], [-9.7371, 11.7457, 17.6309]], device=device, dtype=dtype
),
- 'center': torch.tensor(
+ "center": torch.tensor(
[[99.5000, 99.5000, 99.5000], [99.5000, 99.5000, 99.5000]], device=device, dtype=dtype
),
- 'scale': torch.tensor([[1.1797, 0.8952, 1.0004], [1.1797, 0.8952, 1.0004]], device=device, dtype=dtype),
- 'angles': torch.tensor(
+ "scale": torch.tensor([[1.1797, 0.8952, 1.0004], [1.1797, 0.8952, 1.0004]], device=device, dtype=dtype),
+ "angles": torch.tensor(
[[18.8227, 19.1500, 13.8286], [18.8227, 19.1500, 13.8286]], device=device, dtype=dtype
),
- 'sxy': torch.tensor([2.6637, 2.6637], device=device, dtype=dtype),
- 'sxz': torch.tensor([18.6920, 18.6920], device=device, dtype=dtype),
- 'syx': torch.tensor([11.8716, 11.8716], device=device, dtype=dtype),
- 'syz': torch.tensor([17.3881, 17.3881], device=device, dtype=dtype),
- 'szx': torch.tensor([11.3543, 11.3543], device=device, dtype=dtype),
- 'szy': torch.tensor([14.8219, 14.8219], device=device, dtype=dtype),
+ "sxy": torch.tensor([2.6637, 2.6637], device=device, dtype=dtype),
+ "sxz": torch.tensor([18.6920, 18.6920], device=device, dtype=dtype),
+ "syx": torch.tensor([11.8716, 11.8716], device=device, dtype=dtype),
+ "syz": torch.tensor([17.3881, 17.3881], device=device, dtype=dtype),
+ "szx": torch.tensor([11.3543, 11.3543], device=device, dtype=dtype),
+ "szy": torch.tensor([14.8219, 14.8219], device=device, dtype=dtype),
}
assert res.keys() == expected.keys()
- assert_close(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)
- assert_close(res['center'], expected['center'], rtol=1e-4, atol=1e-4)
- assert_close(res['scale'], expected['scale'], rtol=1e-4, atol=1e-4)
- assert_close(res['angles'], expected['angles'], rtol=1e-4, atol=1e-4)
- assert_close(res['sxy'], expected['sxy'], rtol=1e-4, atol=1e-4)
- assert_close(res['sxz'], expected['sxz'], rtol=1e-4, atol=1e-4)
- assert_close(res['syx'], expected['syx'], rtol=1e-4, atol=1e-4)
- assert_close(res['syz'], expected['syz'], rtol=1e-4, atol=1e-4)
- assert_close(res['szx'], expected['szx'], rtol=1e-4, atol=1e-4)
- assert_close(res['szy'], expected['szy'], rtol=1e-4, atol=1e-4)
+ assert_close(res["translations"], expected["translations"], rtol=1e-4, atol=1e-4)
+ assert_close(res["center"], expected["center"], rtol=1e-4, atol=1e-4)
+ assert_close(res["scale"], expected["scale"], rtol=1e-4, atol=1e-4)
+ assert_close(res["angles"], expected["angles"], rtol=1e-4, atol=1e-4)
+ assert_close(res["sxy"], expected["sxy"], rtol=1e-4, atol=1e-4)
+ assert_close(res["sxz"], expected["sxz"], rtol=1e-4, atol=1e-4)
+ assert_close(res["syx"], expected["syx"], rtol=1e-4, atol=1e-4)
+ assert_close(res["syz"], expected["syz"], rtol=1e-4, atol=1e-4)
+ assert_close(res["szx"], expected["szx"], rtol=1e-4, atol=1e-4)
+ assert_close(res["szy"], expected["szy"], rtol=1e-4, atol=1e-4)
class TestRandomRotationGen3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(self, batch_size, same_on_batch, device, dtype):
degrees = torch.tensor([[0.0, 30.0], [0.0, 30.0], [0.0, 30.0]], device=device, dtype=dtype)
param_gen = RotationGenerator3D(degrees=degrees.to(device=device, dtype=dtype))
param_gen(torch.Size((batch_size,)), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
- 'degrees',
+ "degrees",
[(torch.tensor(-10)), (torch.tensor([-10])), (torch.tensor([[0, 30]])), (torch.tensor([[0, 30], [0, 30]]))],
)
def test_invalid_param_combinations(self, degrees, device, dtype):
@@ -343,14 +343,14 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
res = param_gen(torch.Size((2,)), same_on_batch=False)
expected = {
- 'yaw': torch.tensor([26.4681, 27.4501], device=device, dtype=dtype),
- 'pitch': torch.tensor([11.4859, 28.7792], device=device, dtype=dtype),
- 'roll': torch.tensor([11.7134, 18.0269], device=device, dtype=dtype),
+ "yaw": torch.tensor([26.4681, 27.4501], device=device, dtype=dtype),
+ "pitch": torch.tensor([11.4859, 28.7792], device=device, dtype=dtype),
+ "roll": torch.tensor([11.7134, 18.0269], device=device, dtype=dtype),
}
assert res.keys() == expected.keys()
- assert_close(res['yaw'], expected['yaw'], atol=1e-4, rtol=1e-4)
- assert_close(res['pitch'], expected['pitch'], atol=1e-4, rtol=1e-4)
- assert_close(res['roll'], expected['roll'], atol=1e-4, rtol=1e-4)
+ assert_close(res["yaw"], expected["yaw"], atol=1e-4, rtol=1e-4)
+ assert_close(res["pitch"], expected["pitch"], atol=1e-4, rtol=1e-4)
+ assert_close(res["roll"], expected["roll"], atol=1e-4, rtol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -359,22 +359,22 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
res = param_gen(torch.Size((2,)), same_on_batch=True)
expected = {
- 'yaw': torch.tensor([26.4681, 26.4681], device=device, dtype=dtype),
- 'pitch': torch.tensor([27.4501, 27.4501], device=device, dtype=dtype),
- 'roll': torch.tensor([11.4859, 11.4859], device=device, dtype=dtype),
+ "yaw": torch.tensor([26.4681, 26.4681], device=device, dtype=dtype),
+ "pitch": torch.tensor([27.4501, 27.4501], device=device, dtype=dtype),
+ "roll": torch.tensor([11.4859, 11.4859], device=device, dtype=dtype),
}
assert res.keys() == expected.keys()
- assert_close(res['yaw'], expected['yaw'], atol=1e-4, rtol=1e-4)
- assert_close(res['pitch'], expected['pitch'], atol=1e-4, rtol=1e-4)
- assert_close(res['roll'], expected['roll'], atol=1e-4, rtol=1e-4)
+ assert_close(res["yaw"], expected["yaw"], atol=1e-4, rtol=1e-4)
+ assert_close(res["pitch"], expected["pitch"], atol=1e-4, rtol=1e-4)
+ assert_close(res["roll"], expected["roll"], atol=1e-4, rtol=1e-4)
class TestRandomCropGen3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 2])
- @pytest.mark.parametrize('input_size', [(200, 200, 200)])
- @pytest.mark.parametrize('size', [(100, 100, 100), torch.tensor([50, 60, 70])])
- @pytest.mark.parametrize('resize_to', [None, (100, 100, 100)])
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("batch_size", [0, 2])
+ @pytest.mark.parametrize("input_size", [(200, 200, 200)])
+ @pytest.mark.parametrize("size", [(100, 100, 100), torch.tensor([50, 60, 70])])
+ @pytest.mark.parametrize("resize_to", [None, (100, 100, 100)])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(self, batch_size, input_size, size, resize_to, same_on_batch, device, dtype):
if isinstance(size, torch.Tensor):
size = size.repeat(batch_size, 1).to(device=device, dtype=dtype)
@@ -383,7 +383,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
param_gen(batch_shape=torch.Size((batch_size, 1, *input_size)), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
- 'input_size,size,resize_to',
+ "input_size,size,resize_to",
[
((-300, 300, 300), (200, 200, 200), (100, 100, 100)),
((100, 100, 100), (200, 200, 200), (100, 100, 100)),
@@ -407,7 +407,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
res = param_gen(batch_shape=torch.Size((2, 1, 200, 200, 200)))
expected = {
- 'src': torch.tensor(
+ "src": torch.tensor(
[
[
[115, 53, 58],
@@ -433,7 +433,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
device=device,
dtype=dtype,
),
- 'dst': torch.tensor(
+ "dst": torch.tensor(
[
[
[0, 0, 0],
@@ -461,8 +461,8 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
),
}
assert res.keys() == expected.keys()
- assert_close(res['src'], expected['src'], atol=1e-4, rtol=1e-4)
- assert_close(res['dst'], expected['dst'], atol=1e-4, rtol=1e-4)
+ assert_close(res["src"], expected["src"], atol=1e-4, rtol=1e-4)
+ assert_close(res["dst"], expected["dst"], atol=1e-4, rtol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -473,7 +473,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
res = param_gen(batch_shape=torch.Size((2, 1, 200, 200, 200)), same_on_batch=True)
expected = {
- 'src': torch.tensor(
+ "src": torch.tensor(
[
[
[115, 129, 57],
@@ -499,7 +499,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
device=device,
dtype=dtype,
),
- 'dst': torch.tensor(
+ "dst": torch.tensor(
[
[
[0, 0, 0],
@@ -527,19 +527,19 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
),
}
assert res.keys() == expected.keys()
- assert_close(res['src'], expected['src'], atol=1e-4, rtol=1e-4)
- assert_close(res['dst'], expected['dst'], atol=1e-4, rtol=1e-4)
+ assert_close(res["src"], expected["src"], atol=1e-4, rtol=1e-4)
+ assert_close(res["dst"], expected["dst"], atol=1e-4, rtol=1e-4)
class TestCenterCropGen3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 2])
- @pytest.mark.parametrize('depth,height,width', [(200, 200, 200)])
- @pytest.mark.parametrize('size', [(100, 100, 100)])
+ @pytest.mark.parametrize("batch_size", [0, 2])
+ @pytest.mark.parametrize("depth,height,width", [(200, 200, 200)])
+ @pytest.mark.parametrize("size", [(100, 100, 100)])
def test_valid_param_combinations(self, batch_size, depth, height, width, size, device, dtype):
center_crop_generator3d(batch_size=batch_size, depth=depth, height=height, width=width, size=size)
@pytest.mark.parametrize(
- 'depth,height,width,size',
+ "depth,height,width,size",
[
(200, 200, -200, (100, 100, 100)),
(200, -200, 200, (100, 100)),
@@ -556,7 +556,7 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):
torch.manual_seed(42)
res = center_crop_generator3d(batch_size=2, depth=200, height=200, width=200, size=(120, 150, 100))
expected = {
- 'src': torch.tensor(
+ "src": torch.tensor(
[
[
[50, 25, 40],
@@ -572,7 +572,7 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):
device=device,
dtype=torch.long,
).repeat(2, 1, 1),
- 'dst': torch.tensor(
+ "dst": torch.tensor(
[
[
[0, 0, 0],
@@ -590,21 +590,21 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):
).repeat(2, 1, 1),
}
assert res.keys() == expected.keys()
- assert_close(res['src'].to(device=device), expected['src'], atol=1e-4, rtol=1e-4)
- assert_close(res['dst'].to(device=device), expected['dst'], atol=1e-4, rtol=1e-4)
+ assert_close(res["src"].to(device=device), expected["src"], atol=1e-4, rtol=1e-4)
+ assert_close(res["dst"].to(device=device), expected["dst"], atol=1e-4, rtol=1e-4)
def test_same_on_batch(self, device, dtype):
pass
class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('kernel_size', [3, (3, 5)])
- @pytest.mark.parametrize('angle', [torch.tensor([(10.0, 30.0), (30.0, 60.0), (60.0, 90.0)])])
+ @pytest.mark.parametrize("batch_size", [0, 1, 8])
+ @pytest.mark.parametrize("kernel_size", [3, (3, 5)])
+ @pytest.mark.parametrize("angle", [torch.tensor([(10.0, 30.0), (30.0, 60.0), (60.0, 90.0)])])
@pytest.mark.parametrize(
- 'direction', [torch.tensor([-1.0, -1.0]), torch.tensor([-1.0, 1.0]), torch.tensor([1.0, 1.0])]
+ "direction", [torch.tensor([-1.0, -1.0]), torch.tensor([-1.0, 1.0]), torch.tensor([1.0, 1.0])]
)
- @pytest.mark.parametrize('same_on_batch', [True, False])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(self, batch_size, kernel_size, angle, direction, same_on_batch, device, dtype):
param_gen = MotionBlurGenerator3D(
kernel_size=kernel_size,
@@ -615,7 +615,7 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
param_gen(batch_shape=torch.Size((batch_size,)), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
- 'kernel_size,angle,direction',
+ "kernel_size,angle,direction",
[
(4, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1])),
(1, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1])),
@@ -643,16 +643,16 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
res = param_gen(batch_shape=torch.Size((2,)), same_on_batch=False)
expected = {
- 'ksize_factor': torch.tensor([3, 3], device=device, dtype=torch.int32),
- 'angle_factor': torch.tensor(
+ "ksize_factor": torch.tensor([3, 3], device=device, dtype=torch.int32),
+ "angle_factor": torch.tensor(
[[27.6454, 41.4859, 71.7134], [28.3001, 58.7792, 78.0269]], device=device, dtype=dtype
),
- 'direction_factor': torch.tensor([-0.4869, 0.5873], device=device, dtype=dtype),
+ "direction_factor": torch.tensor([-0.4869, 0.5873], device=device, dtype=dtype),
}
assert res.keys() == expected.keys()
- assert_close(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)
- assert_close(res['angle_factor'], expected['angle_factor'], rtol=1e-4, atol=1e-4)
- assert_close(res['direction_factor'], expected['direction_factor'], rtol=1e-4, atol=1e-4)
+ assert_close(res["ksize_factor"], expected["ksize_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(res["angle_factor"], expected["angle_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(res["direction_factor"], expected["direction_factor"], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -663,13 +663,13 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
res = param_gen(batch_shape=torch.Size((2,)), same_on_batch=True)
expected = {
- 'ksize_factor': torch.tensor([3, 3], device=device, dtype=torch.int32),
- 'angle_factor': torch.tensor(
+ "ksize_factor": torch.tensor([3, 3], device=device, dtype=torch.int32),
+ "angle_factor": torch.tensor(
[[27.6454, 57.4501, 71.4859], [27.6454, 57.4501, 71.4859]], device=device, dtype=dtype
),
- 'direction_factor': torch.tensor([0.9186, 0.9186], device=device, dtype=dtype),
+ "direction_factor": torch.tensor([0.9186, 0.9186], device=device, dtype=dtype),
}
assert res.keys() == expected.keys()
- assert_close(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)
- assert_close(res['angle_factor'], expected['angle_factor'], rtol=1e-4, atol=1e-4)
- assert_close(res['direction_factor'], expected['direction_factor'], rtol=1e-4, atol=1e-4)
+ assert_close(res["ksize_factor"], expected["ksize_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(res["angle_factor"], expected["angle_factor"], rtol=1e-4, atol=1e-4)
+ assert_close(res["direction_factor"], expected["direction_factor"], rtol=1e-4, atol=1e-4)
diff --git a/test/benchmark.py b/test/benchmark.py
index 93ad7b36e..3f43ecc69 100644
--- a/test/benchmark.py
+++ b/test/benchmark.py
@@ -10,19 +10,19 @@ sizes = [1, 64, 1024]
for b, n in product(sizes, sizes):
# label and sub_label are the rows
# description is the column
- label = 'get_perspective_transform'
- sub_label = f'[{b}, {4}, {2}]'
+ label = "get_perspective_transform"
+ sub_label = f"[{b}, {4}, {2}]"
x = torch.rand((b, 4, 2))
for num_threads in [1, 4, 16, 32]:
results.append(
benchmark.Timer(
- stmt='get_perspective_transform(x, x)',
- setup='from kornia.geometry import get_perspective_transform',
- globals={'x': x},
+ stmt="get_perspective_transform(x, x)",
+ setup="from kornia.geometry import get_perspective_transform",
+ globals={"x": x},
num_threads=num_threads,
label=label,
sub_label=sub_label,
- description='get_perspective_transform',
+ description="get_perspective_transform",
).blocked_autorange(min_run_time=1)
)
diff --git a/test/color/test_colormap.py b/test/color/test_colormap.py
index 48f227fff..5ec0d1872 100644
--- a/test/color/test_colormap.py
+++ b/test/color/test_colormap.py
@@ -79,7 +79,7 @@ class TestApplyColorMap(BaseTester):
assert actual.shape == expected_shape
- @pytest.mark.skip(reason='jacobian mismatch')
+ @pytest.mark.skip(reason="jacobian mismatch")
def test_gradcheck(self, device, dtype):
# TODO: implement differentiability
cm = AUTUMN(device=device, dtype=dtype)
diff --git a/test/color/test_gray.py b/test/color/test_gray.py
index 775856313..75620ac9f 100644
--- a/test/color/test_gray.py
+++ b/test/color/test_gray.py
@@ -202,7 +202,7 @@ class TestRgbToGrayscale(BaseTester):
assert gradcheck(kornia.color.rgb_to_grayscale, (img,), raise_exception=True, fast_mode=True)
@pytest.mark.slow
- @pytest.mark.skipif(torch_version() in {'2.0.0', '2.0.1'}, reason='Not working on 2.0')
+ @pytest.mark.skipif(torch_version() in {"2.0.0", "2.0.1"}, reason="Not working on 2.0")
def test_dynamo(self, device, dtype, torch_optimizer):
# TODO: investigate the problem with dynamo
B, C, H, W = 2, 3, 4, 4
@@ -296,7 +296,7 @@ class TestBgrToGrayscale(BaseTester):
assert gradcheck(kornia.color.bgr_to_grayscale, (img,), raise_exception=True, fast_mode=True)
@pytest.mark.slow
- @pytest.mark.skipif(torch_version() in {'2.0.0', '2.0.1'}, reason='Not working on 2.0')
+ @pytest.mark.skipif(torch_version() in {"2.0.0", "2.0.1"}, reason="Not working on 2.0")
def test_dynamo(self, device, dtype, torch_optimizer):
# TODO: investigate the problem with dynamo
B, C, H, W = 2, 3, 4, 4
diff --git a/test/color/test_hls.py b/test/color/test_hls.py
index e4b4c0759..550eff5f1 100644
--- a/test/color/test_hls.py
+++ b/test/color/test_hls.py
@@ -95,9 +95,9 @@ class TestRgbToHls(BaseTester):
def test_nan_rgb_to_hls(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
- if device != torch.device('cpu') and version.parse(torch.__version__) < version.parse('1.7.0'):
+ if device != torch.device("cpu") and version.parse(torch.__version__) < version.parse("1.7.0"):
warnings.warn(
"This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
"support pytorch 1.6.0. `torch.max()` have a problem in pytorch < 1.7.0 then we cannot get the correct "
@@ -132,7 +132,7 @@ class TestRgbToHls(BaseTester):
@pytest.mark.jit()
def test_jit(self, device, dtype):
- if version.parse(torch.__version__) < version.parse('1.7.0'):
+ if version.parse(torch.__version__) < version.parse("1.7.0"):
warnings.warn(
"This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
"support pytorch 1.6.0. `rgb_to_hls()` method for pytorch < 1.7.0 version cannot be compiled with JIT.",
@@ -258,7 +258,7 @@ class TestHlsToRgb(BaseTester):
@pytest.mark.jit()
def test_jit(self, device, dtype):
- if version.parse(torch.__version__) < version.parse('1.7.0'):
+ if version.parse(torch.__version__) < version.parse("1.7.0"):
warnings.warn(
"This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
"support pytorch 1.6.0. `hls_to_rgb()` method for pytorch < 1.7.0 version cannot be compiled with JIT.",
diff --git a/test/color/test_hsv.py b/test/color/test_hsv.py
index 7bb6a44c3..58d79e5e1 100644
--- a/test/color/test_hsv.py
+++ b/test/color/test_hsv.py
@@ -93,7 +93,7 @@ class TestRgbToHsv(BaseTester):
def test_nan_rgb_to_hsv(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
data = torch.zeros(3, 5, 5, device=device, dtype=dtype) # 3x5x5
expected = torch.zeros_like(data) # 3x5x5
diff --git a/test/color/test_lab.py b/test/color/test_lab.py
index 7350037e2..bfda90acf 100644
--- a/test/color/test_lab.py
+++ b/test/color/test_lab.py
@@ -31,7 +31,7 @@ class TestRgbToLab(BaseTester):
def test_unit(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
data = torch.tensor(
[
@@ -88,7 +88,7 @@ class TestRgbToLab(BaseTester):
def test_forth_and_back(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
data = torch.rand(3, 4, 5, device=device, dtype=dtype)
lab = kornia.color.rgb_to_lab
@@ -144,7 +144,7 @@ class TestLabToRgb(BaseTester):
def test_unit(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
data = torch.tensor(
[
@@ -233,7 +233,7 @@ class TestLabToRgb(BaseTester):
def test_forth_and_back(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
data = torch.rand(3, 4, 5, device=device, dtype=dtype)
lab = kornia.color.rgb_to_lab
diff --git a/test/color/test_luv.py b/test/color/test_luv.py
index 809a5afd6..e55505222 100644
--- a/test/color/test_luv.py
+++ b/test/color/test_luv.py
@@ -31,7 +31,7 @@ class TestRgbToLuv(BaseTester):
def test_unit(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
data = torch.tensor(
[
@@ -88,7 +88,7 @@ class TestRgbToLuv(BaseTester):
def test_forth_and_back(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
data = torch.rand(3, 4, 5, device=device, dtype=dtype)
luv = kornia.color.rgb_to_luv
@@ -144,7 +144,7 @@ class TestLuvToRgb(BaseTester):
def test_unit(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
data = torch.tensor(
[
[
@@ -205,7 +205,7 @@ class TestLuvToRgb(BaseTester):
def test_forth_and_back(self, device, dtype):
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
data = torch.rand(3, 4, 5, device=device, dtype=dtype)
luv = kornia.color.rgb_to_luv
diff --git a/test/color/test_raw.py b/test/color/test_raw.py
index b63ee3087..b61e3c504 100644
--- a/test/color/test_raw.py
+++ b/test/color/test_raw.py
@@ -125,7 +125,7 @@ class TestRawToRgb(BaseTester):
@pytest.mark.jit()
def test_jit(self, device, dtype):
- if version.parse(torch.__version__) < version.parse('1.7.0'):
+ if version.parse(torch.__version__) < version.parse("1.7.0"):
warnings.warn(
"This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
"support pytorch 1.6.0. `rgb_to_hls()` method for pytorch < 1.7.0 version cannot be compiled with JIT.",
@@ -176,7 +176,7 @@ class TestRgbToRaw(BaseTester):
@pytest.mark.jit()
def test_jit(self, device, dtype):
- if version.parse(torch.__version__) < version.parse('1.7.0'):
+ if version.parse(torch.__version__) < version.parse("1.7.0"):
warnings.warn(
"This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
"support pytorch 1.6.0. `rgb_to_hls()` method for pytorch < 1.7.0 version cannot be compiled with JIT.",
@@ -220,7 +220,7 @@ class TestRawToRgb2x2Downscaled(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(Exception) as errinf:
kornia.color.raw_to_rgb_2x2_downscaled([0.0], kornia.color.CFA.BG)
- assert 'Input type is not a torch.Tensor' in str(errinf)
+ assert "Input type is not a torch.Tensor" in str(errinf)
with pytest.raises(TypeError) as errinf:
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -235,18 +235,18 @@ class TestRawToRgb2x2Downscaled(BaseTester):
with pytest.raises(Exception) as errinf:
img = torch.ones(1, 3, 2, device=device, dtype=dtype)
kornia.color.raw_to_rgb_2x2_downscaled(img, kornia.color.CFA.GR)
- assert 'Input H&W must be evenly disible by 2. Got' in str(errinf)
+ assert "Input H&W must be evenly disible by 2. Got" in str(errinf)
with pytest.raises(Exception) as errinf:
img = torch.ones(1, 2, 3, device=device, dtype=dtype)
kornia.color.raw_to_rgb_2x2_downscaled(img, kornia.color.CFA.GR)
- assert 'Input H&W must be evenly disible by 2. Got' in str(errinf)
+ assert "Input H&W must be evenly disible by 2. Got" in str(errinf)
with pytest.raises(ValueError) as errinf:
img = torch.ones(1, 4, 8, device=device, dtype=dtype)
nonexistent_cfa = 195162495283
kornia.color.raw_to_rgb_2x2_downscaled(img, nonexistent_cfa)
- assert 'Unsupported CFA Got' in str(errinf)
+ assert "Unsupported CFA Got" in str(errinf)
@pytest.mark.parametrize(
"cfa, expected_rgb",
diff --git a/test/color/test_rgb.py b/test/color/test_rgb.py
index 4dfc0d40a..05151b5a3 100644
--- a/test/color/test_rgb.py
+++ b/test/color/test_rgb.py
@@ -119,7 +119,7 @@ class TestRgbToRgba(BaseTester):
with pytest.raises(TypeError):
img = torch.ones(3, 1, 1, device=device, dtype=dtype)
- assert kornia.color.rgb_to_rgba(img, 'alpha_str')
+ assert kornia.color.rgb_to_rgba(img, "alpha_str")
# rgba to rgb
with pytest.raises(TypeError):
diff --git a/test/contrib/models/test_rt_detr.py b/test/contrib/models/test_rt_detr.py
index 54ea6035a..1ea683745 100644
--- a/test/contrib/models/test_rt_detr.py
+++ b/test/contrib/models/test_rt_detr.py
@@ -12,7 +12,7 @@ from kornia.testing import BaseTester, assert_close
@pytest.mark.parametrize(
- 'backbone_factory',
+ "backbone_factory",
(partial(ResNetD.from_config, 18), partial(ResNetD.from_config, 50), partial(PPHGNetV2.from_config, "L")),
)
def test_backbone(backbone_factory, device, dtype):
diff --git a/test/contrib/models/test_sam.py b/test/contrib/models/test_sam.py
index 8a04c0597..adb0e58c4 100644
--- a/test/contrib/models/test_sam.py
+++ b/test/contrib/models/test_sam.py
@@ -15,7 +15,7 @@ def _pad_rb(x, size):
class TestSam(BaseTester):
@pytest.mark.slow
- @pytest.mark.parametrize('model_type', ['vit_b', 'mobile_sam'])
+ @pytest.mark.parametrize("model_type", ["vit_b", "mobile_sam"])
def test_smoke(self, device, model_type):
model = Sam.from_config(SamConfig(model_type)).to(device)
assert isinstance(model, Sam)
@@ -25,43 +25,43 @@ class TestSam(BaseTester):
keypoints = torch.randint(0, img_size, (1, 2, 2), device=device, dtype=torch.float)
labels = torch.randint(0, 1, (1, 2), device=device, dtype=torch.float)
- model(inpt, [{'points': (keypoints, labels)}], False)
+ model(inpt, [{"points": (keypoints, labels)}], False)
@pytest.mark.slow
- @pytest.mark.parametrize('batch_size', [1, 3])
- @pytest.mark.parametrize('N', [2, 5])
- @pytest.mark.parametrize('multimask_output', [True, False])
+ @pytest.mark.parametrize("batch_size", [1, 3])
+ @pytest.mark.parametrize("N", [2, 5])
+ @pytest.mark.parametrize("multimask_output", [True, False])
def test_cardinality(self, device, batch_size, N, multimask_output):
# SAM: don't supports float64
dtype = torch.float32
inpt = torch.rand(1, 3, 77, 128, device=device, dtype=dtype)
- model = Sam.from_config(SamConfig('vit_b'))
+ model = Sam.from_config(SamConfig("vit_b"))
model = model.to(device=device, dtype=dtype)
inpt = _pad_rb(inpt, model.image_encoder.img_size)
keypoints = torch.randint(0, min(inpt.shape[-2:]), (batch_size, N, 2), device=device).to(dtype=dtype)
labels = torch.randint(0, 1, (batch_size, N), device=device).to(dtype=dtype)
- out = model(inpt, [{'points': (keypoints, labels)}], multimask_output)
+ out = model(inpt, [{"points": (keypoints, labels)}], multimask_output)
C = 3 if multimask_output else 1
assert len(out) == inpt.size(0)
assert out[0].logits.shape == (batch_size, C, 256, 256)
def test_exception(self):
- model = Sam.from_config(SamConfig('mobile_sam'))
+ model = Sam.from_config(SamConfig("mobile_sam"))
with pytest.raises(TypeError) as errinfo:
inpt = torch.rand(3, 1, 2)
model(inpt, [], False)
- assert 'shape must be [[\'B\', \'3\', \'H\', \'W\']]. Got torch.Size([3, 1, 2])' in str(errinfo)
+ assert "shape must be [['B', '3', 'H', 'W']]. Got torch.Size([3, 1, 2])" in str(errinfo)
with pytest.raises(Exception) as errinfo:
inpt = torch.rand(2, 3, 1, 2)
model(inpt, [{}], False)
- assert 'The number of images (`B`) should match with the length of prompts!' in str(errinfo)
+ assert "The number of images (`B`) should match with the length of prompts!" in str(errinfo)
@pytest.mark.slow
- @pytest.mark.parametrize('model_type', ['vit_b', 'vit_l', 'vit_h', 'mobile_sam'])
+ @pytest.mark.parametrize("model_type", ["vit_b", "vit_l", "vit_h", "mobile_sam"])
def test_config(self, device, model_type):
model = Sam.from_config(SamConfig(model_type))
model = model.to(device=device)
@@ -69,20 +69,20 @@ class TestSam(BaseTester):
assert isinstance(model, Sam)
assert next(model.parameters()).device == device
- @pytest.mark.skip(reason='Unsupport at moment -- the code is not tested for training and had `torch.no_grad`')
+ @pytest.mark.skip(reason="Unsupported at moment -- the code is not tested for training and had `torch.no_grad`")
def test_gradcheck(self, device):
...
- @pytest.mark.skip(reason='Unecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_module(self):
...
- @pytest.mark.skip(reason='Needs to be reviewed.')
+ @pytest.mark.skip(reason="Needs to be reviewed.")
def test_dynamo(self, device, torch_optimizer):
dtype = torch.float32
img = torch.rand(1, 3, 128, 75, device=device, dtype=dtype)
- op = Sam.from_config(SamConfig('vit_b'))
+ op = Sam.from_config(SamConfig("vit_b"))
op = op.to(device=device, dtype=dtype)
op_optimized = torch_optimizer(op)
diff --git a/test/contrib/models/test_tiny_vit.py b/test/contrib/models/test_tiny_vit.py
index 38dd18f35..59cb6f650 100644
--- a/test/contrib/models/test_tiny_vit.py
+++ b/test/contrib/models/test_tiny_vit.py
@@ -16,8 +16,8 @@ class TestTinyViT(BaseTester):
assert isinstance(out, Tensor)
@pytest.mark.slow
- @pytest.mark.parametrize('num_classes', [10, 100])
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("num_classes", [10, 100])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_cardinality(self, device, dtype, batch_size, num_classes):
model = TinyViT(num_classes=num_classes).to(device=device, dtype=dtype)
inpt = torch.rand(batch_size, 3, model.img_size, model.img_size, device=device, dtype=dtype)
@@ -25,15 +25,15 @@ class TestTinyViT(BaseTester):
out = model(inpt)
assert out.shape == (batch_size, num_classes)
- @pytest.mark.skip('not implemented')
+ @pytest.mark.skip("not implemented")
def test_exception(self):
...
- @pytest.mark.skip('not implemented')
+ @pytest.mark.skip("not implemented")
def test_gradcheck(self):
...
- @pytest.mark.skip('not implemented')
+ @pytest.mark.skip("not implemented")
def test_module(self):
...
@@ -52,7 +52,7 @@ class TestTinyViT(BaseTester):
assert isinstance(model, TinyViT)
@pytest.mark.slow
- @pytest.mark.parametrize('num_classes', [1000, 8])
+ @pytest.mark.parametrize("num_classes", [1000, 8])
@pytest.mark.parametrize("img_size", [224, 256])
def test_pretrained(self, img_size, num_classes):
model = TinyViT.from_config("5m", img_size=img_size, num_classes=num_classes, pretrained=True)
diff --git a/test/contrib/test_contrib.py b/test/contrib/test_contrib.py
index 782f60e40..0379b85d4 100644
--- a/test/contrib/test_contrib.py
+++ b/test/contrib/test_contrib.py
@@ -81,11 +81,11 @@ class TestVisionTransformer:
class TestMobileViT:
@pytest.mark.parametrize("B", [1, 2])
@pytest.mark.parametrize("image_size", [(256, 256)])
- @pytest.mark.parametrize("mode", ['xxs', 'xs', 's'])
+ @pytest.mark.parametrize("mode", ["xxs", "xs", "s"])
@pytest.mark.parametrize("patch_size", [(2, 2)])
def test_smoke(self, device, dtype, B, image_size, mode, patch_size):
ih, iw = image_size
- channel = {'xxs': 320, 'xs': 384, 's': 640}
+ channel = {"xxs": 320, "xs": 384, "s": 640}
img = torch.rand(B, 3, ih, iw, device=device, dtype=dtype)
mvit = kornia.contrib.MobileViT(mode=mode, patch_size=patch_size).to(device, dtype)
@@ -121,20 +121,20 @@ class TestConnectedComponents:
with pytest.raises(TypeError) as errinf:
assert kornia.contrib.connected_components(img, 1.0)
- assert 'Input num_iterations must be a positive integer.' in str(errinf)
+ assert "Input num_iterations must be a positive integer." in str(errinf)
with pytest.raises(TypeError) as errinf:
- assert kornia.contrib.connected_components('not a tensor', 0)
- assert 'Input imagetype is not a Tensor. Got:' in str(errinf)
+ assert kornia.contrib.connected_components("not a tensor", 0)
+ assert "Input imagetype is not a Tensor. Got:" in str(errinf)
with pytest.raises(TypeError) as errinf:
assert kornia.contrib.connected_components(img, 0)
- assert 'Input num_iterations must be a positive integer.' in str(errinf)
+ assert "Input num_iterations must be a positive integer." in str(errinf)
with pytest.raises(ValueError) as errinf:
img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
assert kornia.contrib.connected_components(img, 2)
- assert 'Input image shape must be (*,1,H,W). Got:' in str(errinf)
+ assert "Input image shape must be (*,1,H,W). Got:" in str(errinf)
def test_value(self, device, dtype):
img = torch.tensor(
@@ -445,7 +445,7 @@ class TestLambdaModule:
class TestImageStitcher:
- @pytest.mark.parametrize("estimator", ['ransac', 'vanilla'])
+ @pytest.mark.parametrize("estimator", ["ransac", "vanilla"])
def test_smoke(self, estimator, device, dtype):
B, C, H, W = 1, 3, 6, 6
sample1 = torch.tensor(
@@ -541,7 +541,7 @@ class TestImageStitcher:
"batch_indexes": torch.zeros((15,), device=device, dtype=dtype),
}
with patch(
- 'kornia.contrib.ImageStitcher.on_matcher', new_callable=PropertyMock, return_value=lambda x: return_value
+ "kornia.contrib.ImageStitcher.on_matcher", new_callable=PropertyMock, return_value=lambda x: return_value
):
# NOTE: This will need to download the pretrained weights.
# To avoid that, we mock as below
@@ -561,7 +561,7 @@ class TestImageStitcher:
matcher = kornia.feature.LoFTR(None)
with pytest.raises(NotImplementedError):
- stitcher = kornia.contrib.ImageStitcher(matcher, estimator='random').to(device=device, dtype=dtype)
+ stitcher = kornia.contrib.ImageStitcher(matcher, estimator="random").to(device=device, dtype=dtype)
stitcher = kornia.contrib.ImageStitcher(matcher).to(device=device, dtype=dtype)
with pytest.raises(RuntimeError):
diff --git a/test/contrib/test_prompter.py b/test/contrib/test_prompter.py
index ca189cedc..cf164b065 100644
--- a/test/contrib/test_prompter.py
+++ b/test/contrib/test_prompter.py
@@ -10,7 +10,7 @@ class TestVisualPrompter(BaseTester):
@pytest.mark.slow
def test_smoke(self, device, dtype):
inpt = torch.rand(3, 77, 128, device=device, dtype=dtype)
- prompter = VisualPrompter(SamConfig('vit_b'), device, dtype)
+ prompter = VisualPrompter(SamConfig("vit_b"), device, dtype)
prompter.set_image(inpt)
assert prompter.is_image_set
@@ -19,14 +19,14 @@ class TestVisualPrompter(BaseTester):
assert not prompter.is_image_set
@pytest.mark.slow
- @pytest.mark.parametrize('batch_size', [1, 4])
- @pytest.mark.parametrize('N', [2, 5])
- @pytest.mark.parametrize('multimask_output', [True, False])
+ @pytest.mark.parametrize("batch_size", [1, 4])
+ @pytest.mark.parametrize("N", [2, 5])
+ @pytest.mark.parametrize("multimask_output", [True, False])
def test_cardinality(self, device, batch_size, N, multimask_output):
# SAM: don't supports float64
dtype = torch.float32
inpt = torch.rand(3, 77, 128, device=device, dtype=dtype)
- prompter = VisualPrompter(SamConfig('vit_b'), device, dtype)
+ prompter = VisualPrompter(SamConfig("vit_b"), device, dtype)
keypoints = torch.randint(0, min(inpt.shape[-2:]), (batch_size, N, 2), device=device).to(dtype=dtype)
labels = torch.randint(0, 1, (batch_size, N), device=device).to(dtype=dtype)
@@ -40,48 +40,48 @@ class TestVisualPrompter(BaseTester):
assert out.scores.shape == (batch_size, C)
def test_exception(self):
- prompter = VisualPrompter(SamConfig('vit_b'))
+ prompter = VisualPrompter(SamConfig("vit_b"))
inpt = torch.rand(1, 3, 1, 2)
# Wrong shape for the image
with pytest.raises(TypeError) as errinfo:
prompter.set_image(inpt, [], False)
- assert 'shape must be [[\'3\', \'H\', \'W\']]. Got torch.Size([1, 3, 1, 2])' in str(errinfo)
+ assert "shape must be [['3', 'H', 'W']]. Got torch.Size([1, 3, 1, 2])" in str(errinfo)
# predict without set an image
with pytest.raises(Exception) as errinfo:
prompter.predict()
- assert 'An image must be set with `self.set_image(...)`' in str(errinfo)
+ assert "An image must be set with `self.set_image(...)`" in str(errinfo)
# Valid masks
with pytest.raises(TypeError) as errinfo:
prompter._valid_masks(inpt)
- assert 'shape must be [[\'K\', \'1\', \'256\', \'256\']]. Got torch.Size([1, 3, 1, 2])' in str(errinfo)
+ assert "shape must be [['K', '1', '256', '256']]. Got torch.Size([1, 3, 1, 2])" in str(errinfo)
# Valid boxes
with pytest.raises(TypeError) as errinfo:
prompter._valid_boxes(inpt)
- assert 'shape must be [[\'K\', \'4\']]. Got torch.Size([1, 3, 1, 2])' in str(errinfo)
+ assert "shape must be [['K', '4']]. Got torch.Size([1, 3, 1, 2])" in str(errinfo)
# Valid keypoints
with pytest.raises(TypeError) as errinfo:
prompter._valid_keypoints(inpt, None)
- assert 'shape must be [[\'K\', \'N\', \'2\']]. Got torch.Size([1, 3, 1, 2])' in str(errinfo)
+ assert "shape must be [['K', 'N', '2']]. Got torch.Size([1, 3, 1, 2])" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
prompter._valid_keypoints(torch.rand(1, 1, 2), inpt)
- assert 'shape must be [[\'K\', \'N\']]. Got torch.Size([1, 3, 1, 2])' in str(errinfo)
+ assert "shape must be [['K', 'N']]. Got torch.Size([1, 3, 1, 2])" in str(errinfo)
with pytest.raises(Exception) as errinfo:
prompter._valid_keypoints(torch.rand(1, 1, 2), torch.rand(2, 1))
- assert 'The keypoints and labels should have the same batch size' in str(errinfo)
+ assert "The keypoints and labels should have the same batch size" in str(errinfo)
- @pytest.mark.skip(reason='Unecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_gradcheck(self, device):
...
- @pytest.mark.skip(reason='Unecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_module(self):
...
@@ -89,7 +89,7 @@ class TestVisualPrompter(BaseTester):
dtype = torch.float32
img = torch.rand(3, 128, 75, device=device, dtype=dtype)
- prompter = VisualPrompter(SamConfig('vit_b'), device, dtype)
+ prompter = VisualPrompter(SamConfig("vit_b"), device, dtype)
prompter.set_image(img)
expected = prompter.predict(img)
diff --git a/test/enhance/test_equalization.py b/test/enhance/test_equalization.py
index 6f78ad007..a24f972e5 100644
--- a/test/enhance/test_equalization.py
+++ b/test/enhance/test_equalization.py
@@ -45,12 +45,12 @@ class TestEqualization(BaseTester):
@pytest.mark.parametrize(
"B, clip, grid, exception_type, expected_error_msg",
[
- (0, 1.0, (2, 2), ValueError, 'Invalid input tensor, it is empty.'), # from perform_keep_shape_image
- (1, 1, (2, 2), TypeError, 'Input clip_limit type is not float. Got'),
- (1, 2.0, 2, TypeError, 'Input grid_size type is not Tuple. Got'),
- (1, 2.0, (2, 2, 2), TypeError, 'Input grid_size is not a Tuple with 2 elements. Got 3'),
- (1, 2.0, (2, 2.0), TypeError, 'Input grid_size type is not valid, must be a Tuple[int, int]'),
- (1, 2.0, (2, 0), ValueError, 'Input grid_size elements must be positive. Got'),
+ (0, 1.0, (2, 2), ValueError, "Invalid input tensor, it is empty."), # from perform_keep_shape_image
+ (1, 1, (2, 2), TypeError, "Input clip_limit type is not float. Got"),
+ (1, 2.0, 2, TypeError, "Input grid_size type is not Tuple. Got"),
+ (1, 2.0, (2, 2, 2), TypeError, "Input grid_size is not a Tuple with 2 elements. Got 3"),
+ (1, 2.0, (2, 2.0), TypeError, "Input grid_size type is not valid, must be a Tuple[int, int]"),
+ (1, 2.0, (2, 0), ValueError, "Input grid_size elements must be positive. Got"),
],
)
def test_exception(self, B, clip, grid, exception_type, expected_error_msg):
diff --git a/test/enhance/test_integral.py b/test/enhance/test_integral.py
index 03c4efc3c..0c2c5d921 100644
--- a/test/enhance/test_integral.py
+++ b/test/enhance/test_integral.py
@@ -27,7 +27,7 @@ class TestIntegralTensor(BaseTester):
integral_tensor(tensor, dim)
with pytest.raises(Exception) as errinfo:
integral_tensor(tensor, ())
- assert 'dim must be a non-empty tuple.' in str(errinfo)
+ assert "dim must be a non-empty tuple." in str(errinfo)
def test_module(self, device, dtype):
mod = IntegralTensor()
diff --git a/test/enhance/test_normalize.py b/test/enhance/test_normalize.py
index 906c731d9..64b4ea266 100644
--- a/test/enhance/test_normalize.py
+++ b/test/enhance/test_normalize.py
@@ -282,10 +282,10 @@ class TestNormalizeMinMax(BaseTester):
assert kornia.enhance.normalize_min_max(0.0)
with pytest.raises(TypeError):
- assert kornia.enhance.normalize_min_max(x, '', '')
+ assert kornia.enhance.normalize_min_max(x, "", "")
with pytest.raises(TypeError):
- assert kornia.enhance.normalize_min_max(x, 2.0, '')
+ assert kornia.enhance.normalize_min_max(x, 2.0, "")
@pytest.mark.parametrize("input_shape", [(1, 2, 3, 4), (2, 1, 4, 3), (1, 3, 2, 1)])
def test_cardinality(self, device, dtype, input_shape):
diff --git a/test/enhance/test_zca.py b/test/enhance/test_zca.py
index e16f3d28f..65e140fb3 100644
--- a/test/enhance/test_zca.py
+++ b/test/enhance/test_zca.py
@@ -27,11 +27,11 @@ class TestZCA(BaseTester):
@pytest.mark.parametrize("dim", [0, 1])
def test_dim_args(self, dim, device, dtype):
- if 'xla' in device.type:
+ if "xla" in device.type:
pytest.skip("buggy with XLA devices.")
if dtype == torch.float16:
- pytest.skip('not work for half-precision')
+ pytest.skip("not work for half-precision")
data = torch.tensor([[0, 1], [1, 0], [-1, 0], [0, -1]], device=device, dtype=dtype)
diff --git a/test/feature/test_disk.py b/test/feature/test_disk.py
index 06a157036..b877227ee 100644
--- a/test/feature/test_disk.py
+++ b/test/feature/test_disk.py
@@ -29,7 +29,7 @@ class TestDisk:
@pytest.mark.slow
def test_smoke_pretrained(self, device):
- disk = DISK.from_pretrained(checkpoint='depth', device=device)
+ disk = DISK.from_pretrained(checkpoint="depth", device=device)
inp = torch.ones(1, 3, 64, 64, device=device)
output = disk(inp)
assert isinstance(output, list)
@@ -40,11 +40,11 @@ class TestDisk:
@pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")
@pytest.mark.parametrize("data", ["disk_outdoor"], indirect=True)
def test_pretrained_outdoor(self, device, dtype, data):
- disk = DISK.from_pretrained(checkpoint='depth', device=device).to(dtype)
+ disk = DISK.from_pretrained(checkpoint="depth", device=device).to(dtype)
data_dev = utils.dict_to(data, device, dtype)
num_feat = 256
with torch.no_grad():
- out = disk(data_dev['img1'], num_feat)
+ out = disk(data_dev["img1"], num_feat)
assert_close(out[0].keypoints, data_dev["disk1"][0].keypoints.to(dtype))
assert_close(out[0].descriptors, data_dev["disk1"][0].descriptors.to(dtype))
diff --git a/test/feature/test_integrated.py b/test/feature/test_integrated.py
index 41d118dcb..35dae6911 100644
--- a/test/feature/test_integrated.py
+++ b/test/feature/test_integrated.py
@@ -233,21 +233,21 @@ class TestGFTTAffNetHardNet:
# TODO: add kornia.testing.BaseTester
class TestLocalFeatureMatcher:
def test_smoke(self, device):
- matcher = LocalFeatureMatcher(SIFTFeature(5), DescriptorMatcher('snn', 0.8)).to(device)
+ matcher = LocalFeatureMatcher(SIFTFeature(5), DescriptorMatcher("snn", 0.8)).to(device)
assert matcher is not None
@pytest.mark.slow
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_nomatch(self, device, dtype, data):
- matcher = LocalFeatureMatcher(GFTTAffNetHardNet(100), DescriptorMatcher('snn', 0.8)).to(device, dtype)
+ matcher = LocalFeatureMatcher(GFTTAffNetHardNet(100), DescriptorMatcher("snn", 0.8)).to(device, dtype)
data_dev = utils.dict_to(data, device, dtype)
with torch.no_grad():
out = matcher({"image0": data_dev["image0"], "image1": 0 * data_dev["image0"]})
- assert len(out['keypoints0']) == 0
+ assert len(out["keypoints0"]) == 0
@pytest.mark.skip("Takes too long time (but works)")
def test_gradcheck(self, device):
- matcher = LocalFeatureMatcher(SIFTFeature(5), DescriptorMatcher('nn', 1.0)).to(device)
+ matcher = LocalFeatureMatcher(SIFTFeature(5), DescriptorMatcher("nn", 1.0)).to(device)
patches = torch.rand(1, 1, 32, 32, device=device)
patches05 = resize(patches, (48, 48))
patches = utils.tensor_to_gradcheck_var(patches) # to var
@@ -264,14 +264,14 @@ class TestLocalFeatureMatcher:
def test_real_sift(self, device, dtype, data):
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
- matcher = LocalFeatureMatcher(SIFTFeature(1000), DescriptorMatcher('snn', 0.8)).to(device, dtype)
- ransac = RANSAC('homography', 1.0, 1024, 5).to(device, dtype)
+ matcher = LocalFeatureMatcher(SIFTFeature(1000), DescriptorMatcher("snn", 0.8)).to(device, dtype)
+ ransac = RANSAC("homography", 1.0, 1024, 5).to(device, dtype)
data_dev = utils.dict_to(data, device, dtype)
- pts_src = data_dev['pts0']
- pts_dst = data_dev['pts1']
+ pts_src = data_dev["pts0"]
+ pts_dst = data_dev["pts1"]
with torch.no_grad():
out = matcher(data_dev)
- homography, inliers = ransac(out['keypoints0'], out['keypoints1'])
+ homography, inliers = ransac(out["keypoints0"], out["keypoints1"])
assert inliers.sum().item() > 50 # we have enough inliers
# Reprojection error of 5px is OK
assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
@@ -283,11 +283,11 @@ class TestLocalFeatureMatcher:
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
feat = SIFTFeature(1000).to(device, dtype)
- matcher = LocalFeatureMatcher(feat, DescriptorMatcher('snn', 0.8)).to(device)
- ransac = RANSAC('homography', 1.0, 1024, 5).to(device, dtype)
+ matcher = LocalFeatureMatcher(feat, DescriptorMatcher("snn", 0.8)).to(device)
+ ransac = RANSAC("homography", 1.0, 1024, 5).to(device, dtype)
data_dev = utils.dict_to(data, device, dtype)
- pts_src = data_dev['pts0']
- pts_dst = data_dev['pts1']
+ pts_src = data_dev["pts0"]
+ pts_dst = data_dev["pts1"]
lafs, _, descs = feat(data_dev["image0"])
data_dev["lafs0"] = lafs
@@ -299,7 +299,7 @@ class TestLocalFeatureMatcher:
with torch.no_grad():
out = matcher(data_dev)
- homography, inliers = ransac(out['keypoints0'], out['keypoints1'])
+ homography, inliers = ransac(out["keypoints0"], out["keypoints1"])
assert inliers.sum().item() > 50 # we have enough inliers
# Reprojection error of 5px is OK
assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
@@ -310,15 +310,15 @@ class TestLocalFeatureMatcher:
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_real_gftt(self, device, dtype, data):
# This is not unit test, but that is quite good integration test
- matcher = LocalFeatureMatcher(GFTTAffNetHardNet(1000), DescriptorMatcher('snn', 0.8)).to(device, dtype)
- ransac = RANSAC('homography', 1.0, 1024, 5).to(device, dtype)
+ matcher = LocalFeatureMatcher(GFTTAffNetHardNet(1000), DescriptorMatcher("snn", 0.8)).to(device, dtype)
+ ransac = RANSAC("homography", 1.0, 1024, 5).to(device, dtype)
data_dev = utils.dict_to(data, device, dtype)
- pts_src = data_dev['pts0']
- pts_dst = data_dev['pts1']
+ pts_src = data_dev["pts0"]
+ pts_dst = data_dev["pts1"]
with torch.no_grad():
torch.manual_seed(0)
out = matcher(data_dev)
- homography, inliers = ransac(out['keypoints0'], out['keypoints1'])
+ homography, inliers = ransac(out["keypoints0"], out["keypoints1"])
assert inliers.sum().item() > 50 # we have enough inliers
# Reprojection error of 5px is OK
assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
@@ -330,14 +330,14 @@ class TestLocalFeatureMatcher:
def test_real_keynet(self, device, dtype, data):
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
- matcher = LocalFeatureMatcher(KeyNetHardNet(500), DescriptorMatcher('snn', 0.9)).to(device, dtype)
- ransac = RANSAC('homography', 1.0, 1024, 5).to(device, dtype)
+ matcher = LocalFeatureMatcher(KeyNetHardNet(500), DescriptorMatcher("snn", 0.9)).to(device, dtype)
+ ransac = RANSAC("homography", 1.0, 1024, 5).to(device, dtype)
data_dev = utils.dict_to(data, device, dtype)
- pts_src = data_dev['pts0']
- pts_dst = data_dev['pts1']
+ pts_src = data_dev["pts0"]
+ pts_dst = data_dev["pts1"]
with torch.no_grad():
out = matcher(data_dev)
- homography, inliers = ransac(out['keypoints0'], out['keypoints1'])
+ homography, inliers = ransac(out["keypoints0"], out["keypoints1"])
assert inliers.sum().item() > 50 # we have enough inliers
# Reprojection error of 5px is OK
assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
@@ -348,7 +348,7 @@ class TestLocalFeatureMatcher:
patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
patches2x = resize(patches, (48, 48))
inputs = {"image0": patches, "image1": patches2x}
- model = LocalFeatureMatcher(SIFTDescriptor(32), DescriptorMatcher('snn', 0.8)).to(device).eval()
+ model = LocalFeatureMatcher(SIFTDescriptor(32), DescriptorMatcher("snn", 0.8)).to(device).eval()
model_jit = torch.jit.script(model)
out = model(inputs)
diff --git a/test/feature/test_loftr.py b/test/feature/test_loftr.py
index 0eed2814f..0187fb587 100644
--- a/test/feature/test_loftr.py
+++ b/test/feature/test_loftr.py
@@ -14,12 +14,12 @@ from kornia.utils._compat import torch_version_ge
class TestLoFTR:
@pytest.mark.slow
def test_pretrained_outdoor_smoke(self, device, dtype):
- loftr = LoFTR('outdoor').to(device, dtype)
+ loftr = LoFTR("outdoor").to(device, dtype)
assert loftr is not None
@pytest.mark.slow
def test_pretrained_indoor_smoke(self, device, dtype):
- loftr = LoFTR('indoor').to(device, dtype)
+ loftr = LoFTR("indoor").to(device, dtype)
assert loftr is not None
@pytest.mark.slow
@@ -27,24 +27,24 @@ class TestLoFTR:
@pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")
@pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)
def test_pretrained_indoor(self, device, dtype, data):
- loftr = LoFTR('indoor').to(device, dtype)
+ loftr = LoFTR("indoor").to(device, dtype)
data_dev = utils.dict_to(data, device, dtype)
with torch.no_grad():
out = loftr(data_dev)
- assert_close(out['keypoints0'], data_dev["loftr_indoor_tentatives0"])
- assert_close(out['keypoints1'], data_dev["loftr_indoor_tentatives1"])
+ assert_close(out["keypoints0"], data_dev["loftr_indoor_tentatives0"])
+ assert_close(out["keypoints1"], data_dev["loftr_indoor_tentatives1"])
@pytest.mark.slow
@pytest.mark.skipif(torch_version_ge(1, 10), reason="RuntimeError: CUDA out of memory with pytorch>=1.10")
@pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_pretrained_outdoor(self, device, dtype, data):
- loftr = LoFTR('outdoor').to(device, dtype)
+ loftr = LoFTR("outdoor").to(device, dtype)
data_dev = utils.dict_to(data, device, dtype)
with torch.no_grad():
out = loftr(data_dev)
- assert_close(out['keypoints0'], data_dev["loftr_outdoor_tentatives0"])
- assert_close(out['keypoints1'], data_dev["loftr_outdoor_tentatives1"])
+ assert_close(out["keypoints0"], data_dev["loftr_outdoor_tentatives0"])
+ assert_close(out["keypoints1"], data_dev["loftr_outdoor_tentatives1"])
@pytest.mark.slow
def test_mask(self, device):
diff --git a/test/feature/test_matching.py b/test/feature/test_matching.py
index a807f9ee2..b3b10285c 100644
--- a/test/feature/test_matching.py
+++ b/test/feature/test_matching.py
@@ -71,7 +71,7 @@ class TestMatchMNN:
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
assert_close(dists, expected_dists)
assert_close(idxs, expected_idx)
- matcher = DescriptorMatcher('mnn').to(device)
+ matcher = DescriptorMatcher("mnn").to(device)
dists1, idxs1 = matcher(desc1, desc2)
assert_close(dists1, expected_dists)
assert_close(idxs1, expected_idx)
@@ -113,7 +113,7 @@ class TestMatchSNN:
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
assert_close(dists, expected_dists)
assert_close(idxs, expected_idx)
- matcher = DescriptorMatcher('snn', 0.8).to(device)
+ matcher = DescriptorMatcher("snn", 0.8).to(device)
dists1, idxs1 = matcher(desc1, desc2)
assert_close(dists1, expected_dists)
assert_close(idxs1, expected_idx)
@@ -127,7 +127,7 @@ class TestMatchSNN:
expected_idx = torch.tensor([[0, 4], [1, 3], [3, 1], [4, 0]], device=device)
assert_close(dists, expected_dists)
assert_close(idxs, expected_idx)
- matcher = DescriptorMatcher('snn', 0.1).to(device)
+ matcher = DescriptorMatcher("snn", 0.1).to(device)
dists1, idxs1 = matcher(desc1, desc2)
assert_close(dists1, expected_dists)
assert_close(idxs1, expected_idx)
@@ -162,7 +162,7 @@ class TestMatchSMNN:
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
assert_close(dists, expected_dists)
assert_close(idxs, expected_idx)
- matcher = DescriptorMatcher('smnn', 0.8).to(device)
+ matcher = DescriptorMatcher("smnn", 0.8).to(device)
dists1, idxs1 = matcher(desc1, desc2)
assert_close(dists1, expected_dists)
assert_close(idxs1, expected_idx)
@@ -184,7 +184,7 @@ class TestMatchSMNN:
expected_idx = torch.tensor([[0, 4], [1, 3], [3, 1], [4, 0]], device=device)
assert_close(dists, expected_dists)
assert_close(idxs, expected_idx)
- matcher = DescriptorMatcher('smnn', 0.1).to(device)
+ matcher = DescriptorMatcher("smnn", 0.1).to(device)
dists1, idxs1 = matcher(desc1, desc2)
assert_close(dists1, expected_dists)
assert_close(idxs1, expected_idx)
@@ -219,7 +219,7 @@ class TestMatchSMNN:
desc2 = torch.rand(7, 8, device=device)
desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
- matcher = DescriptorMatcher('smnn', 0.8).to(device)
+ matcher = DescriptorMatcher("smnn", 0.8).to(device)
assert gradcheck(match_smnn, (desc1, desc2, 0.8), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
assert gradcheck(matcher, (desc1, desc2), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
@@ -273,7 +273,7 @@ class TestMatchFGINN:
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
assert_close(dists, expected_dists, rtol=0.001, atol=1e-3)
assert_close(idxs, expected_idx)
- matcher = GeometryAwareDescriptorMatcher('fginn', {"spatial_th": 0.01}).to(device)
+ matcher = GeometryAwareDescriptorMatcher("fginn", {"spatial_th": 0.01}).to(device)
dists1, idxs1 = matcher(desc1, desc2, lafs1, lafs2)
assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)
assert_close(idxs1, expected_idx)
@@ -289,7 +289,7 @@ class TestMatchFGINN:
expected_idx = torch.tensor([[1, 3], [2, 2], [3, 1], [4, 0], [5, 4]], device=device)
assert_close(dists, expected_dists, rtol=0.001, atol=1e-3)
assert_close(idxs, expected_idx)
- matcher = GeometryAwareDescriptorMatcher('fginn', {"spatial_th": 2.0, "mutual": True}).to(device)
+ matcher = GeometryAwareDescriptorMatcher("fginn", {"spatial_th": 2.0, "mutual": True}).to(device)
dists1, idxs1 = matcher(desc1, desc2, lafs1, lafs2)
assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)
assert_close(idxs1, expected_idx)
@@ -315,7 +315,7 @@ class TestMatchFGINN:
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
assert_close(dists, expected_dists, rtol=0.001, atol=1e-3)
assert_close(idxs, expected_idx)
- matcher = GeometryAwareDescriptorMatcher('fginn', {"spatial_th": 2.0}).to(device)
+ matcher = GeometryAwareDescriptorMatcher("fginn", {"spatial_th": 2.0}).to(device)
dists1, idxs1 = matcher(desc1, desc2, lafs1, lafs2)
assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)
assert_close(idxs1, expected_idx)
@@ -344,8 +344,8 @@ class TestMatchFGINN:
center2 = torch.rand(1, 7, 2, device=device)
lafs1 = laf_from_center_scale_ori(center1)
lafs2 = laf_from_center_scale_ori(center2)
- matcher = GeometryAwareDescriptorMatcher('fginn', 0.8).to(device)
- matcher_jit = torch.jit.script(GeometryAwareDescriptorMatcher('fginn', 0.8).to(device))
+ matcher = GeometryAwareDescriptorMatcher("fginn", 0.8).to(device)
+ matcher_jit = torch.jit.script(GeometryAwareDescriptorMatcher("fginn", 0.8).to(device))
assert_close(matcher(desc1, desc2)[0], matcher_jit(desc1, desc2, lafs1, lafs2)[0])
assert_close(matcher(desc1, desc2)[1], matcher_jit(desc1, desc2, lafs1, lafs2)[1])
@@ -358,13 +358,13 @@ class TestAdalam:
# This is not unit test, but that is quite good integration test
data_dev = utils.dict_to(data, device, dtype)
with torch.no_grad():
- dists, idxs = match_adalam(data_dev['descs1'], data_dev['descs2'], data_dev['lafs1'], data_dev['lafs2'])
+ dists, idxs = match_adalam(data_dev["descs1"], data_dev["descs2"], data_dev["lafs1"], data_dev["lafs2"])
assert idxs.shape[1] == 2
assert dists.shape[1] == 1
assert idxs.shape[0] == dists.shape[0]
- assert dists.shape[0] <= data_dev['descs1'].shape[0]
- assert dists.shape[0] <= data_dev['descs2'].shape[0]
- expected_idxs = data_dev['expected_idxs'].long()
+ assert dists.shape[0] <= data_dev["descs1"].shape[0]
+ assert dists.shape[0] <= data_dev["descs2"].shape[0]
+ expected_idxs = data_dev["expected_idxs"].long()
assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)
@pytest.mark.slow
@@ -375,10 +375,10 @@ class TestAdalam:
data_dev = utils.dict_to(data, device, dtype)
with torch.no_grad():
dists, idxs = match_adalam(
- data_dev['descs1'], data_dev['descs2'][:1], data_dev['lafs1'], data_dev['lafs2'][:, :1]
+ data_dev["descs1"], data_dev["descs2"][:1], data_dev["lafs1"], data_dev["lafs2"][:, :1]
)
dists, idxs = match_adalam(
- data_dev['descs1'][:1], data_dev['descs2'], data_dev['lafs1'][:, :1], data_dev['lafs2']
+ data_dev["descs1"][:1], data_dev["descs2"], data_dev["lafs1"][:, :1], data_dev["lafs2"]
)
@pytest.mark.slow
@@ -390,10 +390,10 @@ class TestAdalam:
adalam_config = {"device": device}
with torch.no_grad():
dists, idxs = match_adalam(
- data_dev['descs1'][:4],
- data_dev['descs2'][:4],
- data_dev['lafs1'][:, :4],
- data_dev['lafs2'][:, :4],
+ data_dev["descs1"][:4],
+ data_dev["descs2"][:4],
+ data_dev["lafs1"][:, :4],
+ data_dev["lafs2"][:, :4],
config=adalam_config,
)
@@ -405,16 +405,16 @@ class TestAdalam:
data_dev = utils.dict_to(data, device, dtype)
with torch.no_grad():
dists, idxs = match_adalam(
- data_dev['descs1'],
+ data_dev["descs1"],
torch.empty(0, 128, device=device, dtype=dtype),
- data_dev['lafs1'],
+ data_dev["lafs1"],
torch.empty(0, 0, 2, 3, device=device, dtype=dtype),
)
dists, idxs = match_adalam(
torch.empty(0, 128, device=device, dtype=dtype),
- data_dev['descs2'],
+ data_dev["descs2"],
torch.empty(0, 0, 2, 3, device=device, dtype=dtype),
- data_dev['lafs2'],
+ data_dev["lafs2"],
)
@pytest.mark.slow
@@ -425,7 +425,7 @@ class TestAdalam:
data_dev = utils.dict_to(data, device, dtype)
with torch.no_grad():
dists, idxs = match_adalam(
- data_dev['descs1'][:4], data_dev['descs2'][:4], data_dev['lafs1'][:, :4], data_dev['lafs2'][:, :4]
+ data_dev["descs1"][:4], data_dev["descs2"][:4], data_dev["lafs1"][:, :4], data_dev["lafs2"][:, :4]
)
@pytest.mark.slow
@@ -436,10 +436,10 @@ class TestAdalam:
data_dev = utils.dict_to(data, device, dtype)
with torch.no_grad():
dists, idxs = match_adalam(
- data_dev['descs1'][:100],
- data_dev['descs2'][:100],
- data_dev['lafs1'][:, :100],
- data_dev['lafs2'][:, :100],
+ data_dev["descs1"][:100],
+ data_dev["descs2"][:100],
+ data_dev["lafs1"][:, :100],
+ data_dev["lafs2"][:, :100],
)
@pytest.mark.slow
@@ -448,15 +448,15 @@ class TestAdalam:
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
data_dev = utils.dict_to(data, device, dtype)
- matcher = GeometryAwareDescriptorMatcher('adalam', {"device": device}).to(device, dtype)
+ matcher = GeometryAwareDescriptorMatcher("adalam", {"device": device}).to(device, dtype)
with torch.no_grad():
- dists, idxs = matcher(data_dev['descs1'], data_dev['descs2'], data_dev['lafs1'], data_dev['lafs2'])
+ dists, idxs = matcher(data_dev["descs1"], data_dev["descs2"], data_dev["lafs1"], data_dev["lafs2"])
assert idxs.shape[1] == 2
assert dists.shape[1] == 1
assert idxs.shape[0] == dists.shape[0]
- assert dists.shape[0] <= data_dev['descs1'].shape[0]
- assert dists.shape[0] <= data_dev['descs2'].shape[0]
- expected_idxs = data_dev['expected_idxs'].long()
+ assert dists.shape[0] <= data_dev["descs1"].shape[0]
+ assert dists.shape[0] <= data_dev["descs2"].shape[0]
+ expected_idxs = data_dev["expected_idxs"].long()
assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)
@@ -468,15 +468,15 @@ class TestLightGlueDISK:
# This is not unit test, but that is quite good integration test
data_dev = utils.dict_to(data, device, dtype)
config = {"depth_confidence": -1, "width_confidence": -1}
- lg = LightGlueMatcher('disk', config).to(device=device, dtype=dtype).eval()
+ lg = LightGlueMatcher("disk", config).to(device=device, dtype=dtype).eval()
with torch.no_grad():
- dists, idxs = lg(data_dev['descs1'], data_dev['descs2'], data_dev['lafs1'], data_dev['lafs2'])
+ dists, idxs = lg(data_dev["descs1"], data_dev["descs2"], data_dev["lafs1"], data_dev["lafs2"])
assert idxs.shape[1] == 2
assert dists.shape[1] == 1
assert idxs.shape[0] == dists.shape[0]
- assert dists.shape[0] <= data_dev['descs1'].shape[0]
- assert dists.shape[0] <= data_dev['descs2'].shape[0]
- expected_idxs = data_dev['lightglue_disk_idxs'].long()
+ assert dists.shape[0] <= data_dev["descs1"].shape[0]
+ assert dists.shape[0] <= data_dev["descs2"].shape[0]
+ expected_idxs = data_dev["lightglue_disk_idxs"].long()
assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)
@pytest.mark.slow
@@ -485,10 +485,10 @@ class TestLightGlueDISK:
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
data_dev = utils.dict_to(data, device, dtype)
- lg = LightGlueMatcher('disk').to(device, dtype).eval()
+ lg = LightGlueMatcher("disk").to(device, dtype).eval()
with torch.no_grad():
- dists, idxs = lg(data_dev['descs1'], data_dev['descs2'][:1], data_dev['lafs1'], data_dev['lafs2'][:, :1])
- dists, idxs = lg(data_dev['descs1'][:1], data_dev['descs2'], data_dev['lafs1'][:, :1], data_dev['lafs2'])
+ dists, idxs = lg(data_dev["descs1"], data_dev["descs2"][:1], data_dev["lafs1"], data_dev["lafs2"][:, :1])
+ dists, idxs = lg(data_dev["descs1"][:1], data_dev["descs2"], data_dev["lafs1"][:, :1], data_dev["lafs2"])
@pytest.mark.slow
@pytest.mark.parametrize("data", ["lightglue_idxs"], indirect=True)
@@ -496,17 +496,17 @@ class TestLightGlueDISK:
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
data_dev = utils.dict_to(data, device, dtype)
- lg = LightGlueMatcher('disk').to(device, dtype).eval()
+ lg = LightGlueMatcher("disk").to(device, dtype).eval()
with torch.no_grad():
dists, idxs = lg(
- data_dev['descs1'],
+ data_dev["descs1"],
torch.empty(0, 256, device=device, dtype=dtype),
- data_dev['lafs1'],
+ data_dev["lafs1"],
torch.empty(0, 0, 2, 3, device=device, dtype=dtype),
)
dists, idxs = lg(
torch.empty(0, 256, device=device, dtype=dtype),
- data_dev['descs2'],
+ data_dev["descs2"],
torch.empty(0, 0, 2, 3, device=device, dtype=dtype),
- data_dev['lafs2'],
+ data_dev["lafs2"],
)
diff --git a/test/feature/test_mkd.py b/test/feature/test_mkd.py
index 9581c72e5..df4d05af1 100644
--- a/test/feature/test_mkd.py
+++ b/test/feature/test_mkd.py
@@ -24,7 +24,7 @@ from kornia.testing import assert_close
@pytest.mark.parametrize("ps", [5, 13, 25])
def test_get_grid_dict(ps):
grid_dict = get_grid_dict(ps)
- param_keys = ['x', 'y', 'phi', 'rho']
+ param_keys = ["x", "y", "phi", "rho"]
assert set(grid_dict.keys()) == set(param_keys)
for k in param_keys:
assert grid_dict[k].shape == (ps, ps)
@@ -198,7 +198,7 @@ class TestEmbedGradients:
assert_close(model(patches), model_jit(patches))
[email protected]("kernel_type,d,ps", [('cart', 9, 9), ('polar', 25, 9), ('cart', 9, 16), ('polar', 25, 16)])
[email protected]("kernel_type,d,ps", [("cart", 9, 9), ("polar", 25, 9), ("cart", 9, 16), ("polar", 25, 16)])
def test_spatial_kernel_embedding(kernel_type, ps, d):
grids = get_grid_dict(ps)
spatial_kernel = spatial_kernel_embedding(kernel_type, grids)
@@ -207,26 +207,26 @@ def test_spatial_kernel_embedding(kernel_type, ps, d):
class TestExplicitSpacialEncoding:
@pytest.mark.parametrize(
- "kernel_type,ps,in_dims", [('cart', 9, 3), ('polar', 9, 3), ('cart', 13, 7), ('polar', 13, 7)]
+ "kernel_type,ps,in_dims", [("cart", 9, 3), ("polar", 9, 3), ("cart", 13, 7), ("polar", 13, 7)]
)
def test_shape(self, kernel_type, ps, in_dims, device):
inp = torch.ones(1, in_dims, ps, ps).to(device)
ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=ps, in_dims=in_dims).to(device)
out = ese(inp)
- d_ = 9 if kernel_type == 'cart' else 25
+ d_ = 9 if kernel_type == "cart" else 25
assert out.shape == (1, d_ * in_dims)
@pytest.mark.parametrize(
- "kernel_type,bs", [('cart', 1), ('cart', 5), ('cart', 13), ('polar', 1), ('polar', 5), ('polar', 13)]
+ "kernel_type,bs", [("cart", 1), ("cart", 5), ("cart", 13), ("polar", 1), ("polar", 5), ("polar", 13)]
)
def test_batch_shape(self, kernel_type, bs, device):
inp = torch.ones(bs, 7, 15, 15).to(device)
ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=15, in_dims=7).to(device)
out = ese(inp)
- d_ = 9 if kernel_type == 'cart' else 25
+ d_ = 9 if kernel_type == "cart" else 25
assert out.shape == (bs, d_ * 7)
- @pytest.mark.parametrize("kernel_type", ['cart', 'polar'])
+ @pytest.mark.parametrize("kernel_type", ["cart", "polar"])
def test_print(self, kernel_type, device):
ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=15, in_dims=7).to(device)
ese.__repr__()
@@ -234,19 +234,19 @@ class TestExplicitSpacialEncoding:
def test_toy(self, device):
inp = torch.ones(1, 2, 6, 6).to(device).float()
inp[0, 0, :, :] = 0
- cart_ese = ExplicitSpacialEncoding(kernel_type='cart', fmap_size=6, in_dims=2).to(device)
+ cart_ese = ExplicitSpacialEncoding(kernel_type="cart", fmap_size=6, in_dims=2).to(device)
out = cart_ese(inp)
out_part = out[:, :9]
expected = torch.zeros_like(out_part).to(device)
assert_close(out_part, expected, atol=1e-3, rtol=1e-3)
- polar_ese = ExplicitSpacialEncoding(kernel_type='polar', fmap_size=6, in_dims=2).to(device)
+ polar_ese = ExplicitSpacialEncoding(kernel_type="polar", fmap_size=6, in_dims=2).to(device)
out = polar_ese(inp)
out_part = out[:, :25]
expected = torch.zeros_like(out_part).to(device)
assert_close(out_part, expected, atol=1e-3, rtol=1e-3)
- @pytest.mark.parametrize("kernel_type", ['cart', 'polar'])
+ @pytest.mark.parametrize("kernel_type", ["cart", "polar"])
def test_gradcheck(self, kernel_type, device):
batch_size, channels, ps = 1, 2, 13
patches = torch.rand(batch_size, channels, ps, ps).to(device)
@@ -266,10 +266,10 @@ class TestExplicitSpacialEncoding:
B, C, H, W = 2, 2, 13, 13
patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
model = (
- ExplicitSpacialEncoding(kernel_type='cart', fmap_size=W, in_dims=2).to(patches.device, patches.dtype).eval()
+ ExplicitSpacialEncoding(kernel_type="cart", fmap_size=W, in_dims=2).to(patches.device, patches.dtype).eval()
)
model_jit = torch.jit.script(
- ExplicitSpacialEncoding(kernel_type='cart', fmap_size=W, in_dims=2).to(patches.device, patches.dtype).eval()
+ ExplicitSpacialEncoding(kernel_type="cart", fmap_size=W, in_dims=2).to(patches.device, patches.dtype).eval()
)
assert_close(model(patches), model_jit(patches))
@@ -278,16 +278,16 @@ class TestWhitening:
@pytest.mark.parametrize(
"kernel_type,xform,output_dims",
[
- ('cart', None, 3),
- ('polar', None, 3),
- ('cart', 'lw', 7),
- ('polar', 'lw', 7),
- ('cart', 'pca', 9),
- ('polar', 'pca', 9),
+ ("cart", None, 3),
+ ("polar", None, 3),
+ ("cart", "lw", 7),
+ ("polar", "lw", 7),
+ ("cart", "pca", 9),
+ ("polar", "pca", 9),
],
)
def test_shape(self, kernel_type, xform, output_dims, device):
- in_dims = 63 if kernel_type == 'cart' else 175
+ in_dims = 63 if kernel_type == "cart" else 175
wh = Whitening(xform=xform, whitening_model=None, in_dims=in_dims, output_dims=output_dims).to(device)
inp = torch.ones(1, in_dims).to(device)
out = wh(inp)
@@ -295,17 +295,17 @@ class TestWhitening:
@pytest.mark.parametrize("bs", [1, 3, 7])
def test_batch_shape(self, bs, device):
- wh = Whitening(xform='lw', whitening_model=None, in_dims=175, output_dims=128).to(device)
+ wh = Whitening(xform="lw", whitening_model=None, in_dims=175, output_dims=128).to(device)
inp = torch.ones(bs, 175).to(device)
out = wh(inp)
assert out.shape == (bs, 128)
def test_print(self, device):
- wh = Whitening(xform='lw', whitening_model=None, in_dims=175, output_dims=128).to(device)
+ wh = Whitening(xform="lw", whitening_model=None, in_dims=175, output_dims=128).to(device)
wh.__repr__()
def test_toy(self, device):
- wh = Whitening(xform='lw', whitening_model=None, in_dims=175, output_dims=175).to(device)
+ wh = Whitening(xform="lw", whitening_model=None, in_dims=175, output_dims=175).to(device)
inp = torch.ones(1, 175).to(device).float()
out = wh(inp)
expected = torch.ones_like(inp).to(device) * 0.0756
@@ -317,7 +317,7 @@ class TestWhitening:
patches = utils.tensor_to_gradcheck_var(patches) # to var
def whitening_describe(patches, in_dims=175):
- wh = Whitening(xform='lw', whitening_model=None, in_dims=in_dims).double()
+ wh = Whitening(xform="lw", whitening_model=None, in_dims=in_dims).double()
wh.to(device)
return wh(patches.double())
@@ -327,18 +327,18 @@ class TestWhitening:
def test_jit(self, device, dtype):
batch_size, in_dims = 1, 175
patches = torch.rand(batch_size, in_dims).to(device)
- model = Whitening(xform='lw', whitening_model=None, in_dims=in_dims).to(patches.device, patches.dtype).eval()
+ model = Whitening(xform="lw", whitening_model=None, in_dims=in_dims).to(patches.device, patches.dtype).eval()
model_jit = torch.jit.script(
- Whitening(xform='lw', whitening_model=None, in_dims=in_dims).to(patches.device, patches.dtype).eval()
+ Whitening(xform="lw", whitening_model=None, in_dims=in_dims).to(patches.device, patches.dtype).eval()
)
assert_close(model(patches), model_jit(patches))
class TestMKDDescriptor:
- dims = {'cart': 63, 'polar': 175, 'concat': 238}
+ dims = {"cart": 63, "polar": 175, "concat": 238}
@pytest.mark.parametrize(
- "ps,kernel_type", [(9, 'concat'), (9, 'cart'), (9, 'polar'), (32, 'concat'), (32, 'cart'), (32, 'polar')]
+ "ps,kernel_type", [(9, "concat"), (9, "cart"), (9, "polar"), (32, "concat"), (32, "cart"), (32, "polar")]
)
def test_shape(self, ps, kernel_type, device):
mkd = MKDDescriptor(patch_size=ps, kernel_type=kernel_type, whitening=None).to(device)
@@ -349,12 +349,12 @@ class TestMKDDescriptor:
@pytest.mark.parametrize(
"ps,kernel_type,whitening",
[
- (9, 'concat', 'lw'),
- (9, 'cart', 'lw'),
- (9, 'polar', 'lw'),
- (9, 'concat', 'pcawt'),
- (9, 'cart', 'pcawt'),
- (9, 'polar', 'pcawt'),
+ (9, "concat", "lw"),
+ (9, "cart", "lw"),
+ (9, "polar", "lw"),
+ (9, "concat", "pcawt"),
+ (9, "cart", "pcawt"),
+ (9, "polar", "pcawt"),
],
)
def test_whitened_shape(self, ps, kernel_type, whitening, device):
@@ -366,32 +366,32 @@ class TestMKDDescriptor:
@pytest.mark.parametrize("bs", [1, 3, 7])
def test_batch_shape(self, bs, device):
- mkd = MKDDescriptor(patch_size=19, kernel_type='concat', whitening=None).to(device)
+ mkd = MKDDescriptor(patch_size=19, kernel_type="concat", whitening=None).to(device)
inp = torch.ones(bs, 1, 19, 19).to(device)
out = mkd(inp)
assert out.shape == (bs, 238)
def test_print(self, device):
- mkd = MKDDescriptor(patch_size=32, whitening='lw', training_set='liberty', output_dims=128).to(device)
+ mkd = MKDDescriptor(patch_size=32, whitening="lw", training_set="liberty", output_dims=128).to(device)
mkd.__repr__()
def test_toy(self, device):
inp = torch.ones(1, 1, 6, 6).to(device).float()
inp[0, 0, :, :] = 0
- mkd = MKDDescriptor(patch_size=6, kernel_type='concat', whitening=None).to(device)
+ mkd = MKDDescriptor(patch_size=6, kernel_type="concat", whitening=None).to(device)
out = mkd(inp)
out_part = out[0, -28:]
expected = torch.zeros_like(out_part).to(device)
assert_close(out_part, expected, atol=1e-3, rtol=1e-3)
- @pytest.mark.parametrize("whitening", [None, 'lw', 'pca'])
+ @pytest.mark.parametrize("whitening", [None, "lw", "pca"])
def test_gradcheck(self, whitening, device):
batch_size, channels, ps = 1, 1, 19
patches = torch.rand(batch_size, channels, ps, ps).to(device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
def mkd_describe(patches, patch_size=19):
- mkd = MKDDescriptor(patch_size=patch_size, kernel_type='concat', whitening=whitening).double()
+ mkd = MKDDescriptor(patch_size=patch_size, kernel_type="concat", whitening=whitening).double()
mkd.to(device)
return mkd(patches.double())
@@ -402,8 +402,8 @@ class TestMKDDescriptor:
def test_jit(self, device, dtype):
batch_size, channels, ps = 1, 1, 19
patches = torch.rand(batch_size, channels, ps, ps).to(device)
- kt = 'concat'
- wt = 'lw'
+ kt = "concat"
+ wt = "lw"
model = MKDDescriptor(patch_size=ps, kernel_type=kt, whitening=wt).to(patches.device, patches.dtype).eval()
model_jit = torch.jit.script(
MKDDescriptor(patch_size=ps, kernel_type=kt, whitening=wt).to(patches.device, patches.dtype).eval()
@@ -412,9 +412,9 @@ class TestMKDDescriptor:
class TestSimpleKD:
- dims = {'cart': 63, 'polar': 175}
+ dims = {"cart": 63, "polar": 175}
- @pytest.mark.parametrize("ps,kernel_type", [(9, 'cart'), (9, 'polar'), (32, 'cart'), (32, 'polar')])
+ @pytest.mark.parametrize("ps,kernel_type", [(9, "cart"), (9, "polar"), (32, "cart"), (32, "polar")])
def test_shape(self, ps, kernel_type, device):
skd = SimpleKD(patch_size=ps, kernel_type=kernel_type).to(device)
inp = torch.ones(1, 1, ps, ps).to(device)
@@ -423,13 +423,13 @@ class TestSimpleKD:
@pytest.mark.parametrize("bs", [1, 3, 7])
def test_batch_shape(self, bs, device):
- skd = SimpleKD(patch_size=19, kernel_type='polar').to(device)
+ skd = SimpleKD(patch_size=19, kernel_type="polar").to(device)
inp = torch.ones(bs, 1, 19, 19).to(device)
out = skd(inp)
assert out.shape == (bs, 128)
def test_print(self, device):
- skd = SimpleKD(patch_size=19, kernel_type='polar').to(device)
+ skd = SimpleKD(patch_size=19, kernel_type="polar").to(device)
skd.__repr__()
def test_gradcheck(self, device):
@@ -438,7 +438,7 @@ class TestSimpleKD:
patches = utils.tensor_to_gradcheck_var(patches) # to var
def skd_describe(patches, patch_size=19):
- skd = SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').double()
+ skd = SimpleKD(patch_size=ps, kernel_type="polar", whitening="lw").double()
skd.to(device)
return skd(patches.double())
diff --git a/test/filters/test_bilateral.py b/test/filters/test_bilateral.py
index af18fa6d8..9f789b950 100644
--- a/test/filters/test_bilateral.py
+++ b/test/filters/test_bilateral.py
@@ -38,11 +38,11 @@ class TestBilateralBlur(BaseTester):
def test_exception(self):
with pytest.raises(Exception) as errinfo:
bilateral_blur(torch.rand(1, 1, 5, 5), 3, 1, 1)
- assert 'Not a Tensor type. Go' in str(errinfo)
+ assert "Not a Tensor type. Go" in str(errinfo)
with pytest.raises(ValueError) as errinfo:
bilateral_blur(torch.rand(1, 1, 5, 5), 3, 0.1, (1, 1), color_distance_type="l3")
- assert 'color_distance_type only acceps l1 or l2' in str(errinfo)
+ assert "color_distance_type only acceps l1 or l2" in str(errinfo)
def test_noncontiguous(self, device, dtype):
batch_size = 3
@@ -77,8 +77,8 @@ class TestBilateralBlur(BaseTester):
op_module = BilateralBlur(*params)
self.assert_close(op_module(img), op(img, *params))
- @pytest.mark.parametrize('kernel_size', [5, (5, 7)])
- @pytest.mark.parametrize('color_distance_type', ["l1", "l2"])
+ @pytest.mark.parametrize("kernel_size", [5, (5, 7)])
+ @pytest.mark.parametrize("color_distance_type", ["l1", "l2"])
def test_dynamo(self, kernel_size, color_distance_type, device, dtype, torch_optimizer):
inpt = torch.ones(2, 3, 8, 8, device=device, dtype=dtype)
op = BilateralBlur(kernel_size, 1, (1, 1), color_distance_type=color_distance_type)
@@ -196,19 +196,19 @@ class TestJointBilateralBlur(BaseTester):
with pytest.raises(Exception) as errinfo:
joint_bilateral_blur(inp, guide, 3, 1, 1)
- assert 'Not a Tensor type. Go' in str(errinfo)
+ assert "Not a Tensor type. Go" in str(errinfo)
with pytest.raises(Exception) as errinfo:
joint_bilateral_blur(inp, torch.randn(1, 1, 2, 4), 3, 1, (1, 1))
- assert 'guidance and input should have the same' in str(errinfo)
+ assert "guidance and input should have the same" in str(errinfo)
with pytest.raises(Exception) as errinfo:
joint_bilateral_blur(inp, torch.randn(2, 1, 5, 5), 3, 1, (1, 1))
- assert 'guidance and input should have the same' in str(errinfo)
+ assert "guidance and input should have the same" in str(errinfo)
with pytest.raises(ValueError) as errinfo:
joint_bilateral_blur(inp, guide, 3, 0.1, (1, 1), color_distance_type="l3")
- assert 'color_distance_type only acceps l1 or l2' in str(errinfo)
+ assert "color_distance_type only acceps l1 or l2" in str(errinfo)
def test_noncontiguous(self, device, dtype):
batch_size = 3
@@ -238,8 +238,8 @@ class TestJointBilateralBlur(BaseTester):
op_module = JointBilateralBlur(*params)
self.assert_close(op_module(img, guide), op(img, guide, *params))
- @pytest.mark.parametrize('kernel_size', [5, (5, 7)])
- @pytest.mark.parametrize('color_distance_type', ["l1", "l2"])
+ @pytest.mark.parametrize("kernel_size", [5, (5, 7)])
+ @pytest.mark.parametrize("color_distance_type", ["l1", "l2"])
def test_dynamo(self, kernel_size, color_distance_type, device, dtype, torch_optimizer):
inpt = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)
guide = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)
diff --git a/test/filters/test_blur.py b/test/filters/test_blur.py
index 88bdb293a..ed1a33071 100644
--- a/test/filters/test_blur.py
+++ b/test/filters/test_blur.py
@@ -6,16 +6,16 @@ from kornia.testing import BaseTester, tensor_to_gradcheck_var
class TestBoxBlur(BaseTester):
- @pytest.mark.parametrize('kernel_size', [5, (3, 5)])
+ @pytest.mark.parametrize("kernel_size", [5, (3, 5)])
def test_smoke(self, kernel_size, device, dtype):
inpt = torch.rand(1, 1, 10, 10, device=device, dtype=dtype)
- bb = BoxBlur(kernel_size, 'reflect')
+ bb = BoxBlur(kernel_size, "reflect")
actual = bb(inpt)
assert actual.shape == (1, 1, 10, 10)
- @pytest.mark.parametrize('kernel_size', [5, (3, 5)])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [5, (3, 5)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_separable(self, batch_size, kernel_size, device, dtype):
inpt = torch.randn(batch_size, 3, 10, 10, device=device, dtype=dtype)
out1 = box_blur(inpt, kernel_size, separable=False)
@@ -27,10 +27,10 @@ class TestBoxBlur(BaseTester):
with pytest.raises(Exception) as errinfo:
box_blur(inpt, (1,))
- assert '2D Kernel size should have a length of 2.' in str(errinfo)
+ assert "2D Kernel size should have a length of 2." in str(errinfo)
- @pytest.mark.parametrize('kernel_size', [(3, 3), 5, (5, 7)])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [(3, 3), 5, (5, 7)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_cardinality(self, batch_size, kernel_size, device, dtype):
inp = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)
blur = BoxBlur(kernel_size)
@@ -38,7 +38,7 @@ class TestBoxBlur(BaseTester):
expected = (batch_size, 3, 4, 4)
assert actual.shape == expected
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_kernel_3x3(self, batch_size, device, dtype):
inp = torch.tensor(
[
@@ -62,7 +62,7 @@ class TestBoxBlur(BaseTester):
self.assert_close(actual.sum(), expected)
- @pytest.mark.parametrize('batch_size', [None, 1, 3])
+ @pytest.mark.parametrize("batch_size", [None, 1, 3])
def test_kernel_5x5(self, batch_size, device, dtype):
inp = torch.tensor(
[
@@ -99,8 +99,8 @@ class TestBoxBlur(BaseTester):
self.assert_close(actual[0, 0, 0, 0], torch.tensor((4 + 0 + 4) / 3, device=device, dtype=dtype))
self.assert_close(actual[0, 0, 1, 0], torch.tensor((0 + 4 + 8) / 3, device=device, dtype=dtype))
- @pytest.mark.parametrize('separable', [False, True])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("separable", [False, True])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_noncontiguous(self, batch_size, separable, device, dtype):
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
@@ -108,16 +108,16 @@ class TestBoxBlur(BaseTester):
assert actual.is_contiguous()
- @pytest.mark.parametrize('kernel_size', [(3, 3), 5, (5, 7)])
+ @pytest.mark.parametrize("kernel_size", [(3, 3), 5, (5, 7)])
def test_gradcheck(self, kernel_size, device, dtype):
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = tensor_to_gradcheck_var(img) # to var
- fast_mode = 'cpu' in str(device) # Disable fast mode for GPU
+ fast_mode = "cpu" in str(device) # Disable fast mode for GPU
self.gradcheck(box_blur, (img, kernel_size), fast_mode=fast_mode)
- @pytest.mark.parametrize('kernel_size', [(3, 3), 5, (5, 7)])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [(3, 3), 5, (5, 7)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_module(self, kernel_size, batch_size, device, dtype):
op = box_blur
op_module = BoxBlur
@@ -128,9 +128,9 @@ class TestBoxBlur(BaseTester):
self.assert_close(actual, expected)
- @pytest.mark.parametrize('separable', [False, True])
- @pytest.mark.parametrize('kernel_size', [5, (5, 7)])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("separable", [False, True])
+ @pytest.mark.parametrize("kernel_size", [5, (5, 7)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_dynamo(self, batch_size, kernel_size, separable, device, dtype, torch_optimizer):
inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
op = BoxBlur(kernel_size, separable=separable)
diff --git a/test/filters/test_blur_pool.py b/test/filters/test_blur_pool.py
index 643cbc4e6..baf7f258c 100644
--- a/test/filters/test_blur_pool.py
+++ b/test/filters/test_blur_pool.py
@@ -13,8 +13,8 @@ from kornia.testing import BaseTester, tensor_to_gradcheck_var
class TestMaxBlurPool(BaseTester):
- @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
- @pytest.mark.parametrize('ceil_mode', [True, False])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("ceil_mode", [True, False])
def test_smoke(self, kernel_size, ceil_mode, device, dtype):
inpt = torch.rand(1, 1, 10, 10, device=device, dtype=dtype)
actual = MaxBlurPool2D(kernel_size, ceil_mode=ceil_mode)(inpt)
@@ -22,8 +22,8 @@ class TestMaxBlurPool(BaseTester):
assert actual.shape == (1, 1, 5, 5)
@pytest.mark.parametrize("ceil_mode", [True, False])
- @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_cardinality(self, batch_size, kernel_size, ceil_mode, device, dtype):
inpt = torch.zeros(batch_size, 4, 4, 8, device=device, dtype=dtype)
blur = MaxBlurPool2D(kernel_size, ceil_mode=ceil_mode)
@@ -33,9 +33,9 @@ class TestMaxBlurPool(BaseTester):
inpt = torch.rand(1, 1, 3, 3)
with pytest.raises(Exception) as errinfo:
MaxBlurPool2D((3, 5))(inpt)
- assert 'Invalid kernel shape. Expect CxC_outxNxN' in str(errinfo)
+ assert "Invalid kernel shape. Expect CxC_outxNxN" in str(errinfo)
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_noncontiguous(self, batch_size, device, dtype):
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
@@ -49,8 +49,8 @@ class TestMaxBlurPool(BaseTester):
img = tensor_to_gradcheck_var(img) # to var
self.gradcheck(max_blur_pool2d, (img, 3))
- @pytest.mark.parametrize('kernel_size', [(3, 3), 5])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [(3, 3), 5])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_module(self, kernel_size, batch_size, device, dtype):
op = max_blur_pool2d
op_module = MaxBlurPool2D
@@ -60,9 +60,9 @@ class TestMaxBlurPool(BaseTester):
expected = op(img, kernel_size)
self.assert_close(actual, expected)
- @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
- @pytest.mark.parametrize('batch_size', [1, 2])
- @pytest.mark.parametrize('ceil_mode', [True, False])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ @pytest.mark.parametrize("ceil_mode", [True, False])
def test_dynamo(self, batch_size, kernel_size, ceil_mode, device, dtype, torch_optimizer):
inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
op = MaxBlurPool2D(kernel_size, ceil_mode=ceil_mode)
@@ -72,17 +72,17 @@ class TestMaxBlurPool(BaseTester):
class TestBlurPool(BaseTester):
- @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
- @pytest.mark.parametrize('stride', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("stride", [1, 2])
def test_smoke(self, kernel_size, stride, device, dtype):
inpt = torch.rand(1, 1, 10, 10, device=device, dtype=dtype)
actual = BlurPool2D(kernel_size, stride=stride)(inpt)
expected = (1, 1, int(10 / stride), int(10 / stride))
assert actual.shape == expected
- @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
- @pytest.mark.parametrize('batch_size', [1, 2])
- @pytest.mark.parametrize('stride', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ @pytest.mark.parametrize("stride", [1, 2])
def test_cardinality(self, batch_size, kernel_size, stride, device, dtype):
inpt = torch.zeros(batch_size, 4, 4, 8, device=device, dtype=dtype)
actual = BlurPool2D(kernel_size, stride=stride)(inpt)
@@ -93,9 +93,9 @@ class TestBlurPool(BaseTester):
inpt = torch.rand(1, 1, 3, 3)
with pytest.raises(Exception) as errinfo:
BlurPool2D((3, 5))(inpt)
- assert 'Invalid kernel shape. Expect CxC_(out, None)xNxN' in str(errinfo)
+ assert "Invalid kernel shape. Expect CxC_(out, None)xNxN" in str(errinfo)
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_noncontiguous(self, batch_size, device, dtype):
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
@@ -108,9 +108,9 @@ class TestBlurPool(BaseTester):
img = tensor_to_gradcheck_var(img) # to var
self.gradcheck(blur_pool2d, (img, 3))
- @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
- @pytest.mark.parametrize('batch_size', [1, 2])
- @pytest.mark.parametrize('stride', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ @pytest.mark.parametrize("stride", [1, 2])
def test_module(self, batch_size, kernel_size, stride, device, dtype):
op = blur_pool2d
op_module = BlurPool2D
@@ -120,9 +120,9 @@ class TestBlurPool(BaseTester):
expected = op(img, kernel_size)
self.assert_close(actual, expected)
- @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
- @pytest.mark.parametrize('batch_size', [1, 2])
- @pytest.mark.parametrize('stride', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ @pytest.mark.parametrize("stride", [1, 2])
def test_dynamo(self, batch_size, kernel_size, stride, device, dtype, torch_optimizer):
inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
op = BlurPool2D(kernel_size, stride=stride)
@@ -132,17 +132,17 @@ class TestBlurPool(BaseTester):
class TestEdgeAwareBlurPool(BaseTester):
- @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
- @pytest.mark.parametrize('batch_size', [1, 2])
- @pytest.mark.parametrize('edge_threshold', [1.25, 2.5])
- @pytest.mark.parametrize('edge_dilation_kernel_size', [3, 5])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ @pytest.mark.parametrize("edge_threshold", [1.25, 2.5])
+ @pytest.mark.parametrize("edge_dilation_kernel_size", [3, 5])
def test_smoke(self, kernel_size, batch_size, edge_threshold, edge_dilation_kernel_size, device, dtype):
inpt = torch.zeros(batch_size, 3, 8, 8, device=device, dtype=dtype)
actual = edge_aware_blur_pool2d(inpt, kernel_size, edge_threshold, edge_dilation_kernel_size)
assert actual.shape == inpt.shape
- @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_cardinality(self, kernel_size, batch_size, device, dtype):
inp = torch.zeros(batch_size, 3, 8, 8, device=device, dtype=dtype)
blur = edge_aware_blur_pool2d(inp, kernel_size=kernel_size)
@@ -152,21 +152,21 @@ class TestEdgeAwareBlurPool(BaseTester):
with pytest.raises(Exception) as errinfo:
inpt = torch.rand(1, 3, 3)
edge_aware_blur_pool2d(inpt, 3)
- assert "shape must be [[\'B\', \'C\', \'H\', \'W\']]" in str(errinfo)
+ assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo)
with pytest.raises(Exception) as errinfo:
inpt = torch.rand(1, 1, 3, 3)
edge_aware_blur_pool2d(inpt, 3, edge_threshold=-1)
assert "edge threshold should be positive, but got" in str(errinfo)
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_noncontiguous(self, batch_size, device, dtype):
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
actual = edge_aware_blur_pool2d(inp, 3)
assert actual.is_contiguous()
- @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_module(self, kernel_size, batch_size, device, dtype):
op = edge_aware_blur_pool2d
op_module = EdgeAwareBlurPool2D
@@ -187,8 +187,8 @@ class TestEdgeAwareBlurPool(BaseTester):
blur = edge_aware_blur_pool2d(img, kernel_size=3, edge_threshold=32.0)
self.assert_close(img, blur)
- @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_dynamo(self, batch_size, kernel_size, device, dtype, torch_optimizer):
op = edge_aware_blur_pool2d
inpt = torch.rand(batch_size, 3, 4, 5, device=device, dtype=dtype)
diff --git a/test/filters/test_canny.py b/test/filters/test_canny.py
index 56bdbef88..33465dc79 100644
--- a/test/filters/test_canny.py
+++ b/test/filters/test_canny.py
@@ -7,11 +7,11 @@ from kornia.utils._compat import torch_version
class TestCanny(BaseTester):
- @pytest.mark.parametrize('batch_size', [1, 2])
- @pytest.mark.parametrize('kernel_size', [3, (5, 7)])
- @pytest.mark.parametrize('sigma', [(1.5, 1.0), (2.5, 0.5)])
- @pytest.mark.parametrize('hysteresis', [False, True])
- @pytest.mark.parametrize('low_threshold,high_threshold', [(0.1, 0.2), (0.3, 0.5)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 7)])
+ @pytest.mark.parametrize("sigma", [(1.5, 1.0), (2.5, 0.5)])
+ @pytest.mark.parametrize("hysteresis", [False, True])
+ @pytest.mark.parametrize("low_threshold,high_threshold", [(0.1, 0.2), (0.3, 0.5)])
def test_smoke(self, batch_size, kernel_size, sigma, hysteresis, low_threshold, high_threshold, device, dtype):
inp = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)
@@ -21,7 +21,7 @@ class TestCanny(BaseTester):
assert actual[0].shape == (batch_size, 1, 4, 4)
assert actual[1].shape == (batch_size, 1, 4, 4)
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_cardinality(self, batch_size, device, dtype):
inp = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)
@@ -34,26 +34,26 @@ class TestCanny(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(Exception) as errinfo:
Canny(0.3, 0.2)
- assert 'low_threshold should be smaller than the high_threshold' in str(errinfo)
+ assert "low_threshold should be smaller than the high_threshold" in str(errinfo)
with pytest.raises(Exception) as errinfo:
Canny(-2, 0.3)
- assert 'Invalid low threshold.' in str(errinfo)
+ assert "Invalid low threshold." in str(errinfo)
with pytest.raises(Exception) as errinfo:
Canny(0.1, 3)
- assert 'Invalid high threshold.' in str(errinfo)
+ assert "Invalid high threshold." in str(errinfo)
with pytest.raises(Exception) as errinfo:
canny(1)
- assert 'Not a Tensor type' in str(errinfo)
+ assert "Not a Tensor type" in str(errinfo)
inp = torch.zeros(3, 4, 4, device=device, dtype=dtype)
with pytest.raises(Exception) as errinfo:
canny(inp)
- assert 'shape must be [[\'B\', \'C\', \'H\', \'W\']]' in str(errinfo)
+ assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo)
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_noncontiguous(self, batch_size, device, dtype):
inp = torch.rand(batch_size, 3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
@@ -295,9 +295,9 @@ class TestCanny(BaseTester):
self.assert_close(actual_magnitude, expected_magnitude)
self.assert_close(actual_edges, expected_edges)
- @pytest.mark.parametrize('kernel_size', [5, (5, 7)])
- @pytest.mark.parametrize('batch_size', [1, 2])
- @pytest.mark.skipif(torch_version() in {'2.0.0', '2.0.1'}, reason='Not working on 2.0')
+ @pytest.mark.parametrize("kernel_size", [5, (5, 7)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ @pytest.mark.skipif(torch_version() in {"2.0.0", "2.0.1"}, reason="Not working on 2.0")
def test_dynamo(self, batch_size, kernel_size, device, dtype, torch_optimizer):
inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
op = Canny(kernel_size=kernel_size)
diff --git a/test/filters/test_filters.py b/test/filters/test_filters.py
index 071da6b3e..5cdf29776 100644
--- a/test/filters/test_filters.py
+++ b/test/filters/test_filters.py
@@ -7,7 +7,7 @@ from kornia.utils._compat import torch_version_le
class TestFilter2D(BaseTester):
- @pytest.mark.parametrize("border_type", ['constant', 'reflect', 'replicate', 'circular'])
+ @pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])
@pytest.mark.parametrize("normalized", [True, False])
@pytest.mark.parametrize("padding", ["same", "valid"])
def test_smoke(self, border_type, normalized, padding, device, dtype):
@@ -29,7 +29,7 @@ class TestFilter2D(BaseTester):
sample = torch.ones(B, 3, 7, 8, device=device, dtype=dtype)
b, c, h, w = sample.shape
out = filter2d(sample, kernel, padding=padding)
- if padding == 'same':
+ if padding == "same":
assert out.shape == (b, c, h, w)
else:
assert out.shape == (b, c, h - height + 1, w - width + 1)
@@ -68,9 +68,9 @@ class TestFilter2D(BaseTester):
device=device,
dtype=dtype,
)
- out_corr = filter2d(inp, kernel, behaviour='corr')
+ out_corr = filter2d(inp, kernel, behaviour="corr")
assert_close(out_corr, corr_expected)
- out_conv = filter2d(inp, kernel, behaviour='conv')
+ out_conv = filter2d(inp, kernel, behaviour="conv")
assert_close(out_conv, conv_expected)
def test_exception(self):
@@ -78,27 +78,27 @@ class TestFilter2D(BaseTester):
inpt = torch.ones(1, 1, 1, 1)
with pytest.raises(TypeError) as errinfo:
filter2d(1, k)
- assert 'Not a Tensor type.' in str(errinfo)
+ assert "Not a Tensor type." in str(errinfo)
with pytest.raises(TypeError) as errinfo:
filter2d(inpt, 1)
- assert 'Not a Tensor type.' in str(errinfo)
+ assert "Not a Tensor type." in str(errinfo)
with pytest.raises(TypeError) as errinfo:
filter2d(torch.ones(1), k)
- assert 'shape must be [[\'B\', \'C\', \'H\', \'W\']]' in str(errinfo)
+ assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
filter2d(inpt, torch.ones(1))
- assert 'shape must be [[\'B\', \'H\', \'W\']]' in str(errinfo)
+ assert "shape must be [['B', 'H', 'W']]" in str(errinfo)
with pytest.raises(Exception) as errinfo:
- filter2d(inpt, k, border_type='a')
- assert 'Invalid border, gotcha a. Ex' in str(errinfo)
+ filter2d(inpt, k, border_type="a")
+ assert "Invalid border, gotcha a. Ex" in str(errinfo)
with pytest.raises(Exception) as errinfo:
- filter2d(inpt, k, padding='a')
- assert 'Invalid padding mode, gotcha a. Ex' in str(errinfo)
+ filter2d(inpt, k, padding="a")
+ assert "Invalid padding mode, gotcha a. Ex" in str(errinfo)
@pytest.mark.parametrize("padding", ["same", "valid"])
def test_mean_filter(self, padding, device, dtype):
@@ -121,7 +121,7 @@ class TestFilter2D(BaseTester):
actual = filter2d(sample, kernel, padding=padding)
- if padding == 'same':
+ if padding == "same":
expected_same = torch.tensor(
[
[
@@ -167,7 +167,7 @@ class TestFilter2D(BaseTester):
actual = filter2d(sample, kernel, padding=padding)
- if padding == 'same':
+ if padding == "same":
expected_same = torch.tensor(
[
[
@@ -213,7 +213,7 @@ class TestFilter2D(BaseTester):
nv: float = 5.0 / 9 # normalization value
actual = filter2d(sample, kernel, normalized=True, padding=padding)
- if padding == 'same':
+ if padding == "same":
expected_same = torch.tensor(
[
[
@@ -259,7 +259,7 @@ class TestFilter2D(BaseTester):
actual = filter2d(sample, kernel, padding=padding)
- if padding == 'same':
+ if padding == "same":
expected_same = torch.tensor(
[
[
@@ -321,7 +321,7 @@ class TestFilter2D(BaseTester):
dtype=dtype,
)
- actual = filter2d(sample_, kernel, padding='same', border_type='constant')
+ actual = filter2d(sample_, kernel, padding="same", border_type="constant")
self.assert_close(actual, expected_same)
@pytest.mark.parametrize("padding", ["same", "valid"])
@@ -353,7 +353,7 @@ class TestFilter2D(BaseTester):
kernel = tensor_to_gradcheck_var(kernel) # to var
self.gradcheck(filter2d, (sample, kernel), nondet_tol=1e-8)
- @pytest.mark.skip(reason='filter2d do not have a module')
+ @pytest.mark.skip(reason="filter2d do not have a module")
def test_module(self):
...
@@ -372,11 +372,11 @@ class TestFilter2D(BaseTester):
class TestFilter3D(BaseTester):
- @pytest.mark.parametrize("border_type", ['constant', 'reflect', 'replicate', 'circular'])
+ @pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])
@pytest.mark.parametrize("normalized", [True, False])
def test_smoke(self, border_type, normalized, device, dtype):
- if torch_version_le(1, 9, 1) and border_type == 'reflect':
- pytest.skip(reason='Reflect border is not implemented for 3D on torch < 1.9.1')
+ if torch_version_le(1, 9, 1) and border_type == "reflect":
+ pytest.skip(reason="Reflect border is not implemented for 3D on torch < 1.9.1")
kernel = torch.rand(1, 3, 3, 3, device=device, dtype=dtype)
inpt = torch.ones(1, 1, 6, 7, 8, device=device, dtype=dtype)
@@ -396,23 +396,23 @@ class TestFilter3D(BaseTester):
inpt = torch.ones(1, 1, 1, 1, 1)
with pytest.raises(TypeError) as errinfo:
filter3d(1, k)
- assert 'Not a Tensor type.' in str(errinfo)
+ assert "Not a Tensor type." in str(errinfo)
with pytest.raises(TypeError) as errinfo:
filter3d(inpt, 1)
- assert 'Not a Tensor type.' in str(errinfo)
+ assert "Not a Tensor type." in str(errinfo)
with pytest.raises(TypeError) as errinfo:
filter3d(torch.ones(1), k)
- assert 'shape must be [[\'B\', \'C\', \'D\', \'H\', \'W\']]' in str(errinfo)
+ assert "shape must be [['B', 'C', 'D', 'H', 'W']]" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
filter3d(inpt, torch.ones(1))
- assert 'shape must be [[\'B\', \'D\', \'H\', \'W\']]' in str(errinfo)
+ assert "shape must be [['B', 'D', 'H', 'W']]" in str(errinfo)
with pytest.raises(Exception) as errinfo:
- filter3d(inpt, k, border_type='a')
- assert 'Invalid border, gotcha a. Ex' in str(errinfo)
+ filter3d(inpt, k, border_type="a")
+ assert "Invalid border, gotcha a. Ex" in str(errinfo)
def test_mean_filter(self, device, dtype):
kernel = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)
@@ -713,7 +713,7 @@ class TestFilter3D(BaseTester):
kernel = tensor_to_gradcheck_var(kernel) # to var
self.gradcheck(filter3d, (sample, kernel), nondet_tol=1e-8)
- @pytest.mark.skip(reason='filter3d do not have a module')
+ @pytest.mark.skip(reason="filter3d do not have a module")
def test_module(self):
...
@@ -758,7 +758,7 @@ class TestDexiNed:
out = model(img)[-1]
assert_close(out, expect, atol=3e-4, rtol=3e-4)
- @pytest.mark.skip(reason='DexiNed do not compile with dynamo.')
+ @pytest.mark.skip(reason="DexiNed do not compile with dynamo.")
def test_dynamo(self, device, dtype, torch_optimizer):
# TODO: update the dexined to be possible to use with dynamo
inpt = torch.rand(2, 3, 32, 32, device=device, dtype=dtype)
diff --git a/test/filters/test_gaussian.py b/test/filters/test_gaussian.py
index e86af3673..19dec5f0e 100644
--- a/test/filters/test_gaussian.py
+++ b/test/filters/test_gaussian.py
@@ -170,12 +170,12 @@ class TestGaussianBlur2d(BaseTester):
inpt = torch.rand(B, C, H, W, device=device, dtype=dtype)
sigma_tensor = torch.rand(B, 2, device=device, dtype=dtype)
- actual_A = gaussian_blur2d(inpt, kernel_size, sigma_tensor, 'reflect', separable)
+ actual_A = gaussian_blur2d(inpt, kernel_size, sigma_tensor, "reflect", separable)
assert isinstance(actual_A, torch.Tensor)
assert actual_A.shape == shape
sigma = tuple(sigma_tensor[0, ...].cpu().numpy().tolist())
- actual_B = gaussian_blur2d(inpt, kernel_size, sigma, 'reflect', separable)
+ actual_B = gaussian_blur2d(inpt, kernel_size, sigma, "reflect", separable)
assert isinstance(actual_B, torch.Tensor)
assert actual_B.shape == shape
@@ -194,12 +194,12 @@ class TestGaussianBlur2d(BaseTester):
# input should be a tensor
with pytest.raises(Exception) as errinfo:
gaussian_blur2d(1, 3, (1.0, 1.0))
- assert 'Not a Tensor type. Go' in str(errinfo)
+ assert "Not a Tensor type. Go" in str(errinfo)
# Sigma should be a tuple or a tensor
with pytest.raises(Exception) as errinfo:
gaussian_blur2d(torch.rand(1, 1, 1, 1), 3, 1.0)
- assert 'Not a Tensor type. Go' in str(errinfo)
+ assert "Not a Tensor type. Go" in str(errinfo)
def test_noncontiguous(self, device, dtype):
batch_size = 3
diff --git a/test/filters/test_guided.py b/test/filters/test_guided.py
index 32e2625b3..333c40f62 100644
--- a/test/filters/test_guided.py
+++ b/test/filters/test_guided.py
@@ -52,11 +52,11 @@ class TestGuidedBlur(BaseTester):
def test_exception(self):
with pytest.raises(Exception) as errinfo:
guided_blur(torch.rand(1, 1, 5, 5), 3, 3, 0.1)
- assert 'Not a Tensor type. Go' in str(errinfo)
+ assert "Not a Tensor type. Go" in str(errinfo)
with pytest.raises(Exception) as errinfo:
guided_blur(torch.rand(1, 1, 5, 5), torch.rand(2, 1, 5, 5), 3, 0.1)
- assert 'same batch size and spatial dimensions' in str(errinfo)
+ assert "same batch size and spatial dimensions" in str(errinfo)
def test_noncontiguous(self, device, dtype):
batch_size = 3
@@ -90,13 +90,13 @@ class TestGuidedBlur(BaseTester):
self.assert_close(op_module(guide, img), op(guide, img, kernel_size, eps, subsample=subsample))
@pytest.mark.skipif(
- torch_version() == '2.1.0',
+ torch_version() == "2.1.0",
reason=(
"https://github.com/pytorch/pytorch/issues/110696 "
"- Failing with: Argument of Integer should be of numeric type, got s3 + 3."
),
)
- @pytest.mark.parametrize('kernel_size', [5, (5, 7)])
+ @pytest.mark.parametrize("kernel_size", [5, (5, 7)])
@pytest.mark.parametrize("subsample", [1, 2])
def test_dynamo(self, kernel_size, subsample, device, dtype, torch_optimizer):
guide = torch.ones(2, 3, 8, 8, device=device, dtype=dtype)
diff --git a/test/filters/test_laplacian.py b/test/filters/test_laplacian.py
index 47059ceec..8829a2115 100644
--- a/test/filters/test_laplacian.py
+++ b/test/filters/test_laplacian.py
@@ -54,7 +54,7 @@ class TestLaplacian(BaseTester):
@pytest.mark.parametrize("normalized", [True, False])
def test_smoke(self, shape, kernel_size, normalized, device, dtype):
inpt = torch.rand(shape, device=device, dtype=dtype)
- actual = laplacian(inpt, kernel_size, 'reflect', normalized)
+ actual = laplacian(inpt, kernel_size, "reflect", normalized)
assert isinstance(actual, torch.Tensor)
assert actual.shape == shape
@@ -65,7 +65,7 @@ class TestLaplacian(BaseTester):
actual = laplacian(sample, kernel_size)
assert actual.shape == shape
- @pytest.mark.skip(reason='Nothing to test.')
+ @pytest.mark.skip(reason="Nothing to test.")
def test_exception(self):
...
@@ -95,8 +95,8 @@ class TestLaplacian(BaseTester):
img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
self.assert_close(op(img, *params), op_module(img))
- @pytest.mark.parametrize('kernel_size', [5, (5, 7)])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [5, (5, 7)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_dynamo(self, batch_size, kernel_size, device, dtype, torch_optimizer):
inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
op = Laplacian(kernel_size)
diff --git a/test/filters/test_median.py b/test/filters/test_median.py
index dede6fa14..c4e0cdd68 100644
--- a/test/filters/test_median.py
+++ b/test/filters/test_median.py
@@ -11,8 +11,8 @@ class TestMedianBlur(BaseTester):
actual = median_blur(inp, 3)
assert isinstance(actual, torch.Tensor)
- @pytest.mark.parametrize('batch_size', [1, 2])
- @pytest.mark.parametrize('kernel_size', [3, (5, 7)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 7)])
def test_cardinality(self, batch_size, kernel_size, device, dtype):
inp = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)
actual = median_blur(inp, kernel_size)
@@ -21,11 +21,11 @@ class TestMedianBlur(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError) as errinfo:
median_blur(1, 1)
- assert 'Not a Tensor type.' in str(errinfo)
+ assert "Not a Tensor type." in str(errinfo)
with pytest.raises(TypeError) as errinfo:
median_blur(torch.ones(1, 1, device=device, dtype=dtype), 1)
- assert 'shape must be [[\'B\', \'C\', \'H\', \'W\']].' in str(errinfo)
+ assert "shape must be [['B', 'C', 'H', 'W']]." in str(errinfo)
def test_kernel_3x3(self, device, dtype):
inp = torch.tensor(
@@ -96,8 +96,8 @@ class TestMedianBlur(BaseTester):
expected = op(img, kernel_size)
self.assert_close(actual, expected)
- @pytest.mark.parametrize('kernel_size', [5, (5, 7)])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("kernel_size", [5, (5, 7)])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_dynamo(self, batch_size, kernel_size, device, dtype, torch_optimizer):
inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
op = MedianBlur(kernel_size)
diff --git a/test/filters/test_motion.py b/test/filters/test_motion.py
index 883bab3a7..c6623b242 100644
--- a/test/filters/test_motion.py
+++ b/test/filters/test_motion.py
@@ -17,7 +17,7 @@ class TestMotionBlur(BaseTester):
@pytest.mark.parametrize("kernel_size", [3, 5])
@pytest.mark.parametrize("angle", [36.0, 200.0])
@pytest.mark.parametrize("direction", [-0.9, 0.0, 0.9])
- @pytest.mark.parametrize("mode", ['bilinear', 'nearest'])
+ @pytest.mark.parametrize("mode", ["bilinear", "nearest"])
@pytest.mark.parametrize("params_as_tensor", [True, False])
def test_smoke(self, shape, kernel_size, angle, direction, mode, params_as_tensor, device, dtype):
B, C, H, W = shape
@@ -26,7 +26,7 @@ class TestMotionBlur(BaseTester):
if params_as_tensor is True:
angle = torch.tensor([angle], device=device, dtype=dtype).repeat(B)
direction = torch.tensor([direction], device=device, dtype=dtype).repeat(B)
- actual = motion_blur(inpt, kernel_size, angle, direction, 'constant', mode)
+ actual = motion_blur(inpt, kernel_size, angle, direction, "constant", mode)
assert isinstance(actual, torch.Tensor)
assert actual.shape == shape
@@ -41,7 +41,7 @@ class TestMotionBlur(BaseTester):
motion = MotionBlur(ksize, angle, direction)
assert motion(sample).shape == shape
- @pytest.mark.skip(reason='nothing to test')
+ @pytest.mark.skip(reason="nothing to test")
def test_exception(self):
...
@@ -92,8 +92,8 @@ class TestMotionBlur(BaseTester):
self.assert_close(op(img, *params), op_module(img))
- @pytest.mark.skip(reason='After the op be optimized the results are not the same')
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.skip(reason="After the op be optimized the results are not the same")
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_dynamo(self, batch_size, device, dtype, torch_optimizer):
# TODO: FIX op
inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
@@ -108,7 +108,7 @@ class TestMotionBlur3D(BaseTester):
@pytest.mark.parametrize("kernel_size", [3, 5])
@pytest.mark.parametrize("angle", [(36.0, 15.0, 200.0), (200.0, 10.0, 150.0)])
@pytest.mark.parametrize("direction", [-0.9, 0.0, 0.9])
- @pytest.mark.parametrize("mode", ['bilinear', 'nearest'])
+ @pytest.mark.parametrize("mode", ["bilinear", "nearest"])
@pytest.mark.parametrize("params_as_tensor", [True, False])
def test_smoke(self, shape, kernel_size, angle, direction, mode, params_as_tensor, device, dtype):
B, C, D, H, W = shape
@@ -117,7 +117,7 @@ class TestMotionBlur3D(BaseTester):
if params_as_tensor is True:
angle = torch.tensor([angle], device=device, dtype=dtype).expand(B, 3)
direction = torch.tensor([direction], device=device, dtype=dtype).repeat(B)
- actual = motion_blur3d(inpt, kernel_size, angle, direction, 'constant', mode)
+ actual = motion_blur3d(inpt, kernel_size, angle, direction, "constant", mode)
assert isinstance(actual, torch.Tensor)
assert actual.shape == shape
@@ -132,7 +132,7 @@ class TestMotionBlur3D(BaseTester):
motion = MotionBlur3D(ksize, angle, direction)
assert motion(sample).shape == shape
- @pytest.mark.skip(reason='nothing to test')
+ @pytest.mark.skip(reason="nothing to test")
def test_exception(self):
...
@@ -183,8 +183,8 @@ class TestMotionBlur3D(BaseTester):
self.assert_close(op(img, *params), op_module(img))
- @pytest.mark.skip(reason='After the op be optimized the results are not the same')
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.skip(reason="After the op be optimized the results are not the same")
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_dynamo(self, batch_size, device, dtype, torch_optimizer):
# TODO: Fix the operation to works after dynamo optimize
inpt = torch.ones(batch_size, 3, 1, 10, 10, device=device, dtype=dtype)
diff --git a/test/filters/test_sobel.py b/test/filters/test_sobel.py
index 90087b01c..8e81771a2 100644
--- a/test/filters/test_sobel.py
+++ b/test/filters/test_sobel.py
@@ -6,16 +6,16 @@ from kornia.testing import BaseTester, tensor_to_gradcheck_var
class TestSpatialGradient(BaseTester):
- @pytest.mark.parametrize('batch_size', [1, 2])
- @pytest.mark.parametrize('mode', ['sobel', 'diff'])
- @pytest.mark.parametrize('order', [1, 2])
- @pytest.mark.parametrize('normalized', [True, False])
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ @pytest.mark.parametrize("mode", ["sobel", "diff"])
+ @pytest.mark.parametrize("order", [1, 2])
+ @pytest.mark.parametrize("normalized", [True, False])
def test_smoke(self, batch_size, mode, order, normalized, device, dtype):
inpt = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)
actual = SpatialGradient(mode, order, normalized)(inpt)
assert isinstance(actual, torch.Tensor)
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_cardinality(self, batch_size, device, dtype):
inp = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)
assert SpatialGradient()(inp).shape == (batch_size, 3, 2, 4, 4)
@@ -23,11 +23,11 @@ class TestSpatialGradient(BaseTester):
def test_exception(self):
with pytest.raises(TypeError) as errinfo:
spatial_gradient(1)
- assert 'Not a Tensor type' in str(errinfo)
+ assert "Not a Tensor type" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
spatial_gradient(torch.zeros(1))
- assert 'shape must be [[\'B\', \'C\', \'H\', \'W\']]' in str(errinfo)
+ assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo)
def test_edges(self, device, dtype):
inp = torch.tensor(
@@ -164,7 +164,7 @@ class TestSpatialGradient(BaseTester):
dtype=dtype,
)
- edges = spatial_gradient(inp, 'diff', normalized=False)
+ edges = spatial_gradient(inp, "diff", normalized=False)
self.assert_close(edges, expected)
def test_edges_sep_norm(self, device, dtype):
@@ -212,7 +212,7 @@ class TestSpatialGradient(BaseTester):
/ 2.0
)
- edges = spatial_gradient(inp, 'diff', normalized=True)
+ edges = spatial_gradient(inp, "diff", normalized=True)
self.assert_close(edges, expected)
def test_noncontiguous(self, device, dtype):
@@ -239,14 +239,14 @@ class TestSpatialGradient(BaseTester):
actual = op_module(img)
self.assert_close(actual, expected)
- @pytest.mark.parametrize('mode', ['sobel', 'diff'])
- @pytest.mark.parametrize('order', [1, 2])
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("mode", ["sobel", "diff"])
+ @pytest.mark.parametrize("order", [1, 2])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_dynamo(self, batch_size, order, mode, device, dtype, torch_optimizer):
inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
if order == 1 and dtype == torch.float64:
# TODO: FIX order 1 spatial gradient with fp64 on dynamo
- pytest.xfail(reason='Order 1 on spatial gradient may be wrong computed for float64 on dynamo')
+ pytest.xfail(reason="Order 1 on spatial gradient may be wrong computed for float64 on dynamo")
op = SpatialGradient(mode, order)
op_optimized = torch_optimizer(op)
@@ -254,15 +254,15 @@ class TestSpatialGradient(BaseTester):
class TestSpatialGradient3d(BaseTester):
- @pytest.mark.parametrize('batch_size', [1, 2])
- @pytest.mark.parametrize('mode', ['diff']) # TODO: add support to 'sobel'
- @pytest.mark.parametrize('order', [1, 2])
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ @pytest.mark.parametrize("mode", ["diff"]) # TODO: add support to 'sobel'
+ @pytest.mark.parametrize("order", [1, 2])
def test_smoke(self, batch_size, mode, order, device, dtype):
inpt = torch.ones(batch_size, 3, 2, 7, 4, device=device, dtype=dtype)
actual = SpatialGradient3d(mode, order)(inpt)
assert isinstance(actual, torch.Tensor)
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_cardinality(self, batch_size, device, dtype):
inp = torch.zeros(batch_size, 2, 4, 5, 6, device=device, dtype=dtype)
sobel = SpatialGradient3d()
@@ -271,11 +271,11 @@ class TestSpatialGradient3d(BaseTester):
def test_exception(self):
with pytest.raises(TypeError) as errinfo:
spatial_gradient3d(1)
- assert 'Not a Tensor type' in str(errinfo)
+ assert "Not a Tensor type" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
spatial_gradient3d(torch.zeros(1))
- assert 'shape must be [[\'B\', \'C\', \'D\', \'H\', \'W\']]' in str(errinfo)
+ assert "shape must be [['B', 'C', 'D', 'H', 'W']]" in str(errinfo)
def test_edges(self, device, dtype):
inp = torch.tensor(
@@ -396,7 +396,7 @@ class TestSpatialGradient3d(BaseTester):
def test_gradcheck(self, device):
img = torch.rand(1, 1, 1, 3, 4, device=device)
img = tensor_to_gradcheck_var(img) # to var
- fast_mode = 'cpu' in str(device) # disable fast mode on gpu
+ fast_mode = "cpu" in str(device) # disable fast mode on gpu
self.gradcheck(spatial_gradient3d, (img,), fast_mode=fast_mode)
def test_module(self, device, dtype):
@@ -407,8 +407,8 @@ class TestSpatialGradient3d(BaseTester):
actual = op_module(img)
self.assert_close(actual, expected)
- @pytest.mark.parametrize('mode', ['diff'])
- @pytest.mark.parametrize('order', [1, 2])
+ @pytest.mark.parametrize("mode", ["diff"])
+ @pytest.mark.parametrize("order", [1, 2])
def test_dynamo(self, mode, order, device, dtype, torch_optimizer):
inpt = torch.ones(1, 3, 1, 10, 10, device=device, dtype=dtype)
op = SpatialGradient3d(mode, order)
@@ -418,8 +418,8 @@ class TestSpatialGradient3d(BaseTester):
class TestSobel(BaseTester):
- @pytest.mark.parametrize('batch_size', [1, 2])
- @pytest.mark.parametrize('normalized', [True, False])
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ @pytest.mark.parametrize("normalized", [True, False])
def test_smoke(self, batch_size, normalized, device, dtype):
inp = torch.zeros(batch_size, 3, 4, 7, device=device, dtype=dtype)
actual = Sobel()(inp)
@@ -427,7 +427,7 @@ class TestSobel(BaseTester):
assert isinstance(actual, torch.Tensor)
assert actual.shape == (batch_size, 3, 4, 7)
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_cardinality(self, batch_size, device, dtype):
inp = torch.zeros(batch_size, 3, 4, 7, device=device, dtype=dtype)
assert Sobel()(inp).shape == (batch_size, 3, 4, 7)
@@ -435,11 +435,11 @@ class TestSobel(BaseTester):
def test_exception(self):
with pytest.raises(TypeError) as errinfo:
sobel(1)
- assert 'Not a Tensor type' in str(errinfo)
+ assert "Not a Tensor type" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
sobel(torch.zeros(1))
- assert 'shape must be [[\'B\', \'C\', \'H\', \'W\']]' in str(errinfo)
+ assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo)
def test_magnitude(self, device, dtype):
inp = torch.tensor(
@@ -488,7 +488,7 @@ class TestSobel(BaseTester):
assert actual.is_contiguous()
assert actual.shape == (3, 3, 5, 5)
- @pytest.mark.parametrize('normalized', [True, False])
+ @pytest.mark.parametrize("normalized", [True, False])
def test_gradcheck(self, normalized, device):
batch_size, channels, height, width = 1, 1, 3, 4
img = torch.rand(batch_size, channels, height, width, device=device)
@@ -503,11 +503,11 @@ class TestSobel(BaseTester):
actual = op_module(img)
self.assert_close(actual, expected)
- @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_dynamo(self, batch_size, device, dtype, torch_optimizer):
if dtype == torch.float64:
# TODO: investigate sobel for float64 with dynamo
- pytest.xfail(reason='The sobel results can be different after dynamo on fp64')
+ pytest.xfail(reason="The sobel results can be different after dynamo on fp64")
inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
op = Sobel()
op_optimized = torch_optimizer(op)
diff --git a/test/filters/test_unsharp_mask.py b/test/filters/test_unsharp_mask.py
index 85a86d356..46a03cf53 100644
--- a/test/filters/test_unsharp_mask.py
+++ b/test/filters/test_unsharp_mask.py
@@ -15,7 +15,7 @@ class Testunsharp(BaseTester):
sigma = torch.tensor([sigma], device=device, dtype=dtype).repeat(shape[0], 1)
inpt = torch.ones(shape, device=device, dtype=dtype)
- actual = unsharp_mask(inpt, kernel_size, sigma, 'replicate')
+ actual = unsharp_mask(inpt, kernel_size, sigma, "replicate")
assert isinstance(actual, torch.Tensor)
assert actual.shape == shape
@@ -28,7 +28,7 @@ class Testunsharp(BaseTester):
actual = unsharp_mask(inpt, kernel_size, sigma, "replicate")
assert actual.shape == shape
- @pytest.mark.skip(reason='nothing to test')
+ @pytest.mark.skip(reason="nothing to test")
def test_exception(self):
...
diff --git a/test/geometry/calibration/test_undistort.py b/test/geometry/calibration/test_undistort.py
index e44f06cc7..42ffa0c1a 100644
--- a/test/geometry/calibration/test_undistort.py
+++ b/test/geometry/calibration/test_undistort.py
@@ -342,7 +342,7 @@ class TestUndistortImage:
gradcheck(undistort_image, (im, K, distCoeff))
- @pytest.mark.xfail(reason='Some times this seems to random fail')
+ @pytest.mark.xfail(reason="Some times this seems to random fail")
def test_dynamo(self, device, dtype, torch_optimizer):
# TODO: check if `undistort_image` fully support dynamo
im = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)
diff --git a/test/geometry/epipolar/test_common.py b/test/geometry/epipolar/test_common.py
index 558b63cb9..d19c29dd5 100644
--- a/test/geometry/epipolar/test_common.py
+++ b/test/geometry/epipolar/test_common.py
@@ -14,20 +14,20 @@ def generate_two_view_random_scene(
scene: Dict[str, torch.Tensor] = epi.generate_scene(num_views, num_points)
# internal parameters (same K)
- K1 = scene['K'].to(device, dtype)
+ K1 = scene["K"].to(device, dtype)
K2 = K1.clone()
# rotation
- R1 = scene['R'][0:1].to(device, dtype)
- R2 = scene['R'][1:2].to(device, dtype)
+ R1 = scene["R"][0:1].to(device, dtype)
+ R2 = scene["R"][1:2].to(device, dtype)
# translation
- t1 = scene['t'][0:1].to(device, dtype)
- t2 = scene['t'][1:2].to(device, dtype)
+ t1 = scene["t"][0:1].to(device, dtype)
+ t2 = scene["t"][1:2].to(device, dtype)
# projection matrix, P = K(R|t)
- P1 = scene['P'][0:1].to(device, dtype)
- P2 = scene['P'][1:2].to(device, dtype)
+ P1 = scene["P"][0:1].to(device, dtype)
+ P2 = scene["P"][1:2].to(device, dtype)
# fundamental matrix
F_mat = epi.fundamental_from_projections(P1[..., :3, :], P2[..., :3, :])
@@ -35,11 +35,11 @@ def generate_two_view_random_scene(
F_mat = epi.normalize_transformation(F_mat)
# points 3d
- X = scene['points3d'].to(device, dtype)
+ X = scene["points3d"].to(device, dtype)
# projected points
- x1 = scene['points2d'][0:1].to(device, dtype)
- x2 = scene['points2d'][1:2].to(device, dtype)
+ x1 = scene["points2d"][0:1].to(device, dtype)
+ x2 = scene["points2d"][1:2].to(device, dtype)
return {
"K1": K1,
diff --git a/test/geometry/epipolar/test_essential.py b/test/geometry/epipolar/test_essential.py
index 2dbfd4dd4..a090c6c33 100644
--- a/test/geometry/epipolar/test_essential.py
+++ b/test/geometry/epipolar/test_essential.py
@@ -106,10 +106,10 @@ class TestEssentialFromFundamental:
def test_from_fundamental(self, device, dtype):
scene = utils.generate_two_view_random_scene(device, dtype)
- F_mat = scene['F']
+ F_mat = scene["F"]
- K1 = scene['K1']
- K2 = scene['K2']
+ K1 = scene["K1"]
+ K2 = scene["K2"]
E_mat = epi.essential_from_fundamental(F_mat, K1, K2)
F_hat = epi.fundamental_from_essential(E_mat, K1, K2)
@@ -207,9 +207,9 @@ class TestEssentalFromRt:
def test_from_fundamental_Rt(self, device, dtype):
scene = utils.generate_two_view_random_scene(device, dtype)
- E_from_Rt = epi.essential_from_Rt(scene['R1'], scene['t1'], scene['R2'], scene['t2'])
+ E_from_Rt = epi.essential_from_Rt(scene["R1"], scene["t1"], scene["R2"], scene["t2"])
- E_from_F = epi.essential_from_fundamental(scene['F'], scene['K1'], scene['K2'])
+ E_from_F = epi.essential_from_fundamental(scene["F"], scene["K1"], scene["K2"])
E_from_Rt_norm = epi.normalize_transformation(E_from_Rt)
E_from_F_norm = epi.normalize_transformation(E_from_F)
@@ -274,8 +274,8 @@ class TestMotionFromEssential:
def test_two_view(self, device, dtype):
scene = utils.generate_two_view_random_scene(device, dtype)
- R1, t1 = scene['R1'], scene['t1']
- R2, t2 = scene['R2'], scene['t2']
+ R1, t1 = scene["R1"], scene["t1"]
+ R2, t2 = scene["R2"], scene["t2"]
E_mat = epi.essential_from_Rt(R1, t1, R2, t2)
@@ -370,13 +370,13 @@ class TestMotionFromEssentialChooseSolution:
def test_two_view(self, device, dtype):
scene = utils.generate_two_view_random_scene(device, dtype)
- E_mat = epi.essential_from_Rt(scene['R1'], scene['t1'], scene['R2'], scene['t2'])
+ E_mat = epi.essential_from_Rt(scene["R1"], scene["t1"], scene["R2"], scene["t2"])
- R, t = epi.relative_camera_motion(scene['R1'], scene['t1'], scene['R2'], scene['t2'])
+ R, t = epi.relative_camera_motion(scene["R1"], scene["t1"], scene["R2"], scene["t2"])
t = torch.nn.functional.normalize(t, dim=1)
R_hat, t_hat, _ = epi.motion_from_essential_choose_solution(
- E_mat, scene['K1'], scene['K2'], scene['x1'], scene['x2']
+ E_mat, scene["K1"], scene["K2"], scene["x1"], scene["x2"]
)
assert_close(t, t_hat)
diff --git a/test/geometry/epipolar/test_fundamental.py b/test/geometry/epipolar/test_fundamental.py
index 1ec548fb2..dbe58824c 100644
--- a/test/geometry/epipolar/test_fundamental.py
+++ b/test/geometry/epipolar/test_fundamental.py
@@ -239,8 +239,8 @@ class TestFindFundamental:
def test_synthetic_sampson_7point(self, device, dtype):
scene: Dict[str, torch.Tensor] = utils.generate_two_view_random_scene(device, dtype)
- x1 = scene['x1'][:, :7, :]
- x2 = scene['x2'][:, :7, :]
+ x1 = scene["x1"][:, :7, :]
+ x2 = scene["x2"][:, :7, :]
F_est = epi.find_fundamental(x1, x2, None, "7POINT")
for i in range(3):
F = F_est[0][i].unsqueeze(0)
@@ -250,8 +250,8 @@ class TestFindFundamental:
def test_epipolar_constraint_7point(self, device, dtype):
scene: Dict[str, torch.Tensor] = utils.generate_two_view_random_scene(device, dtype)
- x1 = scene['x1'][:, :7, :]
- x2 = scene['x2'][:, :7, :]
+ x1 = scene["x1"][:, :7, :]
+ x2 = scene["x2"][:, :7, :]
F_est = epi.find_fundamental(x1, x2, None, "7POINT")
for i in range(3):
F = F_est[0][i].unsqueeze(0)
@@ -263,8 +263,8 @@ class TestFindFundamental:
def test_synthetic_sampson(self, device, dtype):
scene: Dict[str, torch.Tensor] = utils.generate_two_view_random_scene(device, dtype)
- x1 = scene['x1']
- x2 = scene['x2']
+ x1 = scene["x1"]
+ x2 = scene["x2"]
weights = torch.ones_like(x1)[..., 0]
F_est = epi.find_fundamental(x1, x2, weights)
@@ -366,9 +366,9 @@ class TestFundamentlFromEssential:
def test_from_to_essential(self, device, dtype):
scene = utils.generate_two_view_random_scene(device, dtype)
- F_mat = scene['F']
- E_mat = epi.essential_from_fundamental(F_mat, scene['K1'], scene['K2'])
- F_hat = epi.fundamental_from_essential(E_mat, scene['K1'], scene['K2'])
+ F_mat = scene["F"]
+ E_mat = epi.essential_from_fundamental(F_mat, scene["K1"], scene["K2"])
+ F_hat = epi.fundamental_from_essential(E_mat, scene["K1"], scene["K2"])
F_mat_norm = epi.normalize_transformation(F_mat)
F_hat_norm = epi.normalize_transformation(F_hat)
diff --git a/test/geometry/epipolar/test_triangulation.py b/test/geometry/epipolar/test_triangulation.py
index 7d91d04ef..914a86300 100644
--- a/test/geometry/epipolar/test_triangulation.py
+++ b/test/geometry/epipolar/test_triangulation.py
@@ -34,16 +34,16 @@ class TestTriangulation:
num_points: int = 10
scene: Dict[str, torch.Tensor] = epi.generate_scene(num_views, num_points)
- P1 = scene['P'][0:1]
- P2 = scene['P'][1:2]
- x1 = scene['points2d'][0:1]
- x2 = scene['points2d'][1:2]
+ P1 = scene["P"][0:1]
+ P2 = scene["P"][1:2]
+ x1 = scene["points2d"][0:1]
+ x2 = scene["points2d"][1:2]
X = epi.triangulate_points(P1, P2, x1, x2)
- x_reprojected = kornia.geometry.transform_points(scene['P'], X.expand(num_views, -1, -1))
+ x_reprojected = kornia.geometry.transform_points(scene["P"], X.expand(num_views, -1, -1))
- assert_close(scene['points3d'], X, rtol=1e-4, atol=1e-4)
- assert_close(scene['points2d'], x_reprojected, rtol=1e-4, atol=1e-4)
+ assert_close(scene["points3d"], X, rtol=1e-4, atol=1e-4)
+ assert_close(scene["points2d"], x_reprojected, rtol=1e-4, atol=1e-4)
def test_gradcheck(self, device):
points1 = torch.rand(1, 8, 2, device=device, dtype=torch.float64, requires_grad=True)
diff --git a/test/geometry/subpix/test_dsnt.py b/test/geometry/subpix/test_dsnt.py
index 099764116..daecbeb3c 100644
--- a/test/geometry/subpix/test_dsnt.py
+++ b/test/geometry/subpix/test_dsnt.py
@@ -49,7 +49,7 @@ class TestSpatialSoftmax2d:
def test_forward(self, input):
actual = kornia.geometry.subpix.spatial_softmax2d(input)
- assert actual.lt(0).sum().item() == 0, 'expected no negative values'
+ assert actual.lt(0).sum().item() == 0, "expected no negative values"
sums = actual.sum(-1).sum(-1)
assert_close(sums, torch.ones_like(sums))
@@ -81,7 +81,7 @@ class TestSpatialExpectation2d:
actual_px = kornia.geometry.subpix.spatial_expectation2d(input, False)
assert_close(actual_px, expected_px)
- @pytest.mark.skip('After the op be optimized the results are not the same')
+ @pytest.mark.skip("After the op be optimized the results are not the same")
def test_dynamo(self, dtype, device, torch_optimizer):
inpt = torch.tensor([[[[0.0, 0.0, 1.0], [0.0, 0.0, 0.0]]]], device=device, dtype=dtype)
op = kornia.geometry.subpix.spatial_expectation2d
diff --git a/test/geometry/subpix/test_spatial_softargmax.py b/test/geometry/subpix/test_spatial_softargmax.py
index a44f85237..415a443f4 100644
--- a/test/geometry/subpix/test_spatial_softargmax.py
+++ b/test/geometry/subpix/test_spatial_softargmax.py
@@ -139,13 +139,13 @@ class TestSpatialSoftArgmax2d:
pred, torch.as_tensor([[[0.0, 0.0], [0.0, 0.0]]], device=device, dtype=dtype), atol=1e-4, rtol=1e-4
)
- loss1 = mse_loss(pred, target, size_average=None, reduce=None, reduction='none').mean(-1, keepdim=False)
+ loss1 = mse_loss(pred, target, size_average=None, reduce=None, reduction="none").mean(-1, keepdim=False)
expected_loss1 = torch.as_tensor([[0.0, 1.0]], device=device, dtype=dtype)
assert_close(loss1, expected_loss1, atol=1e-4, rtol=1e-4)
target_hm = kornia.geometry.subpix.render_gaussian2d(target, std, sample.shape[-2:]).contiguous()
- loss2 = kornia.losses.js_div_loss_2d(hm, target_hm, reduction='none')
+ loss2 = kornia.losses.js_div_loss_2d(hm, target_hm, reduction="none")
expected_loss2 = torch.as_tensor([[0.0087, 0.0818]], device=device, dtype=dtype)
assert_close(loss2, expected_loss2, rtol=0, atol=1e-3)
diff --git a/test/geometry/test_bbox.py b/test/geometry/test_bbox.py
index 29a9e6c28..5975fcbfb 100644
--- a/test/geometry/test_bbox.py
+++ b/test/geometry/test_bbox.py
@@ -142,7 +142,7 @@ class TestTransformBoxes2D:
trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
- out = transform_bbox(trans_mat, boxes, mode='xywh', restore_coordinates=True)
+ out = transform_bbox(trans_mat, boxes, mode="xywh", restore_coordinates=True)
assert_close(out, expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
diff --git a/test/geometry/test_boxes.py b/test/geometry/test_boxes.py
index a75d96c1d..04236da11 100644
--- a/test/geometry/test_boxes.py
+++ b/test/geometry/test_boxes.py
@@ -79,7 +79,7 @@ class TestBoxes2D:
assert_close(h, torch.as_tensor([[2], [3]], device=device, dtype=dtype))
assert_close(w, torch.as_tensor([[3], [4]], device=device, dtype=dtype))
- @pytest.mark.parametrize('shape', [(1, 4), (1, 1, 4)])
+ @pytest.mark.parametrize("shape", [(1, 4), (1, 1, 4)])
def test_from_tensor(self, shape, device, dtype):
box_xyxy = torch.as_tensor([[1, 2, 3, 4]], device=device, dtype=dtype).view(*shape)
box_xyxy_plus = torch.as_tensor([[1, 2, 2, 3]], device=device, dtype=dtype).view(*shape)
@@ -91,11 +91,11 @@ class TestBoxes2D:
expected_box = torch.as_tensor([[[1, 2], [2, 2], [2, 3], [1, 3]]], device=device, dtype=dtype).view(*shape, 2)
- boxes_xyxy = Boxes.from_tensor(box_xyxy, mode='xyxy').data
- boxes_xyxy_plus = Boxes.from_tensor(box_xyxy_plus, mode='xyxy_plus').data
- boxes_xywh = Boxes.from_tensor(box_xywh, mode='xywh').data
- box_vertices = Boxes.from_tensor(box_vertices, mode='vertices').data
- boxes_vertices_plus = Boxes.from_tensor(box_vertices_plus, mode='vertices_plus').data
+ boxes_xyxy = Boxes.from_tensor(box_xyxy, mode="xyxy").data
+ boxes_xyxy_plus = Boxes.from_tensor(box_xyxy_plus, mode="xyxy_plus").data
+ boxes_xywh = Boxes.from_tensor(box_xywh, mode="xywh").data
+ box_vertices = Boxes.from_tensor(box_vertices, mode="vertices").data
+ boxes_vertices_plus = Boxes.from_tensor(box_vertices_plus, mode="vertices_plus").data
assert boxes_xyxy.shape == expected_box.shape
assert_close(boxes_xyxy, expected_box)
@@ -112,24 +112,24 @@ class TestBoxes2D:
assert boxes_vertices_plus.shape == expected_box.shape
assert_close(boxes_vertices_plus, expected_box)
- @pytest.mark.parametrize('shape', [(1, 4), (1, 1, 4)])
+ @pytest.mark.parametrize("shape", [(1, 4), (1, 1, 4)])
def test_from_invalid_tensor(self, shape, device, dtype):
box_xyxy = torch.as_tensor([[1, 2, -3, 4]], device=device, dtype=dtype).view(*shape) # Invalid width
box_xyxy_plus = torch.as_tensor([[1, 2, 0, 3]], device=device, dtype=dtype).view(*shape) # Invalid height
try:
- Boxes.from_tensor(box_xyxy, mode='xyxy')
+ Boxes.from_tensor(box_xyxy, mode="xyxy")
assert False, "Boxes.from_tensor should have raised any exception"
except ValueError:
pass
try:
- Boxes.from_tensor(box_xyxy_plus, mode='xyxy_plus')
+ Boxes.from_tensor(box_xyxy_plus, mode="xyxy_plus")
assert False, "Boxes.from_tensor should have raised any exception"
except ValueError:
pass
- @pytest.mark.parametrize('shape', [(1, 4), (1, 1, 4)])
+ @pytest.mark.parametrize("shape", [(1, 4), (1, 1, 4)])
def test_boxes_to_tensor(self, shape, device, dtype):
# quadrilateral with randomized vertices to reflect possible transforms.
box = Boxes(torch.as_tensor([[[2, 2], [2, 3], [1, 3], [1, 2]]], device=device, dtype=dtype).view(*shape, 2))
@@ -144,11 +144,11 @@ class TestBoxes2D:
*shape, 2
)
- boxes_xyxy = box.to_tensor(mode='xyxy')
- boxes_xyxy_plus = box.to_tensor(mode='xyxy_plus')
- boxes_xywh = box.to_tensor(mode='xywh')
- boxes_vertices = box.to_tensor(mode='vertices')
- boxes_vertices_plus = box.to_tensor(mode='vertices_plus')
+ boxes_xyxy = box.to_tensor(mode="xyxy")
+ boxes_xyxy_plus = box.to_tensor(mode="xyxy_plus")
+ boxes_xywh = box.to_tensor(mode="xywh")
+ boxes_vertices = box.to_tensor(mode="vertices")
+ boxes_vertices_plus = box.to_tensor(mode="vertices_plus")
assert boxes_xyxy.shape == expected_box_xyxy.shape
assert_close(boxes_xyxy, expected_box_xyxy)
@@ -165,7 +165,7 @@ class TestBoxes2D:
assert boxes_vertices_plus.shape == expected_vertices_plus.shape
assert_close(boxes_vertices_plus, expected_vertices_plus)
- @pytest.mark.parametrize('mode', ['xyxy', 'xyxy_plus', 'xywh', 'vertices', 'vertices_plus'])
+ @pytest.mark.parametrize("mode", ["xyxy", "xyxy_plus", "xywh", "vertices", "vertices_plus"])
def test_boxes_list_to_tensor_list(self, mode, device, dtype):
src_1 = [
torch.as_tensor([[[1, 2], [1, 3], [2, 2], [2, 3]]], device=device, dtype=dtype),
@@ -177,7 +177,7 @@ class TestBoxes2D:
torch.as_tensor([[1, 1, 5, 5]], device=device, dtype=dtype),
torch.as_tensor([[1, 1, 5, 5], [1, 1, 5, 5]], device=device, dtype=dtype),
]
- src = src_1 if mode in ['vertices', 'vertices_plus'] else src_2
+ src = src_1 if mode in ["vertices", "vertices_plus"] else src_2
box = Boxes.from_tensor(src, mode=mode)
out = box.to_tensor(mode)
assert out[0].shape == src[0].shape
@@ -248,7 +248,7 @@ class TestBoxes2D:
assert_close(batched_masks, expected_batched_masks)
def test_to(self, device, dtype):
- boxes = Boxes.from_tensor(torch.as_tensor([[1, 2, 3, 4]], device='cpu', dtype=torch.float32))
+ boxes = Boxes.from_tensor(torch.as_tensor([[1, 2, 3, 4]], device="cpu", dtype=torch.float32))
assert boxes.to(device=device).data.device == device
assert boxes.to(dtype=dtype).data.dtype == dtype
@@ -271,12 +271,12 @@ class TestBoxes2D:
t_boxes_xyxy = tensor_to_gradcheck_var(torch.tensor([[1.0, 3.0, 5.0, 6.0]]))
t_boxes_xyxy1 = tensor_to_gradcheck_var(t_boxes_xyxy.detach().clone())
- gradcheck(partial(apply_boxes_method, method='to_tensor'), (t_boxes2,))
- gradcheck(partial(apply_boxes_method, method='to_tensor', mode='xyxy_plus'), (t_boxes3,))
- gradcheck(partial(apply_boxes_method, method='to_tensor', mode='vertices_plus'), (t_boxes4,))
- gradcheck(partial(apply_boxes_method, method='get_boxes_shape'), (t_boxes1,))
- gradcheck(lambda x: Boxes.from_tensor(x, mode='xyxy_plus').data, (t_boxes_xyxy,))
- gradcheck(lambda x: Boxes.from_tensor(x, mode='xywh').data, (t_boxes_xyxy1,))
+ gradcheck(partial(apply_boxes_method, method="to_tensor"), (t_boxes2,))
+ gradcheck(partial(apply_boxes_method, method="to_tensor", mode="xyxy_plus"), (t_boxes3,))
+ gradcheck(partial(apply_boxes_method, method="to_tensor", mode="vertices_plus"), (t_boxes4,))
+ gradcheck(partial(apply_boxes_method, method="get_boxes_shape"), (t_boxes1,))
+ gradcheck(lambda x: Boxes.from_tensor(x, mode="xyxy_plus").data, (t_boxes_xyxy,))
+ gradcheck(lambda x: Boxes.from_tensor(x, mode="xywh").data, (t_boxes_xyxy1,))
class TestTransformBoxes2D:
@@ -321,9 +321,7 @@ class TestTransformBoxes2D:
],
device=device,
dtype=dtype,
- ).repeat(
- 2, 1, 1
- ) # 2 x 4 x 4 two images 4 boxes each
+ ).repeat(2, 1, 1) # 2 x 4 x 4 two images 4 boxes each
expected_boxes_xyxy = torch.tensor(
[
@@ -494,7 +492,7 @@ class TestBbox3D:
assert_close(h, torch.as_tensor([[21.0], [51.0]], device=device, dtype=dtype))
assert_close(w, torch.as_tensor([[11.0], [41.0]], device=device, dtype=dtype))
- @pytest.mark.parametrize('shape', [(1, 6), (1, 1, 6)])
+ @pytest.mark.parametrize("shape", [(1, 6), (1, 1, 6)])
def test_from_tensor(self, shape, device, dtype):
box_xyzxyz = torch.as_tensor([[1, 2, 3, 4, 5, 6]], device=device, dtype=dtype).view(*shape)
box_xyzxyz_plus = torch.as_tensor([[1, 2, 3, 3, 4, 5]], device=device, dtype=dtype).view(*shape)
@@ -506,9 +504,9 @@ class TestBbox3D:
dtype=dtype,
).view(*shape[:-1], 8, 3)
- kornia_xyzxyz = Boxes3D.from_tensor(box_xyzxyz, mode='xyzxyz').data
- kornia_xyzxyz_plus = Boxes3D.from_tensor(box_xyzxyz_plus, mode='xyzxyz_plus').data
- kornia_xyzwhd = Boxes3D.from_tensor(box_xyzwhd, mode='xyzwhd').data
+ kornia_xyzxyz = Boxes3D.from_tensor(box_xyzxyz, mode="xyzxyz").data
+ kornia_xyzxyz_plus = Boxes3D.from_tensor(box_xyzxyz_plus, mode="xyzxyz_plus").data
+ kornia_xyzwhd = Boxes3D.from_tensor(box_xyzwhd, mode="xyzwhd").data
assert kornia_xyzxyz.shape == expected_box.shape
assert_close(kornia_xyzxyz, expected_box)
@@ -519,24 +517,24 @@ class TestBbox3D:
assert kornia_xyzwhd.shape == expected_box.shape
assert_close(kornia_xyzwhd, expected_box)
- @pytest.mark.parametrize('shape', [(1, 6), (1, 1, 6)])
+ @pytest.mark.parametrize("shape", [(1, 6), (1, 1, 6)])
def test_from_invalid_tensor(self, shape, device, dtype):
box_xyzxyz = torch.as_tensor([[1, 2, 3, 4, -5, 6]], device=device, dtype=dtype).view(*shape)
box_xyzxyz_plus = torch.as_tensor([[1, 2, 3, 0, 6, 4]], device=device, dtype=dtype).view(*shape)
try:
- Boxes3D.from_tensor(box_xyzxyz, mode='xyzxyz')
+ Boxes3D.from_tensor(box_xyzxyz, mode="xyzxyz")
assert False, "Boxes3D.from_tensor should have raised any exception"
except ValueError:
pass
try:
- Boxes3D.from_tensor(box_xyzxyz_plus, mode='xyzxyz_plus')
+ Boxes3D.from_tensor(box_xyzxyz_plus, mode="xyzxyz_plus")
assert False, "Boxes3D.from_tensor should have raised any exception"
except ValueError:
pass
- @pytest.mark.parametrize('shape', [(1, 6), (1, 1, 6)])
+ @pytest.mark.parametrize("shape", [(1, 6), (1, 1, 6)])
def test_boxes_to_tensor(self, shape, device, dtype):
# Hexahedron with randomized vertices to reflect possible transforms.
box = Boxes3D(
@@ -561,11 +559,11 @@ class TestBbox3D:
dtype=dtype,
).view(*shape[:-1], 8, 3)
- kornia_xyzxyz = box.to_tensor(mode='xyzxyz')
- kornia_xyzxyz_plus = box.to_tensor(mode='xyzxyz_plus')
- kornia_xyzwhd = box.to_tensor(mode='xyzwhd')
- kornia_vertices = box.to_tensor(mode='vertices')
- kornia_vertices_plus = box.to_tensor(mode='vertices_plus')
+ kornia_xyzxyz = box.to_tensor(mode="xyzxyz")
+ kornia_xyzxyz_plus = box.to_tensor(mode="xyzxyz_plus")
+ kornia_xyzwhd = box.to_tensor(mode="xyzwhd")
+ kornia_vertices = box.to_tensor(mode="vertices")
+ kornia_vertices_plus = box.to_tensor(mode="vertices_plus")
assert kornia_xyzxyz.shape == expected_box_xyzxyz.shape
assert_close(kornia_xyzxyz, expected_box_xyzxyz)
@@ -714,7 +712,7 @@ class TestBbox3D:
assert_close(batched_masks, expected_batched_masks)
def test_to(self, device, dtype):
- boxes = Boxes3D.from_tensor(torch.as_tensor([[1, 2, 3, 4, 5, 6]], device='cpu', dtype=torch.float32))
+ boxes = Boxes3D.from_tensor(torch.as_tensor([[1, 2, 3, 4, 5, 6]], device="cpu", dtype=torch.float32))
assert boxes.to(device=device).data.device == device
assert boxes.to(dtype=dtype).data.dtype == dtype
@@ -763,8 +761,8 @@ class TestBbox3D:
# partial(apply_boxes_method, method='to_tensor', mode='vertices_plus'), (t_boxes4,), raise_exception=True
# )
# assert gradcheck(partial(apply_boxes_method, method='get_boxes_shape'), (t_boxes1,), raise_exception=True)
- gradcheck(lambda x: Boxes3D.from_tensor(x, mode='xyzxyz_plus').data, (t_boxes_xyzxyz,))
- gradcheck(lambda x: Boxes3D.from_tensor(x, mode='xyzwhd').data, (t_boxes_xyzxyz1,))
+ gradcheck(lambda x: Boxes3D.from_tensor(x, mode="xyzxyz_plus").data, (t_boxes_xyzxyz,))
+ gradcheck(lambda x: Boxes3D.from_tensor(x, mode="xyzwhd").data, (t_boxes_xyzxyz1,))
class TestTransformBoxes3D:
@@ -825,9 +823,7 @@ class TestTransformBoxes3D:
],
device=device,
dtype=dtype,
- ).repeat(
- 2, 1, 1
- ) # 2 x 4 x 4 two images 4 boxes each
+ ).repeat(2, 1, 1) # 2 x 4 x 4 two images 4 boxes each
expected_boxes_xyzxyz = torch.tensor(
[
diff --git a/test/geometry/test_conversions.py b/test/geometry/test_conversions.py
index 5a07aae94..66587c3d6 100644
--- a/test/geometry/test_conversions.py
+++ b/test/geometry/test_conversions.py
@@ -26,7 +26,7 @@ from kornia.testing import BaseTester, assert_close, create_eye_batch, tensor_to
@pytest.fixture()
def atol(device, dtype):
"""Lower tolerance for cuda-float16 only."""
- if 'cuda' in device.type and dtype == torch.float16:
+ if "cuda" in device.type and dtype == torch.float16:
return 1.0e-3
return 1.0e-4
@@ -34,7 +34,7 @@ def atol(device, dtype):
@pytest.fixture()
def rtol(device, dtype):
"""Lower tolerance for cuda-float16 only."""
- if 'cuda' in device.type and dtype == torch.float16:
+ if "cuda" in device.type and dtype == torch.float16:
return 1.0e-3
return 1.0e-4
@@ -845,8 +845,8 @@ class TestNormalizePixelCoordinates:
assert_close(grid_norm, expected, atol=atol, rtol=rtol)
def test_dynamo(self, device, dtype, torch_optimizer):
- if device == torch.device('cpu'):
- pytest.skip('NormalizePixelCoordinates not working on CPU with dynamo!')
+ if device == torch.device("cpu"):
+ pytest.skip("NormalizePixelCoordinates not working on CPU with dynamo!")
op = kornia.geometry.conversions.normalize_pixel_coordinates
op_optimized = torch_optimizer(op)
@@ -888,8 +888,8 @@ class TestDenormalizePixelCoordinates:
assert_close(grid_norm, expected, atol=1e-4, rtol=1e-4)
def test_dynamo(self, device, dtype, torch_optimizer):
- if device == torch.device('cpu'):
- pytest.xfail('DenormalizePixelCoordinates not working on CPU with dynamo!')
+ if device == torch.device("cpu"):
+ pytest.xfail("DenormalizePixelCoordinates not working on CPU with dynamo!")
op = kornia.geometry.conversions.denormalize_pixel_coordinates
op_optimized = torch_optimizer(op)
@@ -1340,7 +1340,7 @@ class TestQuaternionFromEuler(BaseTester):
# out = torch.tensor(out, device=device, dtype=dtype)
[email protected]('batch_size', (None, 1, 2, 5))
[email protected]("batch_size", (None, 1, 2, 5))
def test_vector_to_skew_symmetric_matrix(batch_size, device, dtype):
if batch_size is None:
vector = torch.rand(3, device=device, dtype=dtype)
diff --git a/test/geometry/test_homography.py b/test/geometry/test_homography.py
index 7df0ad25a..d69abbc5d 100644
--- a/test/geometry/test_homography.py
+++ b/test/geometry/test_homography.py
@@ -150,7 +150,7 @@ class TestFindHomographyDLT:
points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)
points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)
weights = torch.ones(1, 4, device=device, dtype=dtype)
- points1[0, 0, 0] = float('nan')
+ points1[0, 0, 0] = float("nan")
H = find_homography_dlt(points1, points2, weights)
assert H.shape == (1, 3, 3)
@@ -158,8 +158,8 @@ class TestFindHomographyDLT:
points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)
points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)
weights = torch.ones(1, 4, device=device, dtype=dtype)
- points1[0, 0, 0] = float('nan')
- H = find_homography_dlt(points1, points2, weights, 'lu')
+ points1[0, 0, 0] = float("nan")
+ H = find_homography_dlt(points1, points2, weights, "lu")
assert H.shape == (1, 3, 3)
@pytest.mark.parametrize("batch_size, num_points", [(1, 4), (2, 5), (3, 6)])
@@ -203,7 +203,7 @@ class TestFindHomographyDLT:
weights = torch.ones(batch_size, 10, device=device, dtype=dtype)
# compute transform from source to target
- dst_homo_src = find_homography_dlt(points_src, points_dst, weights, 'svd')
+ dst_homo_src = find_homography_dlt(points_src, points_dst, weights, "svd")
assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
@@ -219,7 +219,7 @@ class TestFindHomographyDLT:
weights = torch.ones(batch_size, 10, device=device, dtype=dtype)
# compute transform from source to target
- dst_homo_src = find_homography_dlt(points_src, points_dst, weights, 'lu')
+ dst_homo_src = find_homography_dlt(points_src, points_dst, weights, "lu")
assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
@@ -250,7 +250,7 @@ class TestFindHomographyDLT:
assert gradcheck(
find_homography_dlt,
- (points_src, points_dst, weights, 'lu'),
+ (points_src, points_dst, weights, "lu"),
rtol=1e-6,
atol=1e-6,
raise_exception=True,
@@ -286,7 +286,7 @@ class TestFindHomographyFromLinesDLT:
points2st = torch.rand(1, 4, 2, device=device, dtype=dtype)
points2end = torch.rand(1, 4, 2, device=device, dtype=dtype)
weights = torch.ones(1, 4, device=device, dtype=dtype)
- points1st[0, 0, 0] = float('nan')
+ points1st[0, 0, 0] = float("nan")
ls1 = torch.stack([points1st, points1end], dim=2)
ls2 = torch.stack([points2st, points2end], dim=2)
H = find_homography_lines_dlt(ls1, ls2, weights)
diff --git a/test/geometry/test_ransac.py b/test/geometry/test_ransac.py
index f97b2f946..f616d5db3 100644
--- a/test/geometry/test_ransac.py
+++ b/test/geometry/test_ransac.py
@@ -13,7 +13,7 @@ class TestRANSACHomography:
torch.random.manual_seed(0)
points1 = torch.rand(4, 2, device=device, dtype=dtype)
points2 = torch.rand(4, 2, device=device, dtype=dtype)
- ransac = RANSAC('homography').to(device=device, dtype=dtype)
+ ransac = RANSAC("homography").to(device=device, dtype=dtype)
torch.random.manual_seed(0)
H, _ = ransac(points1, points2)
assert H.shape == (3, 3)
@@ -32,7 +32,7 @@ class TestRANSACHomography:
# making last point an outlier
points_dst[:, -1, :] += 800
- ransac = RANSAC('homography', inl_th=0.5, max_iter=20).to(device=device, dtype=dtype)
+ ransac = RANSAC("homography", inl_th=0.5, max_iter=20).to(device=device, dtype=dtype)
# compute transform from source to target
dst_homo_src, _ = ransac(points_src[0], points_dst[0])
@@ -44,11 +44,11 @@ class TestRANSACHomography:
# generate input data
torch.random.manual_seed(0)
data_dev = utils.dict_to(data, device, dtype)
- homography_gt = torch.inverse(data_dev['H_gt'])
+ homography_gt = torch.inverse(data_dev["H_gt"])
homography_gt = homography_gt / homography_gt[2, 2]
- pts_src = data_dev['pts0']
- pts_dst = data_dev['pts1']
- ransac = RANSAC('homography', inl_th=0.5, max_iter=20).to(device=device, dtype=dtype)
+ pts_src = data_dev["pts0"]
+ pts_dst = data_dev["pts1"]
+ ransac = RANSAC("homography", inl_th=0.5, max_iter=20).to(device=device, dtype=dtype)
# compute transform from source to target
dst_homo_src, _ = ransac(pts_src, pts_dst)
@@ -61,15 +61,15 @@ class TestRANSACHomography:
# generate input data
torch.random.manual_seed(0)
data_dev = utils.dict_to(data, device, dtype)
- homography_gt = torch.inverse(data_dev['H_gt'])
+ homography_gt = torch.inverse(data_dev["H_gt"])
homography_gt = homography_gt / homography_gt[2, 2]
- pts_src = data_dev['pts0']
- pts_dst = data_dev['pts1']
+ pts_src = data_dev["pts0"]
+ pts_dst = data_dev["pts1"]
- kp1 = data_dev['loftr_outdoor_tentatives0']
- kp2 = data_dev['loftr_outdoor_tentatives1']
+ kp1 = data_dev["loftr_outdoor_tentatives0"]
+ kp2 = data_dev["loftr_outdoor_tentatives1"]
- ransac = RANSAC('homography', inl_th=3.0, max_iter=30, max_lo_iters=10).to(device=device, dtype=dtype)
+ ransac = RANSAC("homography", inl_th=3.0, max_iter=30, max_lo_iters=10).to(device=device, dtype=dtype)
# compute transform from source to target
dst_homo_src, _ = ransac(kp1, kp2)
@@ -81,8 +81,8 @@ class TestRANSACHomography:
torch.random.manual_seed(0)
points1 = torch.rand(4, 2, device=device, dtype=dtype)
points2 = torch.rand(4, 2, device=device, dtype=dtype)
- model = RANSAC('homography').to(device=device, dtype=dtype)
- model_jit = torch.jit.script(RANSAC('homography').to(device=device, dtype=dtype))
+ model = RANSAC("homography").to(device=device, dtype=dtype)
+ model_jit = torch.jit.script(RANSAC("homography").to(device=device, dtype=dtype))
assert_close(model(points1, points2)[0], model_jit(points1, points2)[0], rtol=1e-4, atol=1e-4)
@@ -91,7 +91,7 @@ class TestRANSACHomographyLineSegments:
torch.random.manual_seed(0)
points1 = torch.rand(4, 2, 2, device=device, dtype=dtype)
points2 = torch.rand(4, 2, 2, device=device, dtype=dtype)
- ransac = RANSAC('homography_from_linesegments').to(device=device, dtype=dtype)
+ ransac = RANSAC("homography_from_linesegments").to(device=device, dtype=dtype)
torch.random.manual_seed(0)
H, _ = ransac(points1, points2)
assert H.shape == (3, 3)
@@ -116,7 +116,7 @@ class TestRANSACHomographyLineSegments:
ls1 = torch.stack([points_src_st, points_src_end], dim=2)
ls2 = torch.stack([points_dst_st, points_dst_end], dim=2)
- ransac = RANSAC('homography_from_linesegments', inl_th=0.5, max_iter=20).to(device=device, dtype=dtype)
+ ransac = RANSAC("homography_from_linesegments", inl_th=0.5, max_iter=20).to(device=device, dtype=dtype)
# compute transform from source to target
dst_homo_src, _ = ransac(ls1[0], ls2[0])
@@ -129,8 +129,8 @@ class TestRANSACHomographyLineSegments:
torch.random.manual_seed(0)
points1 = torch.rand(4, 2, 2, device=device, dtype=dtype)
points2 = torch.rand(4, 2, 2, device=device, dtype=dtype)
- model = RANSAC('homography_from_linesegments').to(device=device, dtype=dtype)
- model_jit = torch.jit.script(RANSAC('homography_from_linesegments').to(device=device, dtype=dtype))
+ model = RANSAC("homography_from_linesegments").to(device=device, dtype=dtype)
+ model_jit = torch.jit.script(RANSAC("homography_from_linesegments").to(device=device, dtype=dtype))
assert_close(model(points1, points2)[0], model_jit(points1, points2)[0], rtol=1e-4, atol=1e-4)
@@ -139,7 +139,7 @@ class TestRANSACFundamental:
torch.random.manual_seed(0)
points1 = torch.rand(8, 2, device=device, dtype=dtype)
points2 = torch.rand(8, 2, device=device, dtype=dtype)
- ransac = RANSAC('fundamental').to(device=device, dtype=dtype)
+ ransac = RANSAC("fundamental").to(device=device, dtype=dtype)
Fm, _ = ransac(points1, points2)
assert Fm.shape == (3, 3)
@@ -150,10 +150,10 @@ class TestRANSACFundamental:
torch.random.manual_seed(0)
# generate input data
data_dev = utils.dict_to(data, device, dtype)
- pts_src = data_dev['pts0']
- pts_dst = data_dev['pts1']
+ pts_src = data_dev["pts0"]
+ pts_dst = data_dev["pts1"]
# compute transform from source to target
- ransac = RANSAC('fundamental', inl_th=0.5, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)
+ ransac = RANSAC("fundamental", inl_th=0.5, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)
fundamental_matrix, _ = ransac(pts_src, pts_dst)
gross_errors = (
sampson_epipolar_distance(pts_src[None], pts_dst[None], fundamental_matrix[None], squared=False) > 1.0
@@ -167,10 +167,10 @@ class TestRANSACFundamental:
torch.random.manual_seed(0)
# generate input data
data_dev = utils.dict_to(data, device, dtype)
- pts_src = data_dev['pts0']
- pts_dst = data_dev['pts1']
+ pts_src = data_dev["pts0"]
+ pts_dst = data_dev["pts1"]
# compute transform from source to target
- ransac = RANSAC('fundamental_7pt', inl_th=1.0, max_iter=100, max_lo_iters=10).to(device=device, dtype=dtype)
+ ransac = RANSAC("fundamental_7pt", inl_th=1.0, max_iter=100, max_lo_iters=10).to(device=device, dtype=dtype)
fundamental_matrix, _ = ransac(pts_src, pts_dst)
gross_errors = (
sampson_epipolar_distance(pts_src[None], pts_dst[None], fundamental_matrix[None], squared=False) > 1.0
@@ -184,13 +184,13 @@ class TestRANSACFundamental:
torch.random.manual_seed(0)
# generate input data
data_dev = utils.dict_to(data, device, dtype)
- pts_src = data_dev['pts0']
- pts_dst = data_dev['pts1']
+ pts_src = data_dev["pts0"]
+ pts_dst = data_dev["pts1"]
- kp1 = data_dev['loftr_indoor_tentatives0']
- kp2 = data_dev['loftr_indoor_tentatives1']
+ kp1 = data_dev["loftr_indoor_tentatives0"]
+ kp2 = data_dev["loftr_indoor_tentatives1"]
- ransac = RANSAC('fundamental', inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)
+ ransac = RANSAC("fundamental", inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)
# compute transform from source to target
fundamental_matrix, _ = ransac(kp1, kp2)
gross_errors = (
@@ -205,13 +205,13 @@ class TestRANSACFundamental:
torch.random.manual_seed(0)
# generate input data
data_dev = utils.dict_to(data, device, dtype)
- pts_src = data_dev['pts0']
- pts_dst = data_dev['pts1']
+ pts_src = data_dev["pts0"]
+ pts_dst = data_dev["pts1"]
- kp1 = data_dev['loftr_indoor_tentatives0']
- kp2 = data_dev['loftr_indoor_tentatives1']
+ kp1 = data_dev["loftr_indoor_tentatives0"]
+ kp2 = data_dev["loftr_indoor_tentatives1"]
- ransac = RANSAC('fundamental_7pt', inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)
+ ransac = RANSAC("fundamental_7pt", inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)
# compute transform from source to target
fundamental_matrix, _ = ransac(kp1, kp2)
gross_errors = (
@@ -224,7 +224,7 @@ class TestRANSACFundamental:
torch.random.manual_seed(0)
points1 = torch.rand(8, 2, device=device, dtype=dtype)
points2 = torch.rand(8, 2, device=device, dtype=dtype)
- model = RANSAC('fundamental').to(device=device, dtype=dtype)
+ model = RANSAC("fundamental").to(device=device, dtype=dtype)
model_jit = torch.jit.script(model)
assert_close(model(points1, points2)[0], model_jit(points1, points2)[0], rtol=1e-3, atol=1e-3)
@@ -233,7 +233,7 @@ class TestRANSACFundamental:
torch.random.manual_seed(0)
points1 = torch.rand(8, 2, device=device, dtype=torch.float64, requires_grad=True)
points2 = torch.rand(8, 2, device=device, dtype=torch.float64)
- model = RANSAC('fundamental').to(device=device, dtype=torch.float64)
+ model = RANSAC("fundamental").to(device=device, dtype=torch.float64)
def gradfun(p1, p2):
return model(p1, p2)[0]
diff --git a/test/geometry/transform/test_affine.py b/test/geometry/transform/test_affine.py
index 0a52f4e7e..64f3e9067 100644
--- a/test/geometry/transform/test_affine.py
+++ b/test/geometry/transform/test_affine.py
@@ -312,7 +312,7 @@ class TestRotate:
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(kornia.geometry.transform.rotate, (input, angle), raise_exception=True, fast_mode=True)
- @pytest.mark.skip('Need deep look into it since crashes everywhere.')
+ @pytest.mark.skip("Need deep look into it since crashes everywhere.")
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
angle = torch.tensor([90.0], device=device, dtype=dtype)
@@ -375,7 +375,7 @@ class TestTranslate:
kornia.geometry.transform.translate, (input, translation), raise_exception=True, fast_mode=True
)
- @pytest.mark.skip('Need deep look into it since crashes everywhere.')
+ @pytest.mark.skip("Need deep look into it since crashes everywhere.")
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
translation = torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)
@@ -460,7 +460,7 @@ class TestScale:
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(kornia.geometry.transform.scale, (input, scale_factor), raise_exception=True, fast_mode=True)
- @pytest.mark.skip('Need deep look into it since crashes everywhere.')
+ @pytest.mark.skip("Need deep look into it since crashes everywhere.")
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
scale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)
@@ -559,7 +559,7 @@ class TestShear:
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(kornia.geometry.transform.shear, (input, shear), raise_exception=True, fast_mode=True)
- @pytest.mark.skip('Need deep look into it since crashes everywhere.')
+ @pytest.mark.skip("Need deep look into it since crashes everywhere.")
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
shear = torch.tensor([[0.5, 0.0]], device=device, dtype=dtype)
@@ -583,7 +583,7 @@ class TestAffine2d:
def test_affine_rotate(self, device, dtype):
# TODO: Remove when #666 is implemented
- if device.type == 'cuda':
+ if device.type == "cuda":
pytest.skip("Currently breaks in CUDA." "See https://github.com/kornia/kornia/issues/666")
torch.manual_seed(0)
angle = torch.rand(1, device=device, dtype=dtype) * 90.0
@@ -596,7 +596,7 @@ class TestAffine2d:
def test_affine_translate(self, device, dtype):
# TODO: Remove when #666 is implemented
- if device.type == 'cuda':
+ if device.type == "cuda":
pytest.skip("Currently breaks in CUDA." "See https://github.com/kornia/kornia/issues/666")
torch.manual_seed(0)
translation = torch.rand(1, 2, device=device, dtype=dtype) * 2.0
@@ -609,7 +609,7 @@ class TestAffine2d:
def test_affine_scale(self, device, dtype):
# TODO: Remove when #666 is implemented
- if device.type == 'cuda':
+ if device.type == "cuda":
pytest.skip("Currently breaks in CUDA." "See https://github.com/kornia/kornia/issues/666")
torch.manual_seed(0)
_scale_factor = torch.rand(1, device=device, dtype=dtype) * 2.0
@@ -637,7 +637,7 @@ class TestAffine2d:
def test_affine_rotate_translate(self, device, dtype):
# TODO: Remove when #666 is implemented
- if device.type == 'cuda':
+ if device.type == "cuda":
pytest.skip("Currently breaks in CUDA." "See https://github.com/kornia/kornia/issues/666")
batch_size = 2
diff --git a/test/geometry/transform/test_crop3d.py b/test/geometry/transform/test_crop3d.py
index 1ede77f45..b83096526 100644
--- a/test/geometry/transform/test_crop3d.py
+++ b/test/geometry/transform/test_crop3d.py
@@ -133,7 +133,7 @@ class TestCenterCrop3D:
)
@pytest.mark.skipif(
- torch_version() == '2.1.0',
+ torch_version() == "2.1.0",
reason=(
"https://github.com/pytorch/pytorch/issues/110680"
" - unsupported operand type(s) for @: 'FakeTensor' and 'FakeTensor' on `normalize_homography3d`"
diff --git a/test/geometry/transform/test_image_registrator.py b/test/geometry/transform/test_image_registrator.py
index b7d4af161..7bf3a8223 100644
--- a/test/geometry/transform/test_image_registrator.py
+++ b/test/geometry/transform/test_image_registrator.py
@@ -57,7 +57,7 @@ class TestHomography:
class TestImageRegistrator:
- @pytest.mark.parametrize("model_type", ['homography', 'similarity', 'translation', 'scale', 'rotation'])
+ @pytest.mark.parametrize("model_type", ["homography", "similarity", "translation", "scale", "rotation"])
def test_smoke(self, device, dtype, model_type):
ir = kornia.geometry.transform.ImageRegistrator(model_type).to(device, dtype)
assert ir is not None
@@ -71,7 +71,7 @@ class TestImageRegistrator:
homography[..., 0, 2] = 0.01
img_src = torch.rand(1, ch, height, width, device=device, dtype=dtype)
img_dst = kornia.geometry.homography_warp(img_src, homography, (height, width), align_corners=False)
- IR = ImageRegistrator('Similarity', num_iterations=500, lr=3e-4, pyramid_levels=2).to(device, dtype)
+ IR = ImageRegistrator("Similarity", num_iterations=500, lr=3e-4, pyramid_levels=2).to(device, dtype)
model = IR.register(img_src, img_dst)
assert_close(model, homography, atol=1e-3, rtol=1e-3)
model, intermediate = IR.register(img_src, img_dst, output_intermediate_models=True)
@@ -80,16 +80,16 @@ class TestImageRegistrator:
@pytest.mark.slow
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
@pytest.mark.skipif(
- torch_version() == '2.0.0' and 'win' in sys.platform, reason='Tensor not matching on win with torch 2.0'
+ torch_version() == "2.0.0" and "win" in sys.platform, reason="Tensor not matching on win with torch 2.0"
)
def test_registration_real(self, device, dtype, data):
data_dev = utils.dict_to(data, device, dtype)
- IR = ImageRegistrator('homography', num_iterations=1200, lr=2e-2, pyramid_levels=5).to(device, dtype)
- model = IR.register(data_dev['image0'], data_dev['image1'])
- homography_gt = torch.inverse(data_dev['H_gt'])
+ IR = ImageRegistrator("homography", num_iterations=1200, lr=2e-2, pyramid_levels=5).to(device, dtype)
+ model = IR.register(data_dev["image0"], data_dev["image1"])
+ homography_gt = torch.inverse(data_dev["H_gt"])
homography_gt = homography_gt / homography_gt[2, 2]
- h0, w0 = data['image0'].shape[2], data['image0'].shape[3]
- h1, w1 = data['image1'].shape[2], data['image1'].shape[3]
+ h0, w0 = data["image0"].shape[2], data["image0"].shape[3]
+ h1, w1 = data["image1"].shape[2], data["image1"].shape[3]
model_denormalized = denormalize_homography(model, (h0, w0), (h1, w1))
model_denormalized = model_denormalized / model_denormalized[0, 2, 2]
diff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.py
index 56228860d..7ce7a571b 100644
--- a/test/geometry/transform/test_imgwarp.py
+++ b/test/geometry/transform/test_imgwarp.py
@@ -458,8 +458,8 @@ class TestWarpPerspective:
assert_close(patch_warped, expected)
def test_dynamo(self, device, dtype, torch_optimizer):
- if dtype == torch.float64 and torch_version() in {'2.0.0', '2.0.1'} and sys.platform == 'linux':
- pytest.xfail('Failling on CI on ubuntu with torch 2.0.0 for float64')
+ if dtype == torch.float64 and torch_version() in {"2.0.0", "2.0.1"} and sys.platform == "linux":
+ pytest.xfail("Failing on CI on ubuntu with torch 2.0.0 for float64")
img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
H_ab = kornia.eye_like(3, img)
args = (img, H_ab, (4, 5))
@@ -598,12 +598,12 @@ class TestRemap:
assert gradcheck(
kornia.geometry.remap,
- (img, grid[..., 0], grid[..., 1], 'bilinear', 'zeros', True),
+ (img, grid[..., 0], grid[..., 1], "bilinear", "zeros", True),
raise_exception=True,
fast_mode=True,
)
- @pytest.mark.skip(reason='Not fully support dynamo')
+ @pytest.mark.skip(reason="Not fully support dynamo")
def test_dynamo(self, device, dtype, torch_optimizer):
# TODO: add dynamo support to create_meshgrid
batch_size, channels, height, width = 1, 1, 3, 4
@@ -615,7 +615,7 @@ class TestRemap:
op = kornia.geometry.remap
op_script = torch_optimizer(op)
- inputs = (img, grid[..., 0], grid[..., 1], 'bilinear', 'zeros', True)
+ inputs = (img, grid[..., 0], grid[..., 1], "bilinear", "zeros", True)
actual = op_script(*inputs)
expected = op(*inputs)
assert_close(actual, expected, rtol=1e-4, atol=1e-4)
diff --git a/test/geometry/transform/test_imgwarp3d.py b/test/geometry/transform/test_imgwarp3d.py
index 11913f3f8..caa0d6ffc 100644
--- a/test/geometry/transform/test_imgwarp3d.py
+++ b/test/geometry/transform/test_imgwarp3d.py
@@ -38,7 +38,7 @@ class TestWarpAffine3d:
P = torch.rand(2, 3, 4, device=device, dtype=dtype)
P = kornia.geometry.convert_affinematrix_to_homography3d(P)
P_hat = (_torch_inverse_cast(P) @ P)[:, :3]
- output = proj.warp_affine3d(sample, P_hat, out_shape, flags='nearest')
+ output = proj.warp_affine3d(sample, P_hat, out_shape, flags="nearest")
assert_close(output, sample, rtol=1e-4, atol=1e-4)
def test_rotate_x(self, device, dtype):
diff --git a/test/geometry/transform/test_thin_plate_spline.py b/test/geometry/transform/test_thin_plate_spline.py
index 7eddb6b07..c42e789a7 100644
--- a/test/geometry/transform/test_thin_plate_spline.py
+++ b/test/geometry/transform/test_thin_plate_spline.py
@@ -15,13 +15,13 @@ def _sample_points(batch_size, device, dtype=torch.float32):
class TestTransformParameters:
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_smoke(self, batch_size, device, dtype):
src = torch.rand(batch_size, 4, 2, device=device)
out = kornia.geometry.transform.get_tps_transform(src, src)
assert len(out) == 2
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_no_warp(self, batch_size, device, dtype):
src = torch.rand(batch_size, 5, 2, device=device)
kernel, affine = kornia.geometry.transform.get_tps_transform(src, src)
@@ -31,7 +31,7 @@ class TestTransformParameters:
assert_close(kernel, target_kernel, atol=1e-4, rtol=1e-4)
assert_close(affine, target_affine, atol=1e-4, rtol=1e-4)
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_affine_only(self, batch_size, device, dtype):
src = torch.tensor([[[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0], [0.5, 0.5]]], device=device).repeat(
batch_size, 1, 1
@@ -40,7 +40,7 @@ class TestTransformParameters:
kernel, _ = kornia.geometry.transform.get_tps_transform(src, dst)
assert_close(kernel, torch.zeros_like(kernel), atol=1e-4, rtol=1e-4)
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_exception(self, batch_size, device, dtype):
with pytest.raises(TypeError):
src = torch.rand(batch_size, 5, 2).numpy()
@@ -51,17 +51,17 @@ class TestTransformParameters:
assert kornia.geometry.transform.get_tps_transform(src, src)
@pytest.mark.grad()
- @pytest.mark.parametrize('batch_size', [1, 3])
- @pytest.mark.parametrize('requires_grad', [True, False])
+ @pytest.mark.parametrize("batch_size", [1, 3])
+ @pytest.mark.parametrize("requires_grad", [True, False])
def test_gradcheck(self, batch_size, device, dtype, requires_grad):
- opts = {'device': device, 'dtype': torch.float64}
+ opts = {"device": device, "dtype": torch.float64}
src, dst = _sample_points(batch_size, **opts)
src.requires_grad_(requires_grad)
dst.requires_grad_(not requires_grad)
assert gradcheck(kornia.geometry.transform.get_tps_transform, (src, dst), raise_exception=True, fast_mode=True)
@pytest.mark.jit()
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_jit(self, batch_size, device, dtype):
src, dst = _sample_points(batch_size, device)
op = kornia.geometry.transform.get_tps_transform
@@ -73,21 +73,21 @@ class TestTransformParameters:
class TestWarpPoints:
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_smoke(self, batch_size, device, dtype):
src, dst = _sample_points(batch_size, device)
kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)
warp = kornia.geometry.transform.warp_points_tps(src, dst, kernel, affine)
assert warp.shape == src.shape
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_warp(self, batch_size, device, dtype):
src, dst = _sample_points(batch_size, device)
kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)
warp = kornia.geometry.transform.warp_points_tps(src, dst, kernel, affine)
assert_close(warp, dst, atol=1e-4, rtol=1e-4)
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_exception(self, batch_size, device, dtype):
src = torch.rand(batch_size, 5, 2)
kernel = torch.zeros_like(src)
@@ -122,10 +122,10 @@ class TestWarpPoints:
assert kornia.geometry.transform.warp_points_tps(src, src, kernel, affine_bad)
@pytest.mark.grad()
- @pytest.mark.parametrize('batch_size', [1, 3])
- @pytest.mark.parametrize('requires_grad', [True, False])
+ @pytest.mark.parametrize("batch_size", [1, 3])
+ @pytest.mark.parametrize("requires_grad", [True, False])
def test_gradcheck(self, batch_size, device, dtype, requires_grad):
- opts = {'device': device, 'dtype': torch.float64}
+ opts = {"device": device, "dtype": torch.float64}
src, dst = _sample_points(batch_size, **opts)
kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)
kernel.requires_grad_(requires_grad)
@@ -135,7 +135,7 @@ class TestWarpPoints:
)
@pytest.mark.jit()
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_jit(self, batch_size, device, dtype):
src, dst = _sample_points(batch_size, device)
kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)
@@ -145,7 +145,7 @@ class TestWarpPoints:
class TestWarpImage:
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_smoke(self, batch_size, device, dtype):
src, dst = _sample_points(batch_size, device)
tensor = torch.rand(batch_size, 3, 32, 32, device=device)
@@ -156,7 +156,7 @@ class TestWarpImage:
@pytest.mark.skipif(
torch_version_ge(1, 10), reason="for some reason the solver detects singular matrices in pytorch >=1.10."
)
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_warp(self, batch_size, device, dtype):
src = torch.tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, -1.0], [0.0, 0.0]]], device=device).repeat(
batch_size, 1, 1
@@ -175,7 +175,7 @@ class TestWarpImage:
warp = kornia.geometry.transform.warp_image_tps(tensor, src, kernel, affine)
assert_close(warp, expected, atol=1e-4, rtol=1e-4)
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_exception(self, batch_size, device, dtype):
image = torch.rand(batch_size, 3, 32, 32)
dst = torch.rand(batch_size, 5, 2)
@@ -211,9 +211,9 @@ class TestWarpImage:
assert kornia.geometry.transform.warp_image_tps(image, dst, kernel, affine_bad)
@pytest.mark.grad()
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_gradcheck(self, batch_size, device, dtype):
- opts = {'device': device, 'dtype': torch.float64}
+ opts = {"device": device, "dtype": torch.float64}
src, dst = _sample_points(batch_size, **opts)
kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)
image = torch.rand(batch_size, 3, 8, 8, requires_grad=True, **opts)
@@ -228,7 +228,7 @@ class TestWarpImage:
)
@pytest.mark.jit()
- @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize("batch_size", [1, 3])
def test_jit(self, batch_size, device, dtype):
src, dst = _sample_points(batch_size, device)
kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)
diff --git a/test/image/test_image.py b/test/image/test_image.py
index 8a8956c77..1c64f35c8 100644
--- a/test/image/test_image.py
+++ b/test/image/test_image.py
@@ -63,7 +63,7 @@ class TestImage:
assert_close(data, Image.from_dlpack(img.to_dlpack()).data)
@pytest.mark.skipif(torch_version_le(1, 9, 1), reason="dlpack is broken in torch<=1.9.1")
- @pytest.mark.xfail(reason='This may fail some time due to jpeg compression assertion')
+ @pytest.mark.xfail(reason="This may fail some time due to jpeg compression assertion")
def test_load_write(self, tmp_path: Path) -> None:
data = torch.randint(0, 255, (3, 4, 5), dtype=torch.uint8)
img = Image.from_numpy(data.numpy(), channels_order=ChannelsOrder.CHANNELS_FIRST)
diff --git a/test/integration/test_conversions.py b/test/integration/test_conversions.py
index 98a045e25..39a910e2d 100644
--- a/test/integration/test_conversions.py
+++ b/test/integration/test_conversions.py
@@ -9,7 +9,7 @@ from kornia.testing import assert_close
@pytest.fixture()
def atol(device, dtype):
"""Lower tolerance for cuda-float16 only."""
- if 'cuda' in device.type and dtype == torch.float16:
+ if "cuda" in device.type and dtype == torch.float16:
return 1.0e-3
return 1.0e-4
@@ -17,7 +17,7 @@ def atol(device, dtype):
@pytest.fixture()
def rtol(device, dtype):
"""Lower tolerance for cuda-float16 only."""
- if 'cuda' in device.type and dtype == torch.float16:
+ if "cuda" in device.type and dtype == torch.float16:
return 1.0e-3
return 1.0e-4
@@ -164,26 +164,26 @@ class TestAngleOfRotations:
def axis_and_angle_to_rotation_matrix(axis_name: str, angle: torch.Tensor, device, dtype):
"""See also: https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations."""
axis_name = axis_name.lower()
- assert axis_name in ('x', 'y', 'z')
+ assert axis_name in ("x", "y", "z")
sn = torch.sin(angle)
cs = torch.cos(angle)
ones = torch.ones_like(sn)
zeros = torch.zeros_like(sn)
- if axis_name == 'x':
+ if axis_name == "x":
axis = torch.tensor((1.0, 0.0, 0.0), device=device, dtype=dtype).repeat(angle.size())
rot_m = torch.stack((ones, zeros, zeros, zeros, cs, -sn, zeros, sn, cs), dim=2).view(-1, 3, 3)
- elif axis_name == 'y':
+ elif axis_name == "y":
axis = torch.tensor((0.0, 1.0, 0.0), device=device, dtype=dtype).repeat(angle.size())
rot_m = torch.stack((cs, zeros, sn, zeros, ones, zeros, -sn, zeros, cs), dim=2).view(-1, 3, 3)
- elif axis_name == 'z':
+ elif axis_name == "z":
axis = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype).repeat(angle.size())
rot_m = torch.stack((cs, -sn, zeros, sn, cs, zeros, zeros, zeros, ones), dim=2).view(-1, 3, 3)
else:
- raise NotImplementedError(f'Not prepared for axis with name {axis_name}')
+ raise NotImplementedError(f"Not prepared for axis with name {axis_name}")
return rot_m, axis
- @pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
+ @pytest.mark.parametrize("axis_name", ("x", "y", "z"))
def test_axis_angle_to_rotation_matrix(self, axis_name, device, dtype, atol, rtol):
# Random angle in [-pi..pi]
angle = torch.tensor((np.random.random(size=(2, 1)) * 2.0 * np.pi - np.pi), device=device, dtype=dtype)
@@ -198,17 +198,17 @@ class TestAngleOfRotations:
assert axis.shape[-2] == angle.numel()
# Make sure the returned axis matches the named one, and the appropriate column
- if axis_name == 'x':
+ if axis_name == "x":
assert_close(axis, torch.tensor(((1.0, 0.0, 0.0),) * angle.numel(), device=device, dtype=dtype))
assert_close(axis, rot_m[..., :3, 0])
- elif axis_name == 'y':
+ elif axis_name == "y":
assert_close(axis, torch.tensor(((0.0, 1.0, 0.0),) * angle.numel(), device=device, dtype=dtype))
assert_close(axis, rot_m[..., :3, 1])
- elif axis_name == 'z':
+ elif axis_name == "z":
assert_close(axis, torch.tensor(((0.0, 0.0, 1.0),) * angle.numel(), device=device, dtype=dtype))
assert_close(axis, rot_m[..., :3, 2])
else:
- raise NotImplementedError(f'Not prepared for axis_name {axis_name}')
+ raise NotImplementedError(f"Not prepared for axis_name {axis_name}")
# Make sure axes are perpendicular
zero = torch.zeros_like(angle).unsqueeze(-1)
@@ -222,7 +222,7 @@ class TestAngleOfRotations:
assert_close(rot_m[..., :3, 1].norm(p=2, dim=-1, keepdim=True), one, atol=atol, rtol=rtol)
assert_close(rot_m[..., :3, 2].norm(p=2, dim=-1, keepdim=True), one, atol=atol, rtol=rtol)
- @pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
+ @pytest.mark.parametrize("axis_name", ("x", "y", "z"))
@pytest.mark.parametrize("angle_deg", (-179.9, -135.0, -90.0, -45.0, 0.0, 45, 90, 135, 179.9))
def test_matrix_angle(self, axis_name, angle_deg, device, dtype):
angle = (angle_deg * kornia.pi / 180.0).to(dtype).to(device).view(1, 1)
@@ -232,7 +232,7 @@ class TestAngleOfRotations:
matrix_angle_abs = TestAngleOfRotations.matrix_angle_abs(rot_m)
assert_close(torch.abs(angle), matrix_angle_abs)
- @pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
+ @pytest.mark.parametrize("axis_name", ("x", "y", "z"))
@pytest.mark.parametrize("angle_deg", (-179.9, -90.0, -45.0, 0.0, 45, 90, 179.9))
def test_quaternion(self, axis_name, angle_deg, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
@@ -260,7 +260,7 @@ class TestAngleOfRotations:
matrix_angle_abs = TestAngleOfRotations.matrix_angle_abs(rot_m)
assert_close(torch.abs(angle_hat), matrix_angle_abs, atol=atol, rtol=rtol)
- @pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
+ @pytest.mark.parametrize("axis_name", ("x", "y", "z"))
@pytest.mark.parametrize("angle_deg", (-179.9, -90.0, -45.0, 0, 45, 90, 179.9))
def test_axis_angle(self, axis_name, angle_deg, device, dtype, atol, rtol):
angle = (angle_deg * kornia.pi / 180.0).to(dtype).to(device).repeat(2, 1)
@@ -279,7 +279,7 @@ class TestAngleOfRotations:
matrix_angle_abs = TestAngleOfRotations.matrix_angle_abs(rot_m)
assert_close(torch.abs(angle_hat), matrix_angle_abs, atol=atol, rtol=rtol)
- @pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
+ @pytest.mark.parametrize("axis_name", ("x", "y", "z"))
@pytest.mark.parametrize("angle_deg", (-179.9, -90.0, -45.0, 0, 45, 90, 179.9))
def test_log_quaternion(self, axis_name, angle_deg, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
diff --git a/test/integration/test_focal.py b/test/integration/test_focal.py
index 98b51d58c..eb9395ce7 100644
--- a/test/integration/test_focal.py
+++ b/test/integration/test_focal.py
@@ -47,7 +47,7 @@ class TestIntegrationFocalLoss:
optimizer = optim.Adam(m.parameters(), lr=self.lr)
- criterion = kornia.losses.FocalLoss(alpha=self.alpha, gamma=self.gamma, reduction='mean')
+ criterion = kornia.losses.FocalLoss(alpha=self.alpha, gamma=self.gamma, reduction="mean")
# NOTE: uncomment to compare against vanilla cross entropy
# criterion = nn.CrossEntropyLoss()
diff --git a/test/io/test_io_image.py b/test/io/test_io_image.py
index 52e1542ab..8f0fcda9d 100644
--- a/test/io/test_io_image.py
+++ b/test/io/test_io_image.py
@@ -42,7 +42,7 @@ def _download_image(url: str, filename: str = "") -> Path:
return Path(filename)
[email protected](scope='session')
[email protected](scope="session")
def png_image(tmp_path_factory):
url = "https://github.com/kornia/data/raw/main/simba.png"
filename = tmp_path_factory.mktemp("data") / "image.png"
@@ -50,7 +50,7 @@ def png_image(tmp_path_factory):
return filename
[email protected](scope='session')
[email protected](scope="session")
def jpg_image(tmp_path_factory):
url = "https://github.com/kornia/data/raw/main/crowd.jpg"
filename = tmp_path_factory.mktemp("data") / "image.jpg"
@@ -58,9 +58,9 @@ def jpg_image(tmp_path_factory):
return filename
[email protected](scope='session')
[email protected](scope="session")
def images_fn(png_image, jpg_image):
- return {'png': png_image, 'jpg': jpg_image}
+ return {"png": png_image, "jpg": jpg_image}
@pytest.mark.skipif(not available_package(), reason="kornia_rs only supports python >=3.7 and pt >= 1.10.0")
diff --git a/test/losses/test_hd.py b/test/losses/test_hd.py
index d4d761b66..b5490cbb8 100644
--- a/test/losses/test_hd.py
+++ b/test/losses/test_hd.py
@@ -8,7 +8,7 @@ from kornia.testing import assert_close
class TestHausdorffLoss:
- @pytest.mark.parametrize("reduction", ['mean', 'none', 'sum'])
+ @pytest.mark.parametrize("reduction", ["mean", "none", "sum"])
@pytest.mark.parametrize(
"hd,shape", [[kornia.losses.HausdorffERLoss, (10, 10)], [kornia.losses.HausdorffERLoss3D, (10, 10, 10)]]
)
@@ -23,28 +23,28 @@ class TestHausdorffLoss:
def test_exception_2d(self):
with pytest.raises(ValueError) as errinf:
kornia.losses.HausdorffERLoss()((torch.rand(1, 2, 1) > 0.5) * 1, (torch.rand(1, 1, 1, 2) > 0.5) * 1)
- assert 'Only 2D images supported. Got ' in str(errinf)
+ assert "Only 2D images supported. Got " in str(errinf)
with pytest.raises(ValueError) as errinf:
kornia.losses.HausdorffERLoss()(
(torch.rand(1, 2, 1, 1) > 0.5) * 1, torch.tensor([[[[1]]]], dtype=torch.float32)
)
- assert 'Expect long type target value in range' in str(errinf)
+ assert "Expect long type target value in range" in str(errinf)
with pytest.raises(ValueError) as errinf:
kornia.losses.HausdorffERLoss()((torch.rand(1, 2, 1, 1) > 0.5) * 1, (torch.rand(1, 1, 1, 2) > 0.5) * 1)
- assert 'Prediction and target need to be of same size, and target should not be one-hot.' in str(errinf)
+ assert "Prediction and target need to be of same size, and target should not be one-hot." in str(errinf)
def test_exception_3d(self):
with pytest.raises(ValueError) as errinf:
kornia.losses.HausdorffERLoss3D()((torch.rand(1, 2, 1) > 0.5) * 1, (torch.rand(1, 1, 1, 2) > 0.5) * 1)
- assert 'Only 3D images supported. Got ' in str(errinf)
+ assert "Only 3D images supported. Got " in str(errinf)
with pytest.raises(ValueError) as errinf:
kornia.losses.HausdorffERLoss3D()(
(torch.rand(1, 2, 1, 1, 1) > 0.5) * 1, torch.tensor([[[[[5]]]]], dtype=torch.float32)
)
- assert 'Invalid target value' in str(errinf)
+ assert "Invalid target value" in str(errinf)
def test_numeric(self, device, dtype):
num_classes = 3
diff --git a/test/losses/test_losses.py b/test/losses/test_losses.py
index 56629ea74..f8f662d08 100644
--- a/test/losses/test_losses.py
+++ b/test/losses/test_losses.py
@@ -11,7 +11,7 @@ from kornia.utils import torch_meshgrid
class TestBinaryFocalLossWithLogits:
- @pytest.mark.parametrize('reduction', ['none', 'mean', 'sum'])
+ @pytest.mark.parametrize("reduction", ["none", "mean", "sum"])
def test_value_same_as_torch_bce_loss(self, device, dtype, reduction):
logits = torch.rand(2, 3, 2, dtype=dtype, device=device)
labels = torch.rand(2, 3, 2, dtype=dtype, device=device)
@@ -22,7 +22,7 @@ class TestBinaryFocalLossWithLogits:
torch_bce_loss = F.binary_cross_entropy_with_logits(logits, labels, reduction=reduction)
assert_close(focal_equivalent_bce_loss, torch_bce_loss)
- @pytest.mark.parametrize('reduction', ['none', 'mean', 'sum'])
+ @pytest.mark.parametrize("reduction", ["none", "mean", "sum"])
def test_value_same_as_torch_bce_loss_pos_weight_weight(self, device, dtype, reduction):
num_classes = 3
logits = torch.rand(2, num_classes, 2, dtype=dtype, device=device)
@@ -39,9 +39,9 @@ class TestBinaryFocalLossWithLogits:
)
assert_close(focal_equivalent_bce_loss, torch_bce_loss)
- @pytest.mark.parametrize('reduction,expected_shape', [('none', (2, 3, 2)), ('mean', ()), ('sum', ())])
- @pytest.mark.parametrize('alpha', [None, 0.2, 0.5])
- @pytest.mark.parametrize('gamma', [0.0, 1.0, 2.0])
+ @pytest.mark.parametrize("reduction,expected_shape", [("none", (2, 3, 2)), ("mean", ()), ("sum", ())])
+ @pytest.mark.parametrize("alpha", [None, 0.2, 0.5])
+ @pytest.mark.parametrize("gamma", [0.0, 1.0, 2.0])
def test_shape_alpha_gamma(self, device, dtype, reduction, expected_shape, alpha, gamma):
logits = torch.rand(2, 3, 2, dtype=dtype, device=device)
labels = torch.rand(2, 3, 2, dtype=dtype, device=device)
@@ -51,7 +51,7 @@ class TestBinaryFocalLossWithLogits:
).shape
assert actual_shape == expected_shape
- @pytest.mark.parametrize('reduction,expected_shape', [('none', (2, 3, 2)), ('mean', ()), ('sum', ())])
+ @pytest.mark.parametrize("reduction,expected_shape", [("none", (2, 3, 2)), ("mean", ()), ("sum", ())])
@pytest.mark.parametrize("pos_weight", [None, (1, 2, 5)])
@pytest.mark.parametrize("weight", [None, (0.2, 0.5, 0.8)])
def test_shape_pos_weight_weight(self, device, dtype, reduction, expected_shape, pos_weight, weight):
@@ -107,9 +107,9 @@ class TestBinaryFocalLossWithLogits:
class TestFocalLoss:
- @pytest.mark.parametrize('reduction,expected_shape', [('none', (2, 3, 3, 2)), ('mean', ()), ('sum', ())])
- @pytest.mark.parametrize('alpha', [None, 0.2, 0.5])
- @pytest.mark.parametrize('gamma', [0.0, 1.0, 2.0])
+ @pytest.mark.parametrize("reduction,expected_shape", [("none", (2, 3, 3, 2)), ("mean", ()), ("sum", ())])
+ @pytest.mark.parametrize("alpha", [None, 0.2, 0.5])
+ @pytest.mark.parametrize("gamma", [0.0, 1.0, 2.0])
def test_shape_alpha_gamma(self, device, dtype, reduction, expected_shape, alpha, gamma):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
@@ -118,7 +118,7 @@ class TestFocalLoss:
actual_shape = kornia.losses.focal_loss(logits, labels, alpha=alpha, gamma=gamma, reduction=reduction).shape
assert actual_shape == expected_shape
- @pytest.mark.parametrize('reduction,expected_shape', [('none', (2, 3)), ('mean', ()), ('sum', ())])
+ @pytest.mark.parametrize("reduction,expected_shape", [("none", (2, 3)), ("mean", ()), ("sum", ())])
def test_shape_target_with_only_one_dim(self, device, dtype, reduction, expected_shape):
num_classes = 3
logits = torch.rand(2, num_classes, device=device, dtype=dtype)
@@ -127,7 +127,7 @@ class TestFocalLoss:
actual_shape = kornia.losses.focal_loss(logits, labels, alpha=0.1, gamma=1.5, reduction=reduction).shape
assert actual_shape == expected_shape
- @pytest.mark.parametrize('reduction,expected_shape', [('none', (2, 3, 3, 2)), ('mean', ()), ('sum', ())])
+ @pytest.mark.parametrize("reduction,expected_shape", [("none", (2, 3, 3, 2)), ("mean", ()), ("sum", ())])
@pytest.mark.parametrize("weight", [None, (0.2, 0.5, 0.8)])
def test_shape_weight(self, device, dtype, reduction, expected_shape, weight):
num_classes = 3
@@ -188,20 +188,20 @@ class TestTverskyLoss:
criterion = kornia.losses.TverskyLoss(alpha=0.5, beta=0.5)
with pytest.raises(TypeError) as errinfo:
- criterion('not a tensor', torch.rand(1))
- assert 'pred type is not a torch.Tensor. Got' in str(errinfo)
+ criterion("not a tensor", torch.rand(1))
+ assert "pred type is not a torch.Tensor. Got" in str(errinfo)
with pytest.raises(ValueError) as errinfo:
criterion(torch.rand(1), torch.rand(1))
- assert 'Invalid pred shape, we expect BxNxHxW. Got:' in str(errinfo)
+ assert "Invalid pred shape, we expect BxNxHxW. Got:" in str(errinfo)
with pytest.raises(ValueError) as errinfo:
criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 2))
- assert 'pred and target shapes must be the same. Got:' in str(errinfo)
+ assert "pred and target shapes must be the same. Got:" in str(errinfo)
with pytest.raises(ValueError) as errinfo:
- criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device='meta'))
- assert 'pred and target must be in the same device. Got:' in str(errinfo)
+ criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device="meta"))
+ assert "pred and target must be in the same device. Got:" in str(errinfo)
def test_all_zeros(self, device, dtype):
num_classes = 3
@@ -281,15 +281,15 @@ class TestDiceLoss:
def test_exception(self):
with pytest.raises(ValueError) as errinf:
kornia.losses.DiceLoss()(torch.rand(1, 1, 1), torch.rand(1, 1, 1))
- assert 'Invalid pred shape, we expect BxNxHxW. Got:' in str(errinf)
+ assert "Invalid pred shape, we expect BxNxHxW. Got:" in str(errinf)
with pytest.raises(ValueError) as errinf:
kornia.losses.DiceLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 2))
- assert 'pred and target shapes must be the same. Got: ' in str(errinf)
+ assert "pred and target shapes must be the same. Got: " in str(errinf)
with pytest.raises(ValueError) as errinf:
- kornia.losses.DiceLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device='meta'))
- assert 'pred and target must be in the same device. Got:' in str(errinf)
+ kornia.losses.DiceLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device="meta"))
+ assert "pred and target must be in the same device. Got:" in str(errinf)
def test_averaging_micro(self, device, dtype):
num_classes = 2
@@ -388,33 +388,33 @@ class TestDepthSmoothnessLoss:
def test_exception(self):
with pytest.raises(TypeError) as errinf:
kornia.losses.InverseDepthSmoothnessLoss()(1, 1)
- assert 'Input idepth type is not a torch.Tensor. Got' in str(errinf)
+ assert "Input idepth type is not a torch.Tensor. Got" in str(errinf)
with pytest.raises(TypeError) as errinf:
kornia.losses.InverseDepthSmoothnessLoss()(torch.rand(1), 1)
- assert 'Input image type is not a torch.Tensor. Got' in str(errinf)
+ assert "Input image type is not a torch.Tensor. Got" in str(errinf)
with pytest.raises(ValueError) as errinf:
kornia.losses.InverseDepthSmoothnessLoss()(torch.rand(1, 1), torch.rand(1, 1, 1, 1))
- assert 'Invalid idepth shape, we expect BxCxHxW. Got' in str(errinf)
+ assert "Invalid idepth shape, we expect BxCxHxW. Got" in str(errinf)
with pytest.raises(ValueError) as errinf:
kornia.losses.InverseDepthSmoothnessLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1))
- assert 'Invalid image shape, we expect BxCxHxW. Got:' in str(errinf)
+ assert "Invalid image shape, we expect BxCxHxW. Got:" in str(errinf)
with pytest.raises(ValueError) as errinf:
kornia.losses.InverseDepthSmoothnessLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 2))
- assert 'idepth and image shapes must be the same. Got' in str(errinf)
+ assert "idepth and image shapes must be the same. Got" in str(errinf)
with pytest.raises(ValueError) as errinf:
- kornia.losses.InverseDepthSmoothnessLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device='meta'))
- assert 'idepth and image must be in the same device. Got:' in str(errinf)
+ kornia.losses.InverseDepthSmoothnessLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device="meta"))
+ assert "idepth and image must be in the same device. Got:" in str(errinf)
with pytest.raises(ValueError) as errinf:
kornia.losses.InverseDepthSmoothnessLoss()(
torch.rand(1, 1, 1, 1, dtype=torch.float32), torch.rand(1, 1, 1, 1, dtype=torch.float64)
)
- assert 'idepth and image must be in the same dtype. Got:' in str(errinf)
+ assert "idepth and image must be in the same dtype. Got:" in str(errinf)
def test_dynamo(self, device, dtype, torch_optimizer):
image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
@@ -575,7 +575,7 @@ class TestTotalVariation:
],
)
def test_tv_on_constant_int(self, device, pred, expected):
- actual = kornia.losses.total_variation(pred.to(device, dtype=torch.int32), reduction='mean')
+ actual = kornia.losses.total_variation(pred.to(device, dtype=torch.int32), reduction="mean")
assert_close(actual, expected.to(device))
# Total variation for 3D tensors
@@ -775,11 +775,11 @@ class TestLovaszHingeLoss:
with pytest.raises(ValueError) as errinfo:
criterion(torch.rand(1, 1, 1, 2), torch.rand(1, 1, 1))
- assert 'pred and target shapes must be the same. Got:' in str(errinfo)
+ assert "pred and target shapes must be the same. Got:" in str(errinfo)
with pytest.raises(ValueError) as errinfo:
- criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, device='meta'))
- assert 'pred and target must be in the same device. Got:' in str(errinfo)
+ criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, device="meta"))
+ assert "pred and target must be in the same device. Got:" in str(errinfo)
def test_multi_class(self, device, dtype):
num_classes = 5
@@ -862,7 +862,7 @@ class TestLovaszSoftmaxLoss:
assert "pred and target shapes must be the same. Got:" in str(errinfo)
with pytest.raises(ValueError) as errinfo:
- criterion(torch.rand(1, 2, 1, 1), torch.rand(1, 1, 1, device='meta'))
+ criterion(torch.rand(1, 2, 1, 1), torch.rand(1, 1, 1, device="meta"))
assert "pred and target must be in the same device. Got:" in str(errinfo)
def test_binary(self, device, dtype):
@@ -897,7 +897,7 @@ class TestLovaszSoftmaxLoss:
logits = tensor_to_gradcheck_var(logits) # to var
assert gradcheck(kornia.losses.lovasz_softmax_loss, (logits, labels), raise_exception=True, fast_mode=True)
- @pytest.mark.skip(reason='Not matching results')
+ @pytest.mark.skip(reason="Not matching results")
def test_dynamo(self, device, dtype, torch_optimizer):
# TODO: investigate if we can fix it or report the issue
num_classes = 6
@@ -934,10 +934,10 @@ class TestWelschLoss(BaseTester):
def test_cardinality(self, shape, device, dtype):
img = torch.rand(shape, device=device, dtype=dtype)
- actual = kornia.losses.WelschLoss(reduction='none')(img, img)
+ actual = kornia.losses.WelschLoss(reduction="none")(img, img)
assert actual.shape == shape
- actual = kornia.losses.WelschLoss(reduction='mean')(img, img)
+ actual = kornia.losses.WelschLoss(reduction="mean")(img, img)
assert actual.shape == ()
def test_gradcheck(self, device):
@@ -980,9 +980,9 @@ class TestWelschLoss(BaseTester):
actual = kornia.losses.welsch_loss(img1, img2, reduction=reduction)
- if reduction == 'mean':
+ if reduction == "mean":
expected = torch.tensor(0.39346934028, device=device, dtype=dtype)
- elif reduction == 'sum':
+ elif reduction == "sum":
expected = (torch.ones_like(img1, device=device, dtype=dtype) * 0.39346934028).sum()
self.assert_close(actual, expected)
@@ -992,23 +992,23 @@ class TestWelschLoss(BaseTester):
# wrong reduction
with pytest.raises(Exception) as execinfo:
- kornia.losses.welsch_loss(img, img, reduction='test')
- assert 'Given type of reduction is not supported. Got: test' in str(execinfo)
+ kornia.losses.welsch_loss(img, img, reduction="test")
+ assert "Given type of reduction is not supported. Got: test" in str(execinfo)
# Check if both are tensors
with pytest.raises(TypeError) as errinfo:
kornia.losses.welsch_loss(1.0, img)
- assert 'Not a Tensor type. Got:' in str(errinfo)
+ assert "Not a Tensor type. Got:" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
kornia.losses.welsch_loss(img, 1.0)
- assert 'Not a Tensor type. Got:' in str(errinfo)
+ assert "Not a Tensor type. Got:" in str(errinfo)
# Check if same shape
img_b = torch.rand(1, 1, 3, 3, 4, device=device, dtype=dtype)
with pytest.raises(TypeError) as errinfo:
kornia.losses.welsch_loss(img, img_b, 3)
- assert 'Not same shape for tensors. Got:' in str(errinfo)
+ assert "Not same shape for tensors. Got:" in str(errinfo)
class TestCauchyLoss(BaseTester):
@@ -1025,35 +1025,35 @@ class TestCauchyLoss(BaseTester):
# wrong reduction
with pytest.raises(Exception) as execinfo:
- kornia.losses.cauchy_loss(img, img, reduction='test')
- assert 'Given type of reduction is not supported. Got: test' in str(execinfo)
+ kornia.losses.cauchy_loss(img, img, reduction="test")
+ assert "Given type of reduction is not supported. Got: test" in str(execinfo)
# Check if both are tensors
with pytest.raises(TypeError) as errinfo:
kornia.losses.cauchy_loss(1.0, img)
- assert 'Not a Tensor type. Got:' in str(errinfo)
+ assert "Not a Tensor type. Got:" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
kornia.losses.cauchy_loss(img, 1.0)
- assert 'Not a Tensor type. Got:' in str(errinfo)
+ assert "Not a Tensor type. Got:" in str(errinfo)
# Check if same shape
img_b = torch.rand(1, 1, 3, 3, 4, device=device, dtype=dtype)
with pytest.raises(TypeError) as errinfo:
kornia.losses.cauchy_loss(img, img_b, 3)
- assert 'Not same shape for tensors. Got:' in str(errinfo)
+ assert "Not same shape for tensors. Got:" in str(errinfo)
@pytest.mark.parametrize("shape", [(1, 3, 5, 5), (2, 5, 5)])
def test_cardinality(self, shape, device, dtype):
img = torch.rand(shape, device=device, dtype=dtype)
- actual = kornia.losses.cauchy_loss(img, img, reduction='none')
+ actual = kornia.losses.cauchy_loss(img, img, reduction="none")
assert actual.shape == shape
- actual = kornia.losses.cauchy_loss(img, img, reduction='sum')
+ actual = kornia.losses.cauchy_loss(img, img, reduction="sum")
assert actual.shape == ()
- actual = kornia.losses.cauchy_loss(img, img, reduction='mean')
+ actual = kornia.losses.cauchy_loss(img, img, reduction="mean")
assert actual.shape == ()
def test_gradcheck(self, device):
@@ -1097,9 +1097,9 @@ class TestCauchyLoss(BaseTester):
actual = kornia.losses.cauchy_loss(img1, img2, reduction=reduction)
- if reduction == 'mean':
+ if reduction == "mean":
expected = torch.tensor(0.40546512603759766, device=device, dtype=dtype)
- elif reduction == 'sum':
+ elif reduction == "sum":
expected = (torch.ones_like(img1, device=device, dtype=dtype) * 0.40546512603759766).sum()
self.assert_close(actual, expected)
@@ -1119,35 +1119,35 @@ class TestGemanMcclureLossLoss(BaseTester):
# wrong reduction
with pytest.raises(Exception) as execinfo:
- kornia.losses.geman_mcclure_loss(img, img, reduction='test')
- assert 'Given type of reduction is not supported. Got: test' in str(execinfo)
+ kornia.losses.geman_mcclure_loss(img, img, reduction="test")
+ assert "Given type of reduction is not supported. Got: test" in str(execinfo)
# Check if both are tensors
with pytest.raises(TypeError) as errinfo:
kornia.losses.geman_mcclure_loss(1.0, img)
- assert 'Not a Tensor type. Got:' in str(errinfo)
+ assert "Not a Tensor type. Got:" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
kornia.losses.geman_mcclure_loss(img, 1.0)
- assert 'Not a Tensor type. Got:' in str(errinfo)
+ assert "Not a Tensor type. Got:" in str(errinfo)
# Check if same shape
img_b = torch.rand(1, 1, 3, 3, 4, device=device, dtype=dtype)
with pytest.raises(TypeError) as errinfo:
kornia.losses.geman_mcclure_loss(img, img_b, 3)
- assert 'Not same shape for tensors. Got:' in str(errinfo)
+ assert "Not same shape for tensors. Got:" in str(errinfo)
@pytest.mark.parametrize("shape", [(1, 3, 5, 5), (2, 5, 5)])
def test_cardinality(self, shape, device, dtype):
img = torch.rand(shape, device=device, dtype=dtype)
- actual = kornia.losses.geman_mcclure_loss(img, img, reduction='none')
+ actual = kornia.losses.geman_mcclure_loss(img, img, reduction="none")
assert actual.shape == shape
- actual = kornia.losses.geman_mcclure_loss(img, img, reduction='sum')
+ actual = kornia.losses.geman_mcclure_loss(img, img, reduction="sum")
assert actual.shape == ()
- actual = kornia.losses.geman_mcclure_loss(img, img, reduction='mean')
+ actual = kornia.losses.geman_mcclure_loss(img, img, reduction="mean")
assert actual.shape == ()
def test_gradcheck(self, device):
@@ -1191,9 +1191,9 @@ class TestGemanMcclureLossLoss(BaseTester):
actual = kornia.losses.geman_mcclure_loss(img1, img2, reduction=reduction)
- if reduction == 'mean':
+ if reduction == "mean":
expected = torch.tensor(0.4, device=device, dtype=dtype)
- elif reduction == 'sum':
+ elif reduction == "sum":
expected = (torch.ones_like(img1, device=device, dtype=dtype) * 0.4).sum()
self.assert_close(actual, expected)
@@ -1213,35 +1213,35 @@ class TestCharbonnierLoss(BaseTester):
# wrong reduction
with pytest.raises(Exception) as execinfo:
- kornia.losses.charbonnier_loss(img, img, reduction='test')
- assert 'Given type of reduction is not supported. Got: test' in str(execinfo)
+ kornia.losses.charbonnier_loss(img, img, reduction="test")
+ assert "Given type of reduction is not supported. Got: test" in str(execinfo)
# Check if both are tensors
with pytest.raises(TypeError) as errinfo:
kornia.losses.charbonnier_loss(1.0, img)
- assert 'Not a Tensor type. Got:' in str(errinfo)
+ assert "Not a Tensor type. Got:" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
kornia.losses.charbonnier_loss(img, 1.0)
- assert 'Not a Tensor type. Got:' in str(errinfo)
+ assert "Not a Tensor type. Got:" in str(errinfo)
# Check if same shape
img_b = torch.rand(1, 1, 3, 3, 4, device=device, dtype=dtype)
with pytest.raises(TypeError) as errinfo:
kornia.losses.charbonnier_loss(img, img_b, 3)
- assert 'Not same shape for tensors. Got:' in str(errinfo)
+ assert "Not same shape for tensors. Got:" in str(errinfo)
@pytest.mark.parametrize("shape", [(1, 3, 5, 5), (2, 5, 5)])
def test_cardinality(self, shape, device, dtype):
img = torch.rand(shape, device=device, dtype=dtype)
- actual = kornia.losses.charbonnier_loss(img, img, reduction='none')
+ actual = kornia.losses.charbonnier_loss(img, img, reduction="none")
assert actual.shape == shape
- actual = kornia.losses.charbonnier_loss(img, img, reduction='sum')
+ actual = kornia.losses.charbonnier_loss(img, img, reduction="sum")
assert actual.shape == ()
- actual = kornia.losses.charbonnier_loss(img, img, reduction='mean')
+ actual = kornia.losses.charbonnier_loss(img, img, reduction="mean")
assert actual.shape == ()
def test_gradcheck(self, device):
@@ -1285,9 +1285,9 @@ class TestCharbonnierLoss(BaseTester):
actual = kornia.losses.charbonnier_loss(img1, img2, reduction=reduction)
- if reduction == 'mean':
+ if reduction == "mean":
expected = torch.tensor(0.41421356237, device=device, dtype=dtype)
- elif reduction == 'sum':
+ elif reduction == "sum":
expected = (torch.ones_like(img1, device=device, dtype=dtype) * 0.41421356237).sum()
self.assert_close(actual, expected)
diff --git a/test/losses/test_ssim.py b/test/losses/test_ssim.py
index aa6c323a2..f61b701bf 100644
--- a/test/losses/test_ssim.py
+++ b/test/losses/test_ssim.py
@@ -16,15 +16,15 @@ class TestSSIMLoss:
ssim1 = kornia.losses.ssim_loss(img1, img1, window_size=5, reduction="none")
ssim2 = kornia.losses.ssim_loss(img2, img2, window_size=5, reduction="none")
- tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
+ tol_val: float = utils._get_precision_by_name(device, "xla", 1e-1, 1e-4)
assert_close(ssim1, torch.zeros_like(img1), rtol=tol_val, atol=tol_val)
assert_close(ssim2, torch.zeros_like(img2), rtol=tol_val, atol=tol_val)
@pytest.mark.parametrize("window_size", [5, 11])
- @pytest.mark.parametrize("reduction_type", ["mean", "sum", 'none'])
+ @pytest.mark.parametrize("reduction_type", ["mean", "sum", "none"])
@pytest.mark.parametrize("batch_shape", [(1, 1, 10, 16), (2, 4, 8, 15)])
def test_ssim(self, device, dtype, batch_shape, window_size, reduction_type):
- if device.type == 'xla':
+ if device.type == "xla":
pytest.skip("test highly unstable with tpu")
# input data
@@ -32,8 +32,8 @@ class TestSSIMLoss:
loss = kornia.losses.ssim_loss(img, img, window_size, reduction=reduction_type)
- tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
- if reduction_type == 'none':
+ tol_val: float = utils._get_precision_by_name(device, "xla", 1e-1, 1e-4)
+ if reduction_type == "none":
expected = torch.zeros_like(img)
else:
expected = torch.tensor(0.0, device=device, dtype=dtype)
@@ -44,7 +44,7 @@ class TestSSIMLoss:
img1 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
img2 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- args = (img1, img2, 5, 1.0, 1e-12, 'mean')
+ args = (img1, img2, 5, 1.0, 1e-12, "mean")
op = kornia.losses.ssim_loss
op_module = kornia.losses.SSIMLoss(*args[2:])
@@ -85,18 +85,18 @@ class TestMS_SSIMLoss:
with pytest.raises(TypeError) as errinfo:
criterion(1, 2)
- assert 'Input type is not a torch.Tensor. Got' in str(errinfo)
+ assert "Input type is not a torch.Tensor. Got" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
criterion(torch.rand(1), 2)
- assert 'Output type is not a torch.Tensor. Got' in str(errinfo)
+ assert "Output type is not a torch.Tensor. Got" in str(errinfo)
with pytest.raises(ValueError) as errinfo:
criterion(torch.rand(1), torch.rand(1, 2))
- assert 'Input shapes should be same. Got' in str(errinfo)
+ assert "Input shapes should be same. Got" in str(errinfo)
# TODO: implement for single channel image
- @pytest.mark.parametrize("reduction_type", ["mean", "sum", 'none'])
+ @pytest.mark.parametrize("reduction_type", ["mean", "sum", "none"])
@pytest.mark.parametrize("batch_shape", [(2, 1, 2, 3), (1, 3, 10, 16)])
def test_msssim(self, device, dtype, batch_shape, reduction_type):
img = torch.rand(batch_shape, device=device, dtype=dtype)
@@ -145,16 +145,16 @@ class TestSSIM3DLoss(BaseTester):
self.assert_close(ssim2, torch.zeros_like(img2))
@pytest.mark.parametrize("window_size", [5, 11])
- @pytest.mark.parametrize("reduction_type", ["mean", "sum", 'none'])
+ @pytest.mark.parametrize("reduction_type", ["mean", "sum", "none"])
@pytest.mark.parametrize("shape", [(1, 1, 2, 16, 16), (2, 4, 2, 15, 20)])
def test_ssim(self, device, dtype, shape, window_size, reduction_type):
- if device.type == 'xla':
+ if device.type == "xla":
pytest.skip("test highly unstable with tpu")
# Sanity test
img = torch.rand(shape, device=device, dtype=dtype)
actual = kornia.losses.ssim3d_loss(img, img, window_size, reduction=reduction_type)
- if reduction_type == 'none':
+ if reduction_type == "none":
expected = torch.zeros_like(img)
else:
expected = torch.tensor(0.0, device=device, dtype=dtype)
@@ -167,11 +167,11 @@ class TestSSIM3DLoss(BaseTester):
actual = kornia.losses.ssim3d_loss(img1, img2, window_size, reduction=reduction_type)
- if reduction_type == 'mean':
+ if reduction_type == "mean":
expected = torch.tensor(0.9999, device=device, dtype=dtype)
- elif reduction_type == 'sum':
+ elif reduction_type == "sum":
expected = (torch.ones_like(img1, device=device, dtype=dtype) * 0.9999).sum()
- elif reduction_type == 'none':
+ elif reduction_type == "none":
expected = torch.ones_like(img1, device=device, dtype=dtype) * 0.9999
self.assert_close(actual, expected)
@@ -180,7 +180,7 @@ class TestSSIM3DLoss(BaseTester):
img1 = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)
img2 = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)
- args = (img1, img2, 5, 1.0, 1e-12, 'mean')
+ args = (img1, img2, 5, 1.0, 1e-12, "mean")
op = kornia.losses.ssim3d_loss
op_module = kornia.losses.SSIM3DLoss(*args[2:])
@@ -203,12 +203,12 @@ class TestSSIM3DLoss(BaseTester):
def test_cardinality(self, shape, device, dtype):
img = torch.rand(shape, device=device, dtype=dtype)
- actual = kornia.losses.SSIM3DLoss(5, reduction='none')(img, img)
+ actual = kornia.losses.SSIM3DLoss(5, reduction="none")(img, img)
assert actual.shape == shape
actual = kornia.losses.SSIM3DLoss(5)(img, img)
assert actual.shape == ()
- @pytest.mark.skip('loss have no exception case')
+ @pytest.mark.skip("loss have no exception case")
def test_exception(self):
pass
diff --git a/test/morphology/test_dilation.py b/test/morphology/test_dilation.py
index 9744c1922..df99f007f 100644
--- a/test/morphology/test_dilation.py
+++ b/test/morphology/test_dilation.py
@@ -26,8 +26,8 @@ class TestDilate:
expected = torch.tensor([[1.0, 1.0, 1.0], [0.7, 1.0, 0.8], [0.9, 0.9, 0.9]], device=device, dtype=dtype)[
None, None, :, :
]
- assert_close(dilation(tensor, kernel, engine='unfold'), expected, atol=1e-4, rtol=1e-4)
- assert_close(dilation(tensor, kernel, engine='convolution'), expected, atol=1e-3, rtol=1e-3)
+ assert_close(dilation(tensor, kernel, engine="unfold"), expected, atol=1e-4, rtol=1e-4)
+ assert_close(dilation(tensor, kernel, engine="convolution"), expected, atol=1e-3, rtol=1e-3)
def test_structural_element(self, device, dtype):
tensor = torch.tensor([[0.5, 1.0, 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device, dtype=dtype)[
@@ -41,7 +41,7 @@ class TestDilate:
]
assert_close(
dilation(
- tensor, torch.ones_like(structural_element), structuring_element=structural_element, engine='unfold'
+ tensor, torch.ones_like(structural_element), structuring_element=structural_element, engine="unfold"
),
expected,
atol=1e-3,
@@ -52,7 +52,7 @@ class TestDilate:
tensor,
torch.ones_like(structural_element),
structuring_element=structural_element,
- engine='convolution',
+ engine="convolution",
),
expected,
atol=1e-3,
diff --git a/test/morphology/test_erosion.py b/test/morphology/test_erosion.py
index 9c6347054..97871a7c8 100644
--- a/test/morphology/test_erosion.py
+++ b/test/morphology/test_erosion.py
@@ -27,7 +27,7 @@ class TestErode:
None, None, :, :
]
assert_close(erosion(tensor, kernel), expected, atol=1e-4, rtol=1e-4)
- assert_close(erosion(tensor, kernel, engine='convolution'), expected, atol=1e-3, rtol=1e-3)
+ assert_close(erosion(tensor, kernel, engine="convolution"), expected, atol=1e-3, rtol=1e-3)
def test_structural_element(self, device, dtype):
tensor = torch.tensor([[0.5, 1.0, 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device, dtype=dtype)[
@@ -50,7 +50,7 @@ class TestErode:
tensor,
torch.ones_like(structural_element),
structuring_element=structural_element,
- engine='convolution',
+ engine="convolution",
),
expected,
atol=1e-3,
@@ -65,8 +65,8 @@ class TestErode:
expected = torch.tensor([[0.3, 0.3, 0.3], [0.3, 0.2, 0.2], [0.3, 0.2, 0.2]], device=device, dtype=dtype)[
None, None, :, :
]
- assert_close(erosion(tensor, kernel, engine='unfold'), expected, atol=1e-4, rtol=1e-4)
- assert_close(erosion(tensor, kernel, engine='convolution'), expected, atol=1e-3, rtol=1e-3)
+ assert_close(erosion(tensor, kernel, engine="unfold"), expected, atol=1e-4, rtol=1e-4)
+ assert_close(erosion(tensor, kernel, engine="convolution"), expected, atol=1e-3, rtol=1e-3)
def test_exception(self, device, dtype):
tensor = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)
diff --git a/test/nerf/test_camera_utils.py b/test/nerf/test_camera_utils.py
index dbb445e1d..78ab727ec 100755
--- a/test/nerf/test_camera_utils.py
+++ b/test/nerf/test_camera_utils.py
@@ -9,13 +9,13 @@ from kornia.nerf.camera_utils import create_spiral_path, parse_colmap_output
from kornia.testing import assert_close
_ref = {
- 'cameras': (
- 'https://raw.githubusercontent.com/kornia/data/main/nerf/cameras.txt',
- 'aee6dbd448be900a0d4de85d08914e47a84f025e16f8498cbf9f7bfc7eff09a6',
+ "cameras": (
+ "https://raw.githubusercontent.com/kornia/data/main/nerf/cameras.txt",
+ "aee6dbd448be900a0d4de85d08914e47a84f025e16f8498cbf9f7bfc7eff09a6",
),
- 'images': (
- 'https://raw.githubusercontent.com/kornia/data/main/nerf/images.txt',
- 'e6b66a9b76d92e498697edece33be76ae69aa28a960bc895a59495763de61286',
+ "images": (
+ "https://raw.githubusercontent.com/kornia/data/main/nerf/images.txt",
+ "e6b66a9b76d92e498697edece33be76ae69aa28a960bc895a59495763de61286",
),
}
@@ -30,12 +30,12 @@ def _get_data(url: str, sha256: str) -> str:
assert hashlib.sha256(data).hexdigest() == sha256
- return data.decode('utf-8')
+ return data.decode("utf-8")
@pytest.fixture()
def colmap_cameras_path(tmp_path):
- data = _get_data(*_ref['cameras'])
+ data = _get_data(*_ref["cameras"])
p = tmp_path / "camera.txt"
p.write_text(data)
@@ -45,7 +45,7 @@ def colmap_cameras_path(tmp_path):
@pytest.fixture()
def colmap_images_path(tmp_path):
- data = _get_data(*_ref['images'])
+ data = _get_data(*_ref["images"])
p = tmp_path / "images.txt"
p.write_text(data)
@@ -75,7 +75,7 @@ def test_parse_colmap_output(device, dtype, colmap_cameras_path, colmap_images_p
assert_close(R, cameras.rotation_matrix[2])
assert_close(cameras.translation_vector[2], t.unsqueeze(-1))
- assert img_names[2] == 'image002.png'
+ assert img_names[2] == "image002.png"
def test_create_spiral_path(device, dtype, colmap_cameras_path, colmap_images_path) -> None:
diff --git a/test/performance/test_imgwarp_speed.py b/test/performance/test_imgwarp_speed.py
index 67f9e0025..7fc58c939 100644
--- a/test/performance/test_imgwarp_speed.py
+++ b/test/performance/test_imgwarp_speed.py
@@ -9,9 +9,9 @@ shapes = [(512, 3, 256, 256), (256, 1, 64, 64)]
PSs = [224, 32]
[email protected](reason='May cause memory issues.')
[email protected](reason="May cause memory issues.")
def test_performance_speed(device, dtype):
- if device.type != 'cuda' or not torch.cuda.is_available():
+ if device.type != "cuda" or not torch.cuda.is_available():
pytest.skip("Cuda not available in system,")
print("Benchmarking warp_affine")
diff --git a/test/performance/test_project_points_speed.py b/test/performance/test_project_points_speed.py
index 95893ae9e..53cb0896e 100644
--- a/test/performance/test_project_points_speed.py
+++ b/test/performance/test_project_points_speed.py
@@ -1,26 +1,26 @@
-from time import time
-
-import pytest
-import torch
-
-import kornia
-
-points_shapes = [(64, 1024**2, 3), (8192, 8192, 3), (1024**2, 64, 3)]
-
-# TODO: remove xfail once we have enough gpu bandwidth in the CI
-
-
[email protected](reason='May cause memory issues.')
-def test_performance_speed(device, dtype):
- if device.type != 'cuda' or not torch.cuda.is_available():
- pytest.skip("Cuda not available in system,")
-
- print("Benchmarking project_points")
- for input_shape in points_shapes:
- inpt = torch.rand(input_shape).to(device)
- pose = torch.rand((1, 4, 4)).to(device)
- torch.cuda.synchronize(device)
- t = time()
- kornia.geometry.transform_points(pose, inpt)
- torch.cuda.synchronize(device)
- print(f"inp={input_shape}, dev={device}, {time() - t}, sec")
+from time import time
+
+import pytest
+import torch
+
+import kornia
+
+points_shapes = [(64, 1024**2, 3), (8192, 8192, 3), (1024**2, 64, 3)]
+
+# TODO: remove xfail once we have enough gpu bandwidth in the CI
+
+
[email protected](reason="May cause memory issues.")
+def test_performance_speed(device, dtype):
+ if device.type != "cuda" or not torch.cuda.is_available():
+ pytest.skip("Cuda not available in system,")
+
+ print("Benchmarking project_points")
+ for input_shape in points_shapes:
+ inpt = torch.rand(input_shape).to(device)
+ pose = torch.rand((1, 4, 4)).to(device)
+ torch.cuda.synchronize(device)
+ t = time()
+ kornia.geometry.transform_points(pose, inpt)
+ torch.cuda.synchronize(device)
+ print(f"inp={input_shape}, dev={device}, {time() - t}, sec")
diff --git a/test/sensors/camera/test_camera_model.py b/test/sensors/camera/test_camera_model.py
index ac05722fc..0b2400ac1 100644
--- a/test/sensors/camera/test_camera_model.py
+++ b/test/sensors/camera/test_camera_model.py
@@ -21,7 +21,7 @@ class TestPinholeCamera(BaseTester):
self.assert_close(image_size.height, cam.height)
self.assert_close(image_size.width, cam.width)
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_cardinality(self, device, dtype):
pass
@@ -38,15 +38,15 @@ class TestPinholeCamera(BaseTester):
with pytest.raises(ValueError):
CameraModel(image_size, CameraModelType.ORTHOGRAPHIC, params)
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_gradcheck(self, device):
pass
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_jit(self, device, dtype):
pass
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_module(self, device, dtype):
pass
diff --git a/test/sensors/camera/test_distortion_model.py b/test/sensors/camera/test_distortion_model.py
index b0ca44aac..8258481c2 100644
--- a/test/sensors/camera/test_distortion_model.py
+++ b/test/sensors/camera/test_distortion_model.py
@@ -7,27 +7,27 @@ from kornia.testing import BaseTester
class TestAffineTransform(BaseTester):
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_smoke(self, device, dtype):
pass
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_cardinality(self, device, dtype):
pass
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_exception(self, device, dtype):
pass
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_gradcheck(self, device):
pass
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_jit(self, device, dtype):
pass
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_module(self, device, dtype):
pass
diff --git a/test/sensors/camera/test_projection_model.py b/test/sensors/camera/test_projection_model.py
index f611df60c..80a904033 100644
--- a/test/sensors/camera/test_projection_model.py
+++ b/test/sensors/camera/test_projection_model.py
@@ -7,27 +7,27 @@ from kornia.testing import BaseTester
class TestZ1Projection(BaseTester):
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_smoke(self, device, dtype):
pass
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_cardinality(self, device, dtype):
pass
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_exception(self, device, dtype):
pass
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_gradcheck(self, device):
pass
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_jit(self, device, dtype):
pass
- @pytest.mark.skip(reason='Unnecessary test')
+ @pytest.mark.skip(reason="Unnecessary test")
def test_module(self, device, dtype):
pass
diff --git a/test/test_metrics.py b/test/test_metrics.py
index 83d7e2299..0bef2dbe6 100644
--- a/test/test_metrics.py
+++ b/test/test_metrics.py
@@ -284,11 +284,11 @@ class TestSSIM3d(BaseTester):
@pytest.mark.parametrize(
"shape,padding,window_size,max_value",
[
- ((1, 1, 3, 3, 3), 'same', 5, 1.0),
- ((1, 1, 3, 3, 3), 'same', 3, 2.0),
- ((1, 1, 3, 3, 3), 'same', 3, 0.5),
- ((1, 1, 3, 3, 3), 'valid', 3, 1.0),
- ((2, 4, 3, 3, 3), 'same', 3, 1.0),
+ ((1, 1, 3, 3, 3), "same", 5, 1.0),
+ ((1, 1, 3, 3, 3), "same", 3, 2.0),
+ ((1, 1, 3, 3, 3), "same", 3, 0.5),
+ ((1, 1, 3, 3, 3), "valid", 3, 1.0),
+ ((2, 4, 3, 3, 3), "same", 3, 1.0),
],
)
def test_smoke(self, shape, padding, window_size, max_value, device, dtype):
@@ -306,10 +306,10 @@ class TestSSIM3d(BaseTester):
@pytest.mark.parametrize(
"shape,padding,window_size,expected",
[
- ((1, 1, 2, 2, 3), 'same', 3, (1, 1, 2, 2, 3)),
- ((1, 1, 3, 3, 3), 'same', 5, (1, 1, 3, 3, 3)),
- ((1, 1, 3, 3, 3), 'valid', 3, (1, 1, 1, 1, 1)),
- ((2, 4, 3, 3, 3), 'same', 3, (2, 4, 3, 3, 3)),
+ ((1, 1, 2, 2, 3), "same", 3, (1, 1, 2, 2, 3)),
+ ((1, 1, 3, 3, 3), "same", 5, (1, 1, 3, 3, 3)),
+ ((1, 1, 3, 3, 3), "valid", 3, (1, 1, 1, 1, 1)),
+ ((2, 4, 3, 3, 3), "same", 3, (2, 4, 3, 3, 3)),
],
)
def test_cardinality(self, shape, padding, window_size, expected, device, dtype):
@@ -325,27 +325,27 @@ class TestSSIM3d(BaseTester):
# Check if both are tensors
with pytest.raises(TypeError) as errinfo:
kornia.metrics.ssim3d(1.0, img, 3)
- assert 'Not a Tensor type. Got:' in str(errinfo)
+ assert "Not a Tensor type. Got:" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
kornia.metrics.ssim3d(img, 1.0, 3)
- assert 'Not a Tensor type. Got:' in str(errinfo)
+ assert "Not a Tensor type. Got:" in str(errinfo)
# Check both shapes
img_wrong_shape = torch.rand(3, 3, device=device, dtype=dtype)
with pytest.raises(TypeError) as errinfo:
kornia.metrics.ssim3d(img, img_wrong_shape, 3)
- assert 'shape must be [' in str(errinfo)
+ assert "shape must be [" in str(errinfo)
with pytest.raises(TypeError) as errinfo:
kornia.metrics.ssim3d(img_wrong_shape, img, 3)
- assert 'shape must be [' in str(errinfo)
+ assert "shape must be [" in str(errinfo)
# Check if same shape
img_b = torch.rand(1, 1, 3, 3, 4, device=device, dtype=dtype)
with pytest.raises(Exception) as errinfo:
kornia.metrics.ssim3d(img, img_b, 3)
- assert 'img1 and img2 shapes must be the same. Got:' in str(errinfo)
+ assert "img1 and img2 shapes must be the same. Got:" in str(errinfo)
def test_unit(self, device, dtype):
img_a = torch.tensor(
@@ -364,7 +364,7 @@ class TestSSIM3d(BaseTester):
img_b = torch.ones(1, 1, 3, 3, 3, device=device, dtype=dtype) * 0.5
- actual = kornia.metrics.ssim3d(img_a, img_b, 3, padding='same')
+ actual = kornia.metrics.ssim3d(img_a, img_b, 3, padding="same")
expected = torch.tensor(
[
@@ -385,10 +385,10 @@ class TestSSIM3d(BaseTester):
@pytest.mark.parametrize(
"shape,padding,window_size,max_value",
[
- ((1, 1, 3, 3, 3), 'same', 5, 1.0),
- ((1, 1, 3, 3, 3), 'same', 3, 2.0),
- ((1, 1, 3, 3, 3), 'same', 3, 0.5),
- ((1, 1, 3, 3, 3), 'valid', 3, 1.0),
+ ((1, 1, 3, 3, 3), "same", 5, 1.0),
+ ((1, 1, 3, 3, 3), "same", 3, 2.0),
+ ((1, 1, 3, 3, 3), "same", 3, 0.5),
+ ((1, 1, 3, 3, 3), "valid", 3, 1.0),
],
)
def test_module(self, shape, padding, window_size, max_value, device, dtype):
diff --git a/test/tracking/test_planar_tracking.py b/test/tracking/test_planar_tracking.py
index e886b8fce..ef8ec533d 100644
--- a/test/tracking/test_planar_tracking.py
+++ b/test/tracking/test_planar_tracking.py
@@ -10,7 +10,7 @@ from kornia.utils._compat import torch_version_le
@pytest.fixture()
def data_url():
- url = 'https://github.com/kornia/data_test/blob/main/loftr_outdoor_and_homography_data.pt?raw=true'
+ url = "https://github.com/kornia/data_test/blob/main/loftr_outdoor_and_homography_data.pt?raw=true"
return url
@@ -25,7 +25,7 @@ class TestHomographyTracker:
data = torch.hub.load_state_dict_from_url(data_url)
# This is not unit test, but that is quite good integration test
- matcher = LocalFeatureMatcher(SIFTFeature(100), DescriptorMatcher('smnn', 0.95)).to(device, dtype)
+ matcher = LocalFeatureMatcher(SIFTFeature(100), DescriptorMatcher("smnn", 0.95)).to(device, dtype)
tracker = HomographyTracker(matcher, matcher, minimum_inliers_num=100)
for k in data.keys():
if isinstance(data[k], torch.Tensor):
@@ -44,10 +44,10 @@ class TestHomographyTracker:
if isinstance(data[k], torch.Tensor):
data[k] = data[k].to(device, dtype)
- data["image0"] = rescale(data["image0"], 0.5, interpolation='bilinear', align_corners=False)
- data["image1"] = rescale(data["image1"], 0.5, interpolation='bilinear', align_corners=False)
+ data["image0"] = rescale(data["image0"], 0.5, interpolation="bilinear", align_corners=False)
+ data["image1"] = rescale(data["image1"], 0.5, interpolation="bilinear", align_corners=False)
- matcher = LocalFeatureMatcher(GFTTAffNetHardNet(1000), DescriptorMatcher('snn', 0.8)).to(device, dtype)
+ matcher = LocalFeatureMatcher(GFTTAffNetHardNet(1000), DescriptorMatcher("snn", 0.8)).to(device, dtype)
torch.manual_seed(8) # issue kornia#2027
tracker = HomographyTracker(matcher, matcher).to(device, dtype)
@@ -56,8 +56,8 @@ class TestHomographyTracker:
torch.manual_seed(8) # issue kornia#2027
homography, success = tracker(data["image1"])
assert success
- pts_src = data['pts0'].to(device, dtype) / 2.0
- pts_dst = data['pts1'].to(device, dtype) / 2.0
+ pts_src = data["pts0"].to(device, dtype) / 2.0
+ pts_dst = data["pts1"].to(device, dtype) / 2.0
# Reprojection error of 5px is OK
assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
diff --git a/test/utils/test_draw.py b/test/utils/test_draw.py
index 8bfe3e336..6299d6229 100644
--- a/test/utils/test_draw.py
+++ b/test/utils/test_draw.py
@@ -237,7 +237,7 @@ class TestDrawLine:
assert_close(img, img_mask)
@pytest.mark.parametrize(
- 'p1', [torch.tensor([-1, 0]), torch.tensor([0, -1]), torch.tensor([8, 0]), torch.tensor([0, 8])]
+ "p1", [torch.tensor([-1, 0]), torch.tensor([0, -1]), torch.tensor([8, 0]), torch.tensor([0, 8])]
)
def test_p1_out_of_bounds(self, p1, dtype, device):
"""Tests that an exception is raised if p1 is out of bounds."""
@@ -245,10 +245,10 @@ class TestDrawLine:
with pytest.raises(ValueError) as excinfo:
draw_line(img, p1, torch.tensor([0, 0]), torch.tensor([255]))
- assert 'p1 is out of bounds.' == str(excinfo.value)
+ assert "p1 is out of bounds." == str(excinfo.value)
@pytest.mark.parametrize(
- 'p2', [torch.tensor([-1, 0]), torch.tensor([0, -1]), torch.tensor([8, 0]), torch.tensor([0, 8])]
+ "p2", [torch.tensor([-1, 0]), torch.tensor([0, -1]), torch.tensor([8, 0]), torch.tensor([0, 8])]
)
def test_p2_out_of_bounds(self, p2, dtype, device):
"""Tests that an exception is raised if p2 is out of bounds."""
@@ -256,38 +256,38 @@ class TestDrawLine:
with pytest.raises(ValueError) as excinfo:
draw_line(img, torch.tensor([0, 0]), p2, torch.tensor([255]))
- assert 'p2 is out of bounds.' == str(excinfo.value)
+ assert "p2 is out of bounds." == str(excinfo.value)
- @pytest.mark.parametrize('img_size', [(200, 100), (32, 3, 20, 20)])
+ @pytest.mark.parametrize("img_size", [(200, 100), (32, 3, 20, 20)])
def test_image_size(self, img_size, dtype, device):
img = torch.zeros(*img_size, dtype=dtype, device=device)
with pytest.raises(ValueError) as excinfo:
draw_line(img, torch.tensor([0, 0]), torch.tensor([1, 1]), torch.tensor([255]))
- assert 'image must have 3 dimensions (C,H,W).' == str(excinfo.value)
+ assert "image must have 3 dimensions (C,H,W)." == str(excinfo.value)
- @pytest.mark.parametrize('img_size,color', [((1, 8, 8), torch.tensor([23, 53])), ((3, 8, 8), torch.tensor([255]))])
+ @pytest.mark.parametrize("img_size,color", [((1, 8, 8), torch.tensor([23, 53])), ((3, 8, 8), torch.tensor([255]))])
def test_color_image_channel_size(self, img_size, color, dtype, device):
img = torch.zeros(*img_size, dtype=dtype, device=device)
with pytest.raises(ValueError) as excinfo:
draw_line(img, torch.tensor([0, 0]), torch.tensor([1, 1]), color)
- assert 'color must have the same number of channels as the image.' == str(excinfo.value)
+ assert "color must have the same number of channels as the image." == str(excinfo.value)
- @pytest.mark.parametrize('p1,p2', [(torch.rand([10, 2]), torch.rand([20, 2])), (torch.rand([2]), torch.rand([3]))])
+ @pytest.mark.parametrize("p1,p2", [(torch.rand([10, 2]), torch.rand([20, 2])), (torch.rand([2]), torch.rand([3]))])
def test_point_size(self, p1, p2, dtype, device):
img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
with pytest.raises(ValueError) as excinfo:
draw_line(img, p1, p2, torch.tensor([255]))
- assert 'Input points must be 2D points with shape (2, ) or (B, 2) and must have the same batch sizes.' == str(
+ assert "Input points must be 2D points with shape (2, ) or (B, 2) and must have the same batch sizes." == str(
excinfo.value
)
class TestDrawRectangle:
- @pytest.mark.parametrize('batch', (4, 17))
- @pytest.mark.parametrize('color', (torch.Tensor([1.0]), torch.Tensor([0.5])))
+ @pytest.mark.parametrize("batch", (4, 17))
+ @pytest.mark.parametrize("color", (torch.Tensor([1.0]), torch.Tensor([0.5])))
def test_smoke(self, device, batch, color):
black_image = torch.zeros(batch, 1, 3, 3, device=device) # 1 channel 3x3 black_image
points = torch.tensor([1.0, 1.0, 1.0, 1.0]).to(device).expand(batch, 1, 4) # single pixel rectangle
@@ -299,10 +299,10 @@ class TestDrawRectangle:
assert torch.all(black_image == target)
- @pytest.mark.parametrize('batch', (8, 11))
- @pytest.mark.parametrize('fill', (True, False))
- @pytest.mark.parametrize('height', (12, 106, 298))
- @pytest.mark.parametrize('width', (7, 123, 537))
+ @pytest.mark.parametrize("batch", (8, 11))
+ @pytest.mark.parametrize("fill", (True, False))
+ @pytest.mark.parametrize("height", (12, 106, 298))
+ @pytest.mark.parametrize("width", (7, 123, 537))
def test_fill_and_edges(self, device, batch, fill, height, width):
black_image = torch.zeros(batch, 3, height, width, device=device)
# we should pass height - 1 and width - 1 but rectangle should clip correctly
@@ -317,9 +317,9 @@ class TestDrawRectangle:
# corners are double counted
assert image_w_rectangle.sum() == batch * 3 * (2 * height + 2 * width - 4)
- @pytest.mark.parametrize('batch', (4, 6))
- @pytest.mark.parametrize('N', (5, 12))
- @pytest.mark.parametrize('fill', (True, False))
+ @pytest.mark.parametrize("batch", (4, 6))
+ @pytest.mark.parametrize("N", (5, 12))
+ @pytest.mark.parametrize("fill", (True, False))
def test_n_rectangles(self, device, batch, N, fill):
points_list = []
h, w = 20, 20
@@ -379,7 +379,7 @@ class TestDrawRectangle:
== (points_list[b][n][2] - points_list[b][n][0] + 1) * 3
)
- @pytest.mark.parametrize('color', (torch.tensor([0.5, 0.3, 0.15]), torch.tensor([0.23, 0.33, 0.8])))
+ @pytest.mark.parametrize("color", (torch.tensor([0.5, 0.3, 0.15]), torch.tensor([0.23, 0.33, 0.8])))
def test_color_background(self, device, color):
image = torch.zeros(1, 3, 40, 40, device=device)
image[:, 0, :, :] = color[0]
@@ -401,7 +401,7 @@ class TestDrawRectangle:
<= 0.0001
)
- @pytest.mark.parametrize('color', (torch.tensor([0.34, 0.63, 0.16]), torch.tensor([0.29, 0.13, 0.48])))
+ @pytest.mark.parametrize("color", (torch.tensor([0.34, 0.63, 0.16]), torch.tensor([0.29, 0.13, 0.48])))
def test_color_foreground(self, device, color):
image = torch.zeros(1, 3, 50, 40, device=device)
image_w_rectangle = image.clone()
diff --git a/test/utils/test_grid.py b/test/utils/test_grid.py
index efa7302fc..b83058756 100644
--- a/test/utils/test_grid.py
+++ b/test/utils/test_grid.py
@@ -22,7 +22,7 @@ def test_create_meshgrid(device, dtype):
def test_normalize_pixel_grid(device, dtype):
- if device.type == 'cuda' and dtype == torch.float16:
+ if device.type == "cuda" and dtype == torch.float16:
pytest.skip('"inverse_cuda" not implemented for "Half"')
# generate input data
diff --git a/test/utils/test_helpers.py b/test/utils/test_helpers.py
index d9b1b3b91..10e91c11d 100644
--- a/test/utils/test_helpers.py
+++ b/test/utils/test_helpers.py
@@ -16,28 +16,28 @@ from kornia.utils.helpers import (
@pytest.mark.parametrize(
"tensor_list,out_device,out_dtype,will_throw_error",
[
- ([], torch.device('cpu'), torch.get_default_dtype(), False),
- ([None, None], torch.device('cpu'), torch.get_default_dtype(), False),
- ([torch.tensor(0, device='cpu', dtype=torch.float16), None], torch.device('cpu'), torch.float16, False),
- ([torch.tensor(0, device='cpu', dtype=torch.float32), None], torch.device('cpu'), torch.float32, False),
- ([torch.tensor(0, device='cpu', dtype=torch.float64), None], torch.device('cpu'), torch.float64, False),
- ([torch.tensor(0, device='cpu', dtype=torch.float16)] * 2, torch.device('cpu'), torch.float16, False),
- ([torch.tensor(0, device='cpu', dtype=torch.float32)] * 2, torch.device('cpu'), torch.float32, False),
- ([torch.tensor(0, device='cpu', dtype=torch.float64)] * 2, torch.device('cpu'), torch.float64, False),
+ ([], torch.device("cpu"), torch.get_default_dtype(), False),
+ ([None, None], torch.device("cpu"), torch.get_default_dtype(), False),
+ ([torch.tensor(0, device="cpu", dtype=torch.float16), None], torch.device("cpu"), torch.float16, False),
+ ([torch.tensor(0, device="cpu", dtype=torch.float32), None], torch.device("cpu"), torch.float32, False),
+ ([torch.tensor(0, device="cpu", dtype=torch.float64), None], torch.device("cpu"), torch.float64, False),
+ ([torch.tensor(0, device="cpu", dtype=torch.float16)] * 2, torch.device("cpu"), torch.float16, False),
+ ([torch.tensor(0, device="cpu", dtype=torch.float32)] * 2, torch.device("cpu"), torch.float32, False),
+ ([torch.tensor(0, device="cpu", dtype=torch.float64)] * 2, torch.device("cpu"), torch.float64, False),
(
- [torch.tensor(0, device='cpu', dtype=torch.float16), torch.tensor(0, device='cpu', dtype=torch.float64)],
+ [torch.tensor(0, device="cpu", dtype=torch.float16), torch.tensor(0, device="cpu", dtype=torch.float64)],
None,
None,
True,
),
(
- [torch.tensor(0, device='cpu', dtype=torch.float32), torch.tensor(0, device='cpu', dtype=torch.float64)],
+ [torch.tensor(0, device="cpu", dtype=torch.float32), torch.tensor(0, device="cpu", dtype=torch.float64)],
None,
None,
True,
),
(
- [torch.tensor(0, device='cpu', dtype=torch.float16), torch.tensor(0, device='cpu', dtype=torch.float32)],
+ [torch.tensor(0, device="cpu", dtype=torch.float16), torch.tensor(0, device="cpu", dtype=torch.float32)],
None,
None,
True,
@@ -127,8 +127,8 @@ class TestSolveWithMask:
assert_close(X[mask], X2[mask], atol=tol_val, rtol=tol_val)
@pytest.mark.skipif(
- (int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 10),
- reason='<1.10.0 not supporting',
+ (int(torch.__version__.split(".")[0]) == 1) and (int(torch.__version__.split(".")[1]) < 10),
+ reason="<1.10.0 not supporting",
)
def test_all_bad(self, device, dtype):
A = torch.ones(10, 3, 3, device=device, dtype=dtype)
diff --git a/test/utils/test_pointcloud_io.py b/test/utils/test_pointcloud_io.py
index c41af96a9..59557e2aa 100644
--- a/test/utils/test_pointcloud_io.py
+++ b/test/utils/test_pointcloud_io.py
@@ -31,11 +31,11 @@ class TestSaveLoadPointCloud:
# add nans or infinite values
# point data (inf, inf, inf) skipped
- xyz_save[0, 0, :] = float('inf')
+ xyz_save[0, 0, :] = float("inf")
# point data (inf, number, number) counted
- xyz_save[0, 1, 0] = float('inf')
+ xyz_save[0, 1, 0] = float("inf")
# point data (inf, inf, number) counted
- xyz_save[1, 0, :-1] = float('inf')
+ xyz_save[1, 0, :-1] = float("inf")
# save to file
filename = "pointcloud.ply"
diff --git a/test/x/test_detection.py b/test/x/test_detection.py
index ad761ea06..9c6b44f11 100644
--- a/test/x/test_detection.py
+++ b/test/x/test_detection.py
@@ -62,7 +62,7 @@ def configuration():
class TestObjectDetectionTrainer:
@pytest.mark.slow
@pytest.mark.skipif(
- torch.__version__ == '1.12.1' and Accelerator is None, reason='accelerate lib problem with torch 1.12.1'
+ torch.__version__ == "1.12.1" and Accelerator is None, reason="accelerate lib problem with torch 1.12.1"
)
@pytest.mark.parametrize("loss_computed_by_model", [True, False])
def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration, loss_computed_by_model):
@@ -80,9 +80,9 @@ class TestObjectDetectionTrainer:
trainer.fit()
@pytest.mark.skipif(
- torch.__version__ == '1.12.1' and Accelerator is None, reason='accelerate lib problem with torch 1.12.1'
+ torch.__version__ == "1.12.1" and Accelerator is None, reason="accelerate lib problem with torch 1.12.1"
)
- @pytest.mark.xfail(sys.platform == 'darwin', reason='Sometimes CI can fail with MPS backend out of memory')
+ @pytest.mark.xfail(sys.platform == "darwin", reason="Sometimes CI can fail with MPS backend out of memory")
def test_exception(self, model, dataloader, criterion, optimizer, scheduler, configuration):
with pytest.raises(ValueError):
ObjectDetectionTrainer(
@@ -94,5 +94,5 @@ class TestObjectDetectionTrainer:
scheduler,
configuration,
num_classes=3,
- callbacks={'frodo': None},
+ callbacks={"frodo": None},
)
diff --git a/test/x/test_image_classification.py b/test/x/test_image_classification.py
index 66ec4633c..20483282a 100644
--- a/test/x/test_image_classification.py
+++ b/test/x/test_image_classification.py
@@ -54,18 +54,18 @@ def configuration():
class TestImageClassifierTrainer:
@pytest.mark.slow
@pytest.mark.skipif(
- torch.__version__ == '1.12.1' and Accelerator is None, reason='accelerate lib problem with torch 1.12.1'
+ torch.__version__ == "1.12.1" and Accelerator is None, reason="accelerate lib problem with torch 1.12.1"
)
def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration):
trainer = ImageClassifierTrainer(model, dataloader, dataloader, criterion, optimizer, scheduler, configuration)
trainer.fit()
@pytest.mark.skipif(
- torch.__version__ == '1.12.1' and Accelerator is None, reason='accelerate lib problem with torch 1.12.1'
+ torch.__version__ == "1.12.1" and Accelerator is None, reason="accelerate lib problem with torch 1.12.1"
)
- @pytest.mark.xfail(sys.platform == 'darwin', reason='Sometimes CI can fail with MPS backend out of memory')
+ @pytest.mark.xfail(sys.platform == "darwin", reason="Sometimes CI can fail with MPS backend out of memory")
def test_exception(self, model, dataloader, criterion, optimizer, scheduler, configuration):
with pytest.raises(ValueError):
ImageClassifierTrainer(
- model, dataloader, dataloader, criterion, optimizer, scheduler, configuration, callbacks={'frodo': None}
+ model, dataloader, dataloader, criterion, optimizer, scheduler, configuration, callbacks={"frodo": None}
)
diff --git a/test/x/test_segmentation.py b/test/x/test_segmentation.py
index 4b49bffca..6816ba7f9 100644
--- a/test/x/test_segmentation.py
+++ b/test/x/test_segmentation.py
@@ -53,7 +53,7 @@ def configuration():
class TestsemanticSegmentationTrainer:
@pytest.mark.slow
@pytest.mark.skipif(
- torch.__version__ == '1.12.1' and Accelerator is None, reason='accelerate lib problem with torch 1.12.1'
+ torch.__version__ == "1.12.1" and Accelerator is None, reason="accelerate lib problem with torch 1.12.1"
)
def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration):
trainer = SemanticSegmentationTrainer(
@@ -62,11 +62,11 @@ class TestsemanticSegmentationTrainer:
trainer.fit()
@pytest.mark.skipif(
- torch.__version__ == '1.12.1' and Accelerator is None, reason='accelerate lib problem with torch 1.12.1'
+ torch.__version__ == "1.12.1" and Accelerator is None, reason="accelerate lib problem with torch 1.12.1"
)
- @pytest.mark.xfail(sys.platform == 'darwin', reason='Sometimes CI can fail with MPS backend out of memory')
+ @pytest.mark.xfail(sys.platform == "darwin", reason="Sometimes CI can fail with MPS backend out of memory")
def test_exception(self, model, dataloader, criterion, optimizer, scheduler, configuration):
with pytest.raises(ValueError):
SemanticSegmentationTrainer(
- model, dataloader, dataloader, criterion, optimizer, scheduler, configuration, callbacks={'frodo': None}
+ model, dataloader, dataloader, criterion, optimizer, scheduler, configuration, callbacks={"frodo": None}
)
diff --git a/test/x/test_x.py b/test/x/test_x.py
index 301e2dc28..91a38ed3a 100644
--- a/test/x/test_x.py
+++ b/test/x/test_x.py
@@ -13,22 +13,22 @@ def model():
class TestModelCheckpoint:
def test_smoke(self, tmp_path, model):
- cb = ModelCheckpoint(tmp_path, 'test_monitor')
+ cb = ModelCheckpoint(tmp_path, "test_monitor")
assert cb is not None
- metric = {'test_monitor': AverageMeter()}
- metric['test_monitor']._avg = 1.0
+ metric = {"test_monitor": AverageMeter()}
+ metric["test_monitor"]._avg = 1.0
cb(model, epoch=0, valid_metric=metric)
assert cb.best_metric == 1.0
assert (tmp_path / "model_0.pt").is_file()
def test_custom_filename(self, tmp_path, model):
- cb = ModelCheckpoint(tmp_path, 'test_monitor', filename_fcn=lambda x: "model.pt")
+ cb = ModelCheckpoint(tmp_path, "test_monitor", filename_fcn=lambda x: "model.pt")
assert cb is not None
- metric = {'test_monitor': AverageMeter()}
- metric['test_monitor']._avg = 1.0
+ metric = {"test_monitor": AverageMeter()}
+ metric["test_monitor"]._avg = 1.0
cb(model, epoch=0, valid_metric=metric)
assert cb.best_metric == 1.0
@@ -36,31 +36,31 @@ class TestModelCheckpoint:
def test_callback_earlystopping(model):
- cb = EarlyStopping('test_monitor', patience=2)
+ cb = EarlyStopping("test_monitor", patience=2)
assert cb is not None
assert cb.counter == 0
- metric = {'test_monitor': AverageMeter()}
- metric['test_monitor']._avg = 1
+ metric = {"test_monitor": AverageMeter()}
+ metric["test_monitor"]._avg = 1
state = cb(model, epoch=0, valid_metric=metric)
assert state == TrainerState.TRAINING
assert cb.best_score == 1
assert cb.counter == 0
- metric['test_monitor']._avg = 2
+ metric["test_monitor"]._avg = 2
state = cb(model, epoch=0, valid_metric=metric)
assert state == TrainerState.TRAINING
assert cb.best_score == 2
assert cb.counter == 0
- metric['test_monitor']._avg = 1.9
+ metric["test_monitor"]._avg = 1.9
state = cb(model, epoch=0, valid_metric=metric)
assert state == TrainerState.TRAINING
assert cb.best_score == 2
assert cb.counter == 1
- metric['test_monitor']._avg = 1.9
+ metric["test_monitor"]._avg = 1.9
state = cb(model, epoch=0, valid_metric=metric)
assert state == TrainerState.TERMINATE
assert cb.best_score == 2