π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs: generate the example figures without opencv-python and kornia_moons (#4306)
Dmytro Mishkin3ea797d404e5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3feafb464..390daea9e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -310,6 +310,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* The generated example figures in the API reference are rendered from RGB input.+ `docs/generate_examples.py` decoded the sample images with `cv2.imdecode` and wrote them with+ `cv2.imwrite`, both BGR, so every tensor the examples fed to kornia held reversed channels. The two+ swaps cancel in the written file for channel-agnostic operations, but 35 colour-dependent figures+ change, and the ones that depend on which channel is which (`rgb_to_hsv`, `ColorJitter`,+ `apply_colormap`, the bbox and keypoint colours of `AugmentationSequential`, ...) showed a blue cast+ or swapped overlay colours. The generator now decodes and writes with PIL, draws the KeyNetAffNet+ LAF figure with kornia's own `get_laf_pts_to_draw`, and `opencv-python` and `kornia_moons` leave+ the `[docs]` extra. (#4306)* `kornia.io.get_sample_images` and `kornia.onnx.ONNXLoader.list_operators` / `list_models` no longer need`requests`, which `pip install kornia` never installed; they fetch with the standard library `urllib` instead.The failure exceptions change with it, all still `OSError` subclasses: a sample-image URL that returns 404 nowdiff --git a/docs/generate_examples.py b/docs/generate_examples.pyindex c39ca38e3..aa9c0cc71 100644--- a/docs/generate_examples.py+++ b/docs/generate_examples.py@@ -18,19 +18,20 @@from __future__ import annotationsimport importlib+import ioimport mathimport osfrom pathlib import Pathfrom typing import Optional+from urllib.request import urlopen-import cv2import matplotlib as mplimport matplotlib.pyplot as pltimport numpy as np-import requestsimport torchimport torch.nn.functional as F-from kornia_moons.feature import visualize_LAF+from matplotlib.axes import Axes+from PIL import Imageimport kornia as K@@ -41,8 +42,9 @@ def download_tutorials_examples(download_infos: dict[str, str], directory: Path)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+ # perform request; S310 is safe here because the URL is the fixed https:// base above+ with urlopen(url, timeout=60) as resp: # noqa: S310+ response = resp.read()path = directory / filenamewith open(path, "wb") as fp:@@ -50,12 +52,12 @@ def download_tutorials_examples(download_infos: dict[str, str], directory: Path)def read_img_from_url(url: str, resize_to: Optional[tuple[int, int]] = None, **resize_kwargs) -> torch.Tensor:- # perform request- response = requests.get(url, timeout=60).content- # convert to array of ints- nparr = np.frombuffer(response, np.uint8)- # convert to image array and resize- img: np.ndarray = cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED)[..., :3]+ # perform request; S310 is safe here because every caller passes a fixed https:// constant+ with urlopen(url, timeout=60) as resp: # noqa: S310+ response = resp.read()+ # decode to an HxWx3 RGB array; ``convert`` also drops the alpha of the RGBA sources.+ # ``np.array`` rather than ``asarray``: the tensor must not alias PIL's read-only buffer.+ img: np.ndarray = np.array(Image.open(io.BytesIO(response)).convert("RGB"))# convert the image to a tensorimg_t: torch.Tensor = K.image.image_to_tensor(img, keepdim=False) # 1xCxHXWimg_t = img_t.float() / 255.0@@ -66,6 +68,22 @@ def read_img_from_url(url: str, resize_to: Optional[tuple[int, int]] = None, **rreturn img_t+def write_png(path: Path, img: np.ndarray) -> None:+ """Save an ``HxW`` grayscale, ``HxWx3`` RGB or ``HxWx4`` RGBA ``uint8`` array as a PNG."""+ Image.fromarray(np.ascontiguousarray(img)).save(path)+++def draw_lafs(ax: Axes, lafs: torch.Tensor, color: str) -> None:+ """Outline the local affine frames of the first image of ``lafs`` on an existing axes.++ Reproduces ``kornia_moons.viz.visualize_LAF(..., draw_ori=False)``: the regions are drawn at+ half the LAF scale, and the leading boundary point -- the LAF centre, which ``draw_ori`` would+ join to the outline -- is dropped.+ """+ xs, ys = K.feature.laf.get_laf_pts_to_draw(K.feature.scale_laf(lafs, 0.5), 0)+ ax.plot(xs[1:], ys[1:], color, linewidth=1)++def transparent_pad(src: torch.Tensor, shape: tuple[int, int]) -> torch.Tensor:"""Apply a transparent pad to src (centerized) to match with shape (h, w)"""w_pad = abs(int(src.shape[-1] - shape[-1]) // 2)@@ -221,7 +239,7 @@ def main():out = torch.cat([ori, *(out[i] for i in range(out.size(0)))], dim=-1)# save the output imageout_np = K.image.tensor_to_image((out * 255.0).byte())- cv2.imwrite(str(OUTPUT_PATH / f"{aug_name}.png"), out_np)+ write_png(OUTPUT_PATH / f"{aug_name}.png", out_np)sig = f"{aug_name}({', '.join([str(a) for a in args])}, p=1.0)"print(f"Generated image example for {aug_name}. {sig}")@@ -244,7 +262,7 @@ def main():output = torch.cat([img_in[0], img_in[1], img_aug], dim=-1)# save the output imageout_np = K.image.tensor_to_image((output * 255.0).byte())- cv2.imwrite(str(OUTPUT_PATH / f"{aug_name}.png"), out_np)+ write_png(OUTPUT_PATH / f"{aug_name}.png", out_np)sig = f"{aug_name}({', '.join([str(a) for a in args])}, p=1.0)"print(f"Generated image example for {aug_name}. {sig}")@@ -265,7 +283,7 @@ def main():output = torch.cat([img_in[0], img_in[1], img_aug[0]], dim=-1)# save the output imageout_np = K.image.tensor_to_image((output * 255.0).byte())- cv2.imwrite(str(OUTPUT_PATH / f"{aug_name}.png"), out_np)+ write_png(OUTPUT_PATH / f"{aug_name}.png", out_np)sig = f"{aug_name}({', '.join([str(a) for a in args])}, p=1.0)"print(f"Generated image example for {aug_name}. {sig}")@@ -325,7 +343,7 @@ def main():# save the output imageout_np = K.image.tensor_to_image((output * 255.0).byte())- cv2.imwrite(str(OUTPUT_PATH / f"{aug_name}.png"), out_np)+ write_png(OUTPUT_PATH / f"{aug_name}.png", out_np)sig = f"{aug_name}({', '.join([str(a) for a in args])}, p=1.0)"print(f"Generated image example for {aug_name}. {sig}")@@ -355,10 +373,10 @@ def main():out = fn(K.color.rgb_to_grayscale(img2), *args)elif fn_name == "apply_colormap":gray_image = (K.color.rgb_to_grayscale(img2) * 255.0).round()- out = K.color.rgb_to_bgr(fn(gray_image, *args))+ out = fn(gray_image, *args)elif fn_name == "ApplyColorMap":gray_image = (K.color.rgb_to_grayscale(img2) * 255.0).round()- out = K.color.rgb_to_bgr(fn(*args)(gray_image))+ out = fn(*args)(gray_image)else:out = fn(img2, *args)# perform normalization to visualize@@ -379,7 +397,7 @@ def main():else:out = torch.cat([img2[0], *(out[i] for i in range(out.size(0)))], dim=-1)out_np = K.image.tensor_to_image((out * 255.0).byte())- cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)+ write_png(OUTPUT_PATH / f"{fn_name}.png", out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")@@ -390,12 +408,12 @@ def main():# ITERATE OVER THE COLORMAPSfor colormap_name, args in colormaps_list.items():cm = K.color.ColorMap(base=colormap_name, num_colors=args[0])- out = K.color.rgb_to_bgr(K.color.apply_colormap(bar_img_gray, cm))[0]+ out = K.color.apply_colormap(bar_img_gray, cm)[0]out = torch.cat([bar_img, out], dim=-1)out_np = K.image.tensor_to_image((out * 255.0).byte())- cv2.imwrite(str(OUTPUT_PATH / f"{colormap_name}.png"), out_np)+ write_png(OUTPUT_PATH / f"{colormap_name}.png", out_np)sig = f"{colormap_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {colormap_name}. {sig}")@@ -460,7 +478,7 @@ def main():# save the output imageout = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)out_np = K.image.tensor_to_image((out * 255.0).byte())- cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)+ write_png(OUTPUT_PATH / f"{fn_name}.png", out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")@@ -487,7 +505,7 @@ def main():# save the output imageout = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)out_np = K.image.tensor_to_image((out * 255.0).byte())- cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)+ write_png(OUTPUT_PATH / f"{fn_name}.png", out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")@@ -538,7 +556,7 @@ def main():# save the output imageout = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)out_np = K.image.tensor_to_image((out * 255.0).byte())- cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)+ write_png(OUTPUT_PATH / f"{fn_name}.png", out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")@@ -561,7 +579,7 @@ def main():# save the output imageout = torch.cat([img1[0], mask[0], filtered[0]], dim=-1)out_np = K.image.tensor_to_image((out * 255.0).byte())- cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)+ write_png(OUTPUT_PATH / f"{fn_name}.png", out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")@@ -648,7 +666,7 @@ def main():else:out = torch.cat([*(out[i] for i in range(out.size(0)))], dim=-1)out_np = K.image.tensor_to_image((out * 255.0).byte())- cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)+ write_png(OUTPUT_PATH / f"{fn_name}.png", out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")@@ -671,7 +689,9 @@ 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)+ fig1, ax = plt.subplots(1, 1)+ ax.imshow(K.image.tensor_to_image(img_outdoor[0]))+ draw_lafs(ax, lafs, color="lime")ax.set_title("KeyNetAffNet 512 LAFs")cur_fname = str(OUTPUT_PATH / "keynet_affnet.jpg")fig1.savefig(cur_fname)@@ -716,13 +736,12 @@ def main():img_in = torch.nn.functional.pad(img_outdoor, (0, pd_w, 0, pd_h), value=0.0)out, _ = fn.heatmap_and_dense_descriptors(img_in)out = K.color.grayscale_to_rgb(out)- img_in = K.color.rgb_to_bgr(img_in)elif fn_name == "ALIKED":fn = K.feature.ALIKED.from_pretrained()with torch.no_grad():_, out = fn.extract_dense_map(img_outdoor)out = K.color.grayscale_to_rgb(out)- img_in = K.color.rgb_to_bgr(img_outdoor)+ img_in = img_outdoorelif fn_name == "XFeat":fn = K.feature.XFeat.from_pretrained()with torch.no_grad():@@ -732,7 +751,7 @@ def main():# upsample heatmap from preprocessed size back to original image sizeout = torch.nn.functional.interpolate(out, img_outdoor.shape[-2:], mode="bilinear", align_corners=False)out = K.color.grayscale_to_rgb(out)- img_in = K.color.rgb_to_bgr(img_outdoor)+ img_in = img_outdoorelse:fn = getattr(mod, fn_name)out = fn(img_in)@@ -743,17 +762,17 @@ def main():# save the output imageout = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)out_np = K.image.tensor_to_image((out * 255.0).byte())- cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)+ write_png(OUTPUT_PATH / f"{fn_name}.png", out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for response function {fn_name}")# Face detection with the pretrained YuNet model, for the landing-page "models" card. The- # checkpoint is ~400 KB, so this stays cheap in the docs build. ``img_crowd`` is BGR like the- # other tensors here; the detector gets RGB and the boxes are drawn onto the BGR copy for cv2.+ # checkpoint is ~400 KB, so this stays cheap in the docs build. ``img_crowd`` is RGB like the+ # other tensors here, so the detector and the drawn boxes share the same tensor.img_crowd = read_img_from_url(BASE_IMAGE_URL_CROWD, (480, 736))face_detector = K.contrib.FaceDetector().eval()with torch.no_grad():- detections = face_detector(K.color.bgr_to_rgb(img_crowd) * 255.0)[0]+ detections = face_detector(img_crowd * 255.0)[0]faces = [K.contrib.FaceDetectorResult(d) for d in detections]confident = [torch.cat([f.top_left, f.bottom_right]) for f in faces if f.score > 0.7]out = img_crowd.clone()@@ -763,7 +782,7 @@ def main():out = K.image.draw_rectangle(out, boxes + torch.tensor([-pad, -pad, pad, pad]), color=torch.tensor([0.4, 1.0, 0.2]))- cv2.imwrite(str(OUTPUT_PATH / "face_detection.png"), K.image.tensor_to_image((out[0] * 255.0).byte()))+ write_png(OUTPUT_PATH / "face_detection.png", K.image.tensor_to_image((out[0] * 255.0).byte()))print(f"Generated image example for FaceDetector. {len(confident)} faces")diff --git a/docs/generate_model_examples.py b/docs/generate_model_examples.pyindex d690b02b2..df8c72752 100644--- a/docs/generate_model_examples.py+++ b/docs/generate_model_examples.py@@ -34,13 +34,13 @@ from __future__ import annotationsimport sysfrom pathlib import Path+from urllib.request import urlopenimport matplotlib as mplmpl.use("Agg") # select the headless backend before pyplot is importedimport matplotlib.pyplot as plt-import requestsimport torchimport kornia as K@@ -74,9 +74,8 @@ def knchurch() -> tuple[torch.Tensor, torch.Tensor]:def imagenet_classes() -> list[str]:- response = requests.get(IMAGENET_CLASSES, timeout=60)- response.raise_for_status()- return response.text.strip().splitlines()+ with urlopen(IMAGENET_CLASSES, timeout=60) as resp:+ return resp.read().decode().strip().splitlines()def show(ax, img: torch.Tensor, title: str = "") -> None:diff --git a/pyproject.toml b/pyproject.tomlindex 7d35a8027..393c2c10b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -52,13 +52,12 @@ dev = []docs = ["pydata-sphinx-theme>=0.21,<0.22", # _static/css/pydata.css and js/custom.js target theme internals- "kornia_moons","matplotlib",# kornia.core.mixin.onnx annotates public members with ``onnx.ModelProto``; without onnx the# lazy loader prompts on stdin while autodoc resolves them and the build dies. onnxruntime is# not needed: no documented member resolves an ``onnxruntime`` annotation."onnx",- "opencv-python",+ "pillow", # docs/generate_examples.py decodes and writes the generated figures with PIL"sphinx","sphinx-autodoc-defaultargs","sphinx-autodoc-typehints",diff --git a/uv.lock b/uv.lockindex 857fb59b6..4fabd2e6c 100644--- a/uv.lock+++ b/uv.lock@@ -827,10 +827,9 @@ dev = [{ name = "transformers" },]docs = [- { name = "kornia-moons" },{ name = "matplotlib" },{ name = "onnx" },- { name = "opencv-python" },+ { name = "pillow" },{ name = "pydata-sphinx-theme" },{ name = "sphinx" },{ name = "sphinx-autodoc-defaultargs" },@@ -847,7 +846,6 @@ docs = [requires-dist = [{ name = "coverage", marker = "extra == 'dev'" },{ name = "diffusers", marker = "extra == 'dev'" },- { name = "kornia-moons", marker = "extra == 'docs'" },{ name = "kornia-rs", specifier = ">=0.1.9" },{ name = "matplotlib", marker = "extra == 'docs'" },{ name = "numpy", specifier = ">=1.21" },@@ -855,8 +853,8 @@ requires-dist = [{ name = "onnx", marker = "extra == 'docs'" },{ name = "onnxruntime", marker = "extra == 'dev'" },{ name = "onnxscript", marker = "extra == 'dev'" },- { name = "opencv-python", marker = "extra == 'docs'" },{ name = "pillow", marker = "extra == 'dev'" },+ { name = "pillow", marker = "extra == 'docs'" },{ name = "pre-commit", marker = "extra == 'dev'" },{ name = "pydata-sphinx-theme", marker = "extra == 'docs'", specifier = ">=0.21,<0.22" },{ name = "pytest", marker = "extra == 'dev'" },@@ -876,21 +874,6 @@ requires-dist = []provides-extras = ["dev", "docs"]-[[package]]-name = "kornia-moons"-version = "0.2.9"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "kornia" },- { name = "matplotlib" },- { name = "opencv-python" },- { name = "torch" },-]-sdist = { url = "https://files.pythonhosted.org/packages/37/4b/10defe8ac68c3ab2b42c58ed302d36e3ba69a33f092f5798a8248e0e0f68/kornia_moons-0.2.9.tar.gz", hash = "sha256:e6e6b3523296a38f099712a322d708730720cfb97de437aa90fa586a86556455", size = 16816, upload-time = "2023-09-26T12:05:10.931Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/dd/61/2d7b4383eab721c785c318d06e412f49a4e04568b46291d30aa3d2e7dba5/kornia_moons-0.2.9-py3-none-any.whl", hash = "sha256:d35e799b29031365c7b57fee3d84b4be547c0513f7c013e8234e05d33d2b1061", size = 15628, upload-time = "2023-09-26T12:05:08.97Z" },-]-[[package]]name = "kornia-rs"version = "0.1.10"@@ -1498,23 +1481,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/dd/bd/a0c8e737b6afda10e42a597787d53d5b66e00268df6f59184701eeae37d9/onnxscript-0.7.1-py3-none-any.whl", hash = "sha256:544763b7fdef49940cdd9412ff5135cbae96d59ac6bc1921457f21280f40f4b7", size = 721970, upload-time = "2026-06-29T23:33:23.298Z" },]-[[package]]-name = "opencv-python"-version = "4.11.0.86"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "numpy" },-]-sdist = { url = "https://files.pythonhosted.org/packages/17/06/68c27a523103dad5837dc5b87e71285280c4f098c60e4fe8a8db6486ab09/opencv-python-4.11.0.86.tar.gz", hash = "sha256:03d60ccae62304860d232272e4a4fda93c39d595780cb40b161b310244b736a4", size = 95171956, upload-time = "2025-01-16T13:52:24.737Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/05/4d/53b30a2a3ac1f75f65a59eb29cf2ee7207ce64867db47036ad61743d5a23/opencv_python-4.11.0.86-cp37-abi3-macosx_13_0_arm64.whl", hash = "sha256:432f67c223f1dc2824f5e73cdfcd9db0efc8710647d4e813012195dc9122a52a", size = 37326322, upload-time = "2025-01-16T13:52:25.887Z" },- { url = "https://files.pythonhosted.org/packages/3b/84/0a67490741867eacdfa37bc18df96e08a9d579583b419010d7f3da8ff503/opencv_python-4.11.0.86-cp37-abi3-macosx_13_0_x86_64.whl", hash = "sha256:9d05ef13d23fe97f575153558653e2d6e87103995d54e6a35db3f282fe1f9c66", size = 56723197, upload-time = "2025-01-16T13:55:21.222Z" },- { url = "https://files.pythonhosted.org/packages/f3/bd/29c126788da65c1fb2b5fb621b7fed0ed5f9122aa22a0868c5e2c15c6d23/opencv_python-4.11.0.86-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1b92ae2c8852208817e6776ba1ea0d6b1e0a1b5431e971a2a0ddd2a8cc398202", size = 42230439, upload-time = "2025-01-16T13:51:35.822Z" },- { url = "https://files.pythonhosted.org/packages/2c/8b/90eb44a40476fa0e71e05a0283947cfd74a5d36121a11d926ad6f3193cc4/opencv_python-4.11.0.86-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6b02611523803495003bd87362db3e1d2a0454a6a63025dc6658a9830570aa0d", size = 62986597, upload-time = "2025-01-16T13:52:08.836Z" },- { url = "https://files.pythonhosted.org/packages/fb/d7/1d5941a9dde095468b288d989ff6539dd69cd429dbf1b9e839013d21b6f0/opencv_python-4.11.0.86-cp37-abi3-win32.whl", hash = "sha256:810549cb2a4aedaa84ad9a1c92fbfdfc14090e2749cedf2c1589ad8359aa169b", size = 29384337, upload-time = "2025-01-16T13:52:13.549Z" },- { url = "https://files.pythonhosted.org/packages/a4/7d/f1c30a92854540bf789e9cd5dde7ef49bbe63f855b85a2e6b3db8135c591/opencv_python-4.11.0.86-cp37-abi3-win_amd64.whl", hash = "sha256:085ad9b77c18853ea66283e98affefe2de8cc4c1f43eda4c100cf9b2721142ec", size = 39488044, upload-time = "2025-01-16T13:52:21.928Z" },-]-[[package]]name = "packaging"version = "25.0"