From d6affbf0d6e9ead13fd1dfb629e7052c03505391 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Mon, 23 Nov 2026 14:19:06 +1000 Subject: [PATCH] chore: format with ruff at line length 88 Set line-length to 88 as in RTB, bdsim and sphinx-pyrunblock, add [tool.ruff.format], ignore E501 (the formatter does not wrap strings or comments), and run ruff format over src and tests (46 files). Moved three type: ignore comments onto the lines mypy reports. AGENTS.md says to use ruff. Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 6 +++ pyproject.toml | 10 ++++- src/machinevisiontoolbox/BagOfWords.py | 2 +- src/machinevisiontoolbox/BundleAdjust.py | 4 -- src/machinevisiontoolbox/Camera.py | 16 ++++--- src/machinevisiontoolbox/ImageCore.py | 10 ++++- src/machinevisiontoolbox/ImageIO.py | 4 +- .../ImagePointFeatures.py | 2 +- src/machinevisiontoolbox/ImageProcessing.py | 11 +++-- .../ImageRegionFeatures.py | 8 +--- src/machinevisiontoolbox/ImageSpatial.py | 6 +-- .../ImageWholeFeatures.py | 22 +++++++-- src/machinevisiontoolbox/Kernel.py | 4 +- src/machinevisiontoolbox/PointCloud.py | 1 - src/machinevisiontoolbox/Sources.py | 9 ++-- src/machinevisiontoolbox/VisualServo.py | 4 +- src/machinevisiontoolbox/base/graphics.py | 13 +++++- src/machinevisiontoolbox/bin/imtool.py | 4 +- src/machinevisiontoolbox/bin/mvtbtool.py | 20 ++++++--- src/machinevisiontoolbox/blocks/camera.py | 1 - tests/base/test_base_color.py | 42 ++++++++--------- tests/base/test_idisp_display_readback.py | 8 +++- tests/base/test_io.py | 8 +++- tests/create_ros_fixture.py | 11 +++-- tests/test_bag_of_words.py | 1 - tests/test_bin.py | 8 ++-- tests/test_camera.py | 2 - tests/test_examples_run.py | 20 +++++++-- tests/test_examples_smoke.py | 1 - tests/test_image_blobs.py | 2 - tests/test_image_color.py | 3 -- tests/test_image_constants.py | 9 ++-- tests/test_image_fiducials.py | 8 +--- tests/test_image_morph.py | 2 - tests/test_image_point_features.py | 15 ++++--- tests/test_image_processing.py | 4 -- tests/test_image_processing_kernel.py | 45 +++++++++++-------- tests/test_image_region_features.py | 1 - tests/test_image_sources.py | 10 ++--- tests/test_image_spatial_extra.py | 1 - tests/test_image_tensor.py | 1 - tests/test_image_whole_features.py | 39 +++++++++++----- tests/test_pointcloud.py | 1 + tests/test_ros.py | 6 --- tests/test_ros_depth_units.py | 8 +++- tests/test_ros_realsense.py | 17 +++++-- tests/test_star_import.py | 1 - tests/test_visual_servo.py | 3 -- 48 files changed, 254 insertions(+), 180 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1752b4c3..9cf77334 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,12 @@ description and ask first. ignores as `# type: ignore[code]` with the specific error code; unused ignores are reported. Import from the defining submodule (for example `machinevisiontoolbox.base.graphics`), not through the package's star imports, which mypy cannot follow. +- Formatting and linting: `ruff`, configured in `pyproject.toml` (line length 88, as in RTB, + bdsim and sphinx-pyrunblock). Format with `ruff format src tests` and lint with + `ruff check src tests`; do not use `black`. Format only the files you change, so that a + feature PR carries no unrelated reformatting. CI does not run ruff yet, but the tree is + formatted, so `ruff format --check src tests` passes. `E501` is ignored: the formatter + does not wrap long strings or comments. - New and changed code uses modern annotation syntax: `X | Y`, `X | None`, `list[X]`, `dict[K, V]`, not `Union`, `Optional`, `List` or `Dict`. For array arguments use `ArrayLike` (or `ArrayLike2` for a 2-element value) from `machinevisiontoolbox.mvtb_types`, and put the diff --git a/pyproject.toml b/pyproject.toml index 7a7253eb..fb808790 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -119,12 +119,20 @@ testpaths = ["tests"] addopts = "--tb=short" [tool.ruff] -line-length = 120 +# 88 matches RTB, bdsim and sphinx-pyrunblock +line-length = 88 # the notebooks that reproduce the book code have a bare except in their setup cell extend-exclude = ["tests/RVC"] [tool.ruff.lint] select = ["E", "F", "I", "BLE", "S110"] +# the formatter wraps code but not long strings or comments, so E501 would only +# report what `ruff format` cannot fix +ignore = ["E501"] + +[tool.ruff.format] +quote-style = "double" +indent-style = "space" [tool.ruff.lint.per-file-ignores] # these files re-export their submodules with star imports on purpose, so that diff --git a/src/machinevisiontoolbox/BagOfWords.py b/src/machinevisiontoolbox/BagOfWords.py index 67ec5b54..c1e9a95e 100644 --- a/src/machinevisiontoolbox/BagOfWords.py +++ b/src/machinevisiontoolbox/BagOfWords.py @@ -359,7 +359,7 @@ def _remove_stopwords(self, verbose: bool = True) -> None: stopfeatures = freq[stopwords].sum() print( - f"Removing {stopfeatures} features ({stopfeatures/len(self.words) * 100:.1f}%) associated with {self.nstopwords} most frequent words" + f"Removing {stopfeatures} features ({stopfeatures / len(self.words) * 100:.1f}%) associated with {self.nstopwords} most frequent words" ) k = np.full(index.shape, False, dtype=bool) diff --git a/src/machinevisiontoolbox/BundleAdjust.py b/src/machinevisiontoolbox/BundleAdjust.py index 665af2c9..f2cddba1 100644 --- a/src/machinevisiontoolbox/BundleAdjust.py +++ b/src/machinevisiontoolbox/BundleAdjust.py @@ -722,14 +722,12 @@ def build_linear_system(self, x: np.ndarray) -> tuple[Any, Any, Any]: # loop over views for view in self.views: - # get camera pose k = view.index X = x[k : k + 6] # loop over all points viewed from this camera for landmark, edge in view.incidences(): - k = landmark.index P = x[k : k + 3] # get landmark position @@ -942,14 +940,12 @@ def getresidual(self, x: np.ndarray | None = None) -> np.ndarray: residual = np.zeros((self.nviews, self.nlandmarks)) # loop over views for view in self.views: - # get view pose k = view.index X = x[k : k + 6] # loop over all points viewed from this camera for landmark, edge in view.incidences(): - k = landmark.index P = x[k : k + 3] # get landmark position diff --git a/src/machinevisiontoolbox/Camera.py b/src/machinevisiontoolbox/Camera.py index 569ef6a9..f58f5960 100644 --- a/src/machinevisiontoolbox/Camera.py +++ b/src/machinevisiontoolbox/Camera.py @@ -120,9 +120,9 @@ def __init__( self.pp = pp if sensorsize is not None: - assert ( - self._imagesize is not None - ), "imagesize must be set when sensorsize is given" + assert self._imagesize is not None, ( + "imagesize must be set when sensorsize is given" + ) self._rhou = sensorsize[0] / self._imagesize[0] self._rhov = sensorsize[1] / self._imagesize[1] else: @@ -1253,7 +1253,9 @@ def _add_collection3d_compat(collection, *args, **kwargs): CameraBase._plot_frustum(ax, pose, scale, alpha) elif shape == "camera": - CameraBase._plot_camera_icon(ax, pose, scale, solid, color, alpha, label) + CameraBase._plot_camera_icon( + ax, pose, scale, solid, color, alpha, label + ) if frame is True: pose.plot( @@ -2982,7 +2984,11 @@ def points2E( method_int = None E, mask = cv2.findEssentialMat( - points1=p1.T, points2=p2.T, cameraMatrix=K, method=method_int, **kwargs # type: ignore[arg-type] + points1=p1.T, + points2=p2.T, + cameraMatrix=K, + method=method_int, # type: ignore[arg-type] + **kwargs, ) if mask is not None: mask = mask.flatten().astype(bool) diff --git a/src/machinevisiontoolbox/ImageCore.py b/src/machinevisiontoolbox/ImageCore.py index a6e46414..ccaa8dc8 100644 --- a/src/machinevisiontoolbox/ImageCore.py +++ b/src/machinevisiontoolbox/ImageCore.py @@ -344,7 +344,11 @@ def __init__( image = image[:, :, 0] # squeeze out singleton plane if kwargs: - image = convert(image, dtype=dtype if defer_dtype_to_convert else None, **kwargs) # type: ignore[arg-type] + image = convert( + image, + dtype=dtype if defer_dtype_to_convert else None, # type: ignore[arg-type] + **kwargs, + ) # assign the image to the object, copying if requested if copy: @@ -497,7 +501,9 @@ def __iter__(self) -> Iterator["Image"]: """Iterate over image planes.""" return self.planes() - def __array__(self, dtype: Dtype | None = None, copy: bool | None = None) -> np.ndarray: + def __array__( + self, dtype: Dtype | None = None, copy: bool | None = None + ) -> np.ndarray: """ Convert to a plain NumPy array diff --git a/src/machinevisiontoolbox/ImageIO.py b/src/machinevisiontoolbox/ImageIO.py index 60249314..92d5c69e 100644 --- a/src/machinevisiontoolbox/ImageIO.py +++ b/src/machinevisiontoolbox/ImageIO.py @@ -774,7 +774,9 @@ def on_click(self, event: Any) -> None: if title is None: if self.name is not None and right.name is not None: - title = f"{os.path.basename(self.name)} / {os.path.basename(right.name)}" + title = ( + f"{os.path.basename(self.name)} / {os.path.basename(right.name)}" + ) else: title = "Stereo Pair" set_window_title(fig, title) diff --git a/src/machinevisiontoolbox/ImagePointFeatures.py b/src/machinevisiontoolbox/ImagePointFeatures.py index 3654d15b..233863c8 100644 --- a/src/machinevisiontoolbox/ImagePointFeatures.py +++ b/src/machinevisiontoolbox/ImagePointFeatures.py @@ -1581,7 +1581,7 @@ def __str__(self) -> str: s = f"{len(self)} matches" if self._inliers is not None: ninlier = sum(self._inliers) - s += f", with {ninlier} ({ninlier/len(self)*100:.1f}%) inliers" + s += f", with {ninlier} ({ninlier / len(self) * 100:.1f}%) inliers" return s def __repr__(self) -> str: diff --git a/src/machinevisiontoolbox/ImageProcessing.py b/src/machinevisiontoolbox/ImageProcessing.py index a909648a..d603df2e 100644 --- a/src/machinevisiontoolbox/ImageProcessing.py +++ b/src/machinevisiontoolbox/ImageProcessing.py @@ -671,9 +671,7 @@ def apply_mode(threshold): fig, axs = plt.subplots(1, 2, figsize=(10, 5)) plt.subplots_adjust(bottom=0.1 if _use_ipywidgets else 0.25) - set_window_title( - fig, "Interactive Image Threshold" if title is None else title - ) + set_window_title(fig, "Interactive Image Threshold" if title is None else title) im = axs[0].imshow(apply_mode(t), cmap="gray") if mode == "binary": @@ -1328,12 +1326,14 @@ def paste( # only fg is valid fg_mask = cv2.bitwise_and( - src1=fg_set, src2=cv2.bitwise_xor(src1=bg_set, src2=1) # type: ignore[call-overload] + src1=fg_set, + src2=cv2.bitwise_xor(src1=bg_set, src2=1), # type: ignore[call-overload] ) # only bg is valid bg_mask = cv2.bitwise_and( - src1=cv2.bitwise_xor(src1=fg_set, src2=1), src2=bg_set # type: ignore[call-overload] + src1=cv2.bitwise_xor(src1=fg_set, src2=1), # type: ignore[call-overload] + src2=bg_set, ) # merge them @@ -1410,7 +1410,6 @@ def invert(self) -> Self: if __name__ == "__main__": - pass # tests = Path(__file__).parent.parent.parent / "tests" diff --git a/src/machinevisiontoolbox/ImageRegionFeatures.py b/src/machinevisiontoolbox/ImageRegionFeatures.py index 28e2ce8c..c9ffce0b 100644 --- a/src/machinevisiontoolbox/ImageRegionFeatures.py +++ b/src/machinevisiontoolbox/ImageRegionFeatures.py @@ -188,11 +188,7 @@ def __init__(self, image: Any = None, **kwargs: Any) -> None: # change. Logged as its own issue (#54), not something this # compat fix can address. # ----------------------------------------------------------------- - lrtb = ( - np.zeros((0, 4), dtype=int) - if len(bboxes) == 0 - else np.array(bboxes) - ) + lrtb = np.zeros((0, 4), dtype=int) if len(bboxes) == 0 else np.array(bboxes) lrtb[:, 2:] = lrtb[:, 0:2] + lrtb[:, 2:] # convert to lrtb self._bboxes = lrtb @@ -282,7 +278,7 @@ def __str__(self) -> str: if len(self) != 1: return f"MSER features, {len(self)} regions" else: - s = f"MSER feature: u: {self._bboxes[0,0]} - {self._bboxes[0,2]}, v: {self._bboxes[0,1]} - {self._bboxes[0,3]}" + s = f"MSER feature: u: {self._bboxes[0, 0]} - {self._bboxes[0, 2]}, v: {self._bboxes[0, 1]} - {self._bboxes[0, 3]}" return s def __repr__(self) -> str: diff --git a/src/machinevisiontoolbox/ImageSpatial.py b/src/machinevisiontoolbox/ImageSpatial.py index 90a66de4..8c039b1c 100644 --- a/src/machinevisiontoolbox/ImageSpatial.py +++ b/src/machinevisiontoolbox/ImageSpatial.py @@ -722,8 +722,7 @@ def canny( percentile: float = ..., k: float = ..., hist: Literal[False] = ..., - ) -> Any: - ... + ) -> Any: ... @overload def canny( @@ -735,8 +734,7 @@ def canny( k: float = ..., *, hist: Literal[True], - ) -> "tuple[Any, CannyHistogram]": - ... + ) -> "tuple[Any, CannyHistogram]": ... def canny( self, diff --git a/src/machinevisiontoolbox/ImageWholeFeatures.py b/src/machinevisiontoolbox/ImageWholeFeatures.py index cb20ecaf..a1af3287 100644 --- a/src/machinevisiontoolbox/ImageWholeFeatures.py +++ b/src/machinevisiontoolbox/ImageWholeFeatures.py @@ -1243,7 +1243,9 @@ def ncdf(self) -> np.ndarray: ) return self.cdf - def compare(self, other: "Histogram", method: str = "correlation") -> float | list[float]: + def compare( + self, other: "Histogram", method: str = "correlation" + ) -> float | list[float]: """ Compare with another histogram @@ -1315,7 +1317,9 @@ def compare(self, other: "Histogram", method: str = "correlation") -> float | li raise ValueError( f"histograms have different numbers of bins: {len(self._x)} and {len(other._x)}" ) - if np.any(np.sum(self._h, axis=0) == 0) or np.any(np.sum(other._h, axis=0) == 0): + if np.any(np.sum(self._h, axis=0) == 0) or np.any( + np.sum(other._h, axis=0) == 0 + ): raise ValueError("cannot compare an empty histogram") # one column per plane, normalized to sum to one @@ -1343,7 +1347,14 @@ def compare(self, other: "Histogram", method: str = "correlation") -> float | li def plot( self, type: Literal[ - "frequency", "pdf", "probability", "cf", "cumulative", "cdf", "normalized", "ncdf" + "frequency", + "pdf", + "probability", + "cf", + "cumulative", + "cdf", + "normalized", + "ncdf", ] = "frequency", block: bool = False, filled: bool | None = None, @@ -1555,7 +1566,10 @@ def plot( for i, ax in enumerate(axes): bin_width = x[1] - x[0] ax.stairs( - y[:, i], np.append(x, x[-1] + bin_width), fill=bool(filled), **kwargs + y[:, i], + np.append(x, x[-1] + bin_width), + fill=bool(filled), + **kwargs, ) ax.grid() if n == 1: diff --git a/src/machinevisiontoolbox/Kernel.py b/src/machinevisiontoolbox/Kernel.py index 33faed67..ad48fef9 100644 --- a/src/machinevisiontoolbox/Kernel.py +++ b/src/machinevisiontoolbox/Kernel.py @@ -126,7 +126,9 @@ def shape(self) -> tuple[int, int]: def ndim(self) -> int: return 2 - def __array__(self, dtype: Dtype | None = None, copy: bool | None = None) -> np.ndarray: + def __array__( + self, dtype: Dtype | None = None, copy: bool | None = None + ) -> np.ndarray: """ Convert to a plain NumPy array diff --git a/src/machinevisiontoolbox/PointCloud.py b/src/machinevisiontoolbox/PointCloud.py index 4dff539c..89f197a7 100644 --- a/src/machinevisiontoolbox/PointCloud.py +++ b/src/machinevisiontoolbox/PointCloud.py @@ -56,7 +56,6 @@ def __init__(self, arg: Any, depth_scale: float = 1.0, **kwargs) -> None: " ** Note that Open3d typically does not run on the latest Python version(s)" ) - if not _open3d: raise RuntimeError( "PointCloud class requires Open3D to be installed: " diff --git a/src/machinevisiontoolbox/Sources.py b/src/machinevisiontoolbox/Sources.py index 966b6010..296a7aa8 100644 --- a/src/machinevisiontoolbox/Sources.py +++ b/src/machinevisiontoolbox/Sources.py @@ -3595,7 +3595,9 @@ def _autodetect_typestore(self, rawdata: bytes, msgtype: str) -> bool: # First pass: ROS 1 wire format (ros1 and ros2 typestores). # For an image the end of the message is computed from its layout, so any # trailing bytes (eg. the RealSense SDK footer) are ignored. - end = _image_payload_end(rawdata, msgtype) if msgtype.endswith("Image") else None + end = ( + _image_payload_end(rawdata, msgtype) if msgtype.endswith("Image") else None + ) raw = rawdata if end is None else rawdata[:end] for name in self._ROS1_STORES_ORDERED + self._ROS2_STORES_ORDERED: if name not in available: @@ -3735,9 +3737,7 @@ def _image_depth_units( if self._is_realsense and len(footer) == 4: if not any(footer): return None # 0.0, a color image - units = _footer_depth_units( - footer, _wire_byteorder(rawdata, self._is_ros2) - ) + units = _footer_depth_units(footer, _wire_byteorder(rawdata, self._is_ros2)) if units is not None: return units if connection.id not in self._warned_footers: @@ -3867,7 +3867,6 @@ def __iter__(self) -> Iterator[Any]: yield img elif connection.msgtype.endswith("Image"): - if hasattr(msg, "encoding"): encoding = msg.encoding if encoding not in self._ROS_ENCODING_MAP: diff --git a/src/machinevisiontoolbox/VisualServo.py b/src/machinevisiontoolbox/VisualServo.py index 1e494f02..192563ea 100644 --- a/src/machinevisiontoolbox/VisualServo.py +++ b/src/machinevisiontoolbox/VisualServo.py @@ -1365,7 +1365,9 @@ def __init__( self.depth = depth @classmethod - def Example(cls, camera: SphericalCamera | None = None, **kwargs: Any) -> "IBVS_sph": + def Example( + cls, camera: SphericalCamera | None = None, **kwargs: Any + ) -> "IBVS_sph": # run a canned example print("canned example, spherical IBVS with 4 points") if camera is None: diff --git a/src/machinevisiontoolbox/base/graphics.py b/src/machinevisiontoolbox/base/graphics.py index 71186121..fa8e5ed3 100644 --- a/src/machinevisiontoolbox/base/graphics.py +++ b/src/machinevisiontoolbox/base/graphics.py @@ -642,7 +642,14 @@ def draw_text( else: lt = cv2.LINE_8 cv2.putText( - image, text or "", _roundvec(pos), _fontdict[font], fontsize, color, fontthickness, lt + image, + text or "", + _roundvec(pos), + _fontdict[font], + fontsize, + color, + fontthickness, + lt, ) return image @@ -977,7 +984,9 @@ def draw_circle( def mpl_styling( - fmt: str | tuple[str] | None = None, defaults: dict | None = None, kwargs: dict | None = None + fmt: str | tuple[str] | None = None, + defaults: dict | None = None, + kwargs: dict | None = None, ): """Merge Matplotlib style options diff --git a/src/machinevisiontoolbox/bin/imtool.py b/src/machinevisiontoolbox/bin/imtool.py index b0cdf24b..7ac10215 100755 --- a/src/machinevisiontoolbox/bin/imtool.py +++ b/src/machinevisiontoolbox/bin/imtool.py @@ -174,9 +174,7 @@ def visualize_image(image, args, block): ax = fig.gca() # Attach interactive rectangle / line-profile overlay. - _nav_help = ( - " x close image and advance to next file\n" " q close window\n" - ) + _nav_help = " x close image and advance to next file\n q close window\n" ImageInteractor(fig, ax, image, nav_help=_nav_help) def _on_exit(event): diff --git a/src/machinevisiontoolbox/bin/mvtbtool.py b/src/machinevisiontoolbox/bin/mvtbtool.py index 40f2ce78..5911d801 100755 --- a/src/machinevisiontoolbox/bin/mvtbtool.py +++ b/src/machinevisiontoolbox/bin/mvtbtool.py @@ -247,7 +247,7 @@ def make_banner(args, optional_modules=None): textwrap.wrap( versions, break_long_words=False, - subsequent_indent=" " * len("You" "re running: "), + subsequent_indent=" " * len("Youre running: "), width=80, ) ) @@ -302,17 +302,25 @@ def run_smoke_test() -> bool: import open3d # noqa: F401 -- presence check; PointCloud does the real work except ImportError as e: checks.append( - (f"PointCloud.Read('bunny.ply') + voxel_grid(): Open3D not installed ({e})", False) + ( + f"PointCloud.Read('bunny.ply') + voxel_grid(): Open3D not installed ({e})", + False, + ) ) else: try: bunny = PointCloud.Read("bunny.ply") voxels = bunny.voxel_grid(voxel_size=0.01) ok = len(bunny) > 0 and len(voxels._voxels.get_voxels()) > 0 - checks.append(("PointCloud.Read('bunny.ply') + voxel_grid() (Open3D-backed)", ok)) + checks.append( + ("PointCloud.Read('bunny.ply') + voxel_grid() (Open3D-backed)", ok) + ) except Exception as e: # noqa: BLE001 - a self-check reports any failure, it must not crash checks.append( - (f"PointCloud.Read('bunny.ply') + voxel_grid() (Open3D-backed): {e}", False) + ( + f"PointCloud.Read('bunny.ply') + voxel_grid() (Open3D-backed): {e}", + False, + ) ) for name, passed in checks: @@ -388,7 +396,7 @@ def out_prompt_tokens(self, cli=None): c.InteractiveShell.ast_node_interactivity = "last_expr_or_assign" code = [ - f"%matplotlib{' '+args.backend if args.backend is not None else ''}", + f"%matplotlib{' ' + args.backend if args.backend is not None else ''}", "import matplotlib.pyplot as plt", "_prec = get_ipython().run_line_magic('precision', '%.3g'); " "print(f'Default numeric formatting: {_prec}')", @@ -411,7 +419,7 @@ def out_prompt_tokens(self, cli=None): images = [] for i, filename in enumerate(args.images, 1): if len(args.images) > 1: - print(f" {filename} --> img[{i-1}]") + print(f" {filename} --> img[{i - 1}]") else: print(f" {filename} --> img") images.append(Image.Read(filename)) diff --git a/src/machinevisiontoolbox/blocks/camera.py b/src/machinevisiontoolbox/blocks/camera.py index 4697b93e..3d67c100 100644 --- a/src/machinevisiontoolbox/blocks/camera.py +++ b/src/machinevisiontoolbox/blocks/camera.py @@ -1,4 +1,3 @@ - from bdsim.components import FunctionBlock from bdsim.graphics import GraphicsBlock diff --git a/tests/base/test_base_color.py b/tests/base/test_base_color.py index d228cab9..99b0da45 100644 --- a/tests/base/test_base_color.py +++ b/tests/base/test_base_color.py @@ -11,32 +11,31 @@ class TestColor(unittest.TestCase): - def test_blackbody(self): e = color.blackbody(500e-9, 4000) - self.assertAlmostEqual(e, 2.86512308e+12, delta=1e4) + self.assertAlmostEqual(e, 2.86512308e12, delta=1e4) e = color.blackbody([400e-9, 500e-9], 4000) self.assertEqual(len(e), 2) - self.assertAlmostEqual(e[0], 1.44662486e+12, delta=1e4) - self.assertAlmostEqual(e[1], 2.86512308e+12, delta=1e4) + self.assertAlmostEqual(e[0], 1.44662486e12, delta=1e4) + self.assertAlmostEqual(e[1], 2.86512308e12, delta=1e4) def test_loadspectrum(self): - data_dir = Path.cwd() / 'machinevisiontoolbox' / 'data' + data_dir = Path.cwd() / "machinevisiontoolbox" / "data" nm = 1e-9 λ = np.linspace(400, 700, 30) * nm - brick = color.loadspectrum(λ, 'redbrick') + brick = color.loadspectrum(λ, "redbrick") self.assertEqual(brick.shape, (30,)) - cone = color.loadspectrum(λ, 'cones') + cone = color.loadspectrum(λ, "cones") self.assertEqual(cone.shape, (30, 3)) # tests outside of interpolation range λ2 = np.linspace(300, 1000, 50) * nm - solar = color.loadspectrum(λ2, 'solar') + solar = color.loadspectrum(λ2, "solar") self.assertEqual(solar.shape, (50,)) # lam_water = np.linspace(400, 700, 30) * nm @@ -51,15 +50,13 @@ def test_chromaticity(self): rg = color.lambda2rg(555e-9) self.assertEqual(rg.shape, (1, 2)) - rg = color.lambda2rg(lam=np.array([555e-9, 666e-9]), - e=np.array([4, 1])) + rg = color.lambda2rg(lam=np.array([555e-9, 666e-9]), e=np.array([4, 1])) self.assertEqual(rg.shape, (1, 2)) xy = color.lambda2xy(555e-9) self.assertEqual(xy.shape, (1, 2)) - xy = color.lambda2rg(lam=np.r_[555e-9, 666e-9], - e=np.r_[4, 1, 2]) + xy = color.lambda2rg(lam=np.r_[555e-9, 666e-9], e=np.r_[4, 1, 2]) self.assertEqual(xy.shape, (1, 2)) # create Bayer pattern @@ -75,7 +72,7 @@ def test_chromaticity(self): nt.assert_array_almost_equal(cc, cc_ans) # chromaticity is invariant to intensity (im/2) - cc = color.tristim2cc(im/2) + cc = color.tristim2cc(im / 2) cc_ans = np.array([[[1, 0], [0, 1]], [[0, 1], [0, 0]]]) nt.assert_array_almost_equal(cc, cc_ans) @@ -131,31 +128,31 @@ def test_lambda2xy(self): def test_name2color(self): """Test named color lookup""" # Basic colors - red = color.name2color('red') + red = color.name2color("red") self.assertEqual(len(red), 3) self.assertEqual(red[0], 1) - blue = color.name2color('blue') + blue = color.name2color("blue") self.assertEqual(blue[2], 1) # Short names - r = color.name2color('r') + r = color.name2color("r") self.assertEqual(r[0], 1) # Test different color spaces - g_xy = color.name2color('g', 'xy') + g_xy = color.name2color("g", "xy") self.assertEqual(len(g_xy), 2) def test_name2color_colororder(self): """colororder= must still return an ndarray, not a list -- regression test for a bug where the reordering used a list comprehension and silently dropped the ndarray return type""" - red_rgb = color.name2color('red', colororder={'R': 0, 'G': 1, 'B': 2}) + red_rgb = color.name2color("red", colororder={"R": 0, "G": 1, "B": 2}) self.assertIsInstance(red_rgb, np.ndarray) nt.assert_array_almost_equal(red_rgb, [1, 0, 0]) # reordered: B first, so red's 1.0 moves to the last position - red_bgr = color.name2color('red', colororder={'B': 0, 'G': 1, 'R': 2}) + red_bgr = color.name2color("red", colororder={"B": 0, "G": 1, "R": 2}) self.assertIsInstance(red_bgr, np.ndarray) nt.assert_array_almost_equal(red_bgr, [0, 0, 1]) @@ -171,8 +168,8 @@ def test_tristim2cc(self): white = np.array([1, 1, 1]) cc = color.tristim2cc(white) # White point should be around [1/3, 1/3] - self.assertAlmostEqual(cc[0], 1/3, delta=0.01) - self.assertAlmostEqual(cc[1], 1/3, delta=0.01) + self.assertAlmostEqual(cc[0], 1 / 3, delta=0.01) + self.assertAlmostEqual(cc[1], 1 / 3, delta=0.01) # Pure red red = np.array([1, 0, 0]) @@ -210,6 +207,5 @@ def test_color_conversion_functions(self): # ---------------------------------------------------------------------------# -if __name__ == '__main__': - +if __name__ == "__main__": unittest.main() diff --git a/tests/base/test_idisp_display_readback.py b/tests/base/test_idisp_display_readback.py index 9a7624d3..a88edaac 100644 --- a/tests/base/test_idisp_display_readback.py +++ b/tests/base/test_idisp_display_readback.py @@ -65,8 +65,12 @@ def _assert_min_black_max_white(self, im: np.ndarray, msg: str): idisp(im, matplotlib=True, fig=fig, ax=ax, block=None) lo = _mpl_pixel_rgba(fig, ax, 0, 0) hi = _mpl_pixel_rgba(fig, ax, 3, 3) - self.assertTrue(np.all(lo[:3] <= 10), f"{msg}: min-value pixel not black: {lo}") - self.assertTrue(np.all(hi[:3] >= 245), f"{msg}: max-value pixel not white: {hi}") + self.assertTrue( + np.all(lo[:3] <= 10), f"{msg}: min-value pixel not black: {lo}" + ) + self.assertTrue( + np.all(hi[:3] >= 245), f"{msg}: max-value pixel not white: {hi}" + ) finally: matplotlib.pyplot.close(fig) diff --git a/tests/base/test_io.py b/tests/base/test_io.py index 3bec7fee..62d49675 100644 --- a/tests/base/test_io.py +++ b/tests/base/test_io.py @@ -53,7 +53,9 @@ def test_iread(self): # URL image try: - im = iread("https://raw.githubusercontent.com/petercorke/machinevision-toolbox-python/main/packages/mvtb-data/mvtbdata/images/monalisa.png") + im = iread( + "https://raw.githubusercontent.com/petercorke/machinevision-toolbox-python/main/packages/mvtb-data/mvtbdata/images/monalisa.png" + ) except (ValueError, urllib.error.URLError) as e: raise unittest.SkipTest(f"Network unavailable: {e}") from e self.assertIsInstance(im[0], np.ndarray) @@ -622,7 +624,9 @@ def test_iread_url_handling(self): """Test iread with URL""" # This tests the URL loading path try: - im, filename = iread("https://raw.githubusercontent.com/petercorke/machinevision-toolbox-python/main/packages/mvtb-data/mvtbdata/images/monalisa.png") + im, filename = iread( + "https://raw.githubusercontent.com/petercorke/machinevision-toolbox-python/main/packages/mvtb-data/mvtbdata/images/monalisa.png" + ) except (ValueError, urllib.error.URLError) as e: raise unittest.SkipTest(f"Network unavailable: {e}") from e self.assertIsInstance(im, np.ndarray) diff --git a/tests/create_ros_fixture.py b/tests/create_ros_fixture.py index 5d74d415..643147a0 100644 --- a/tests/create_ros_fixture.py +++ b/tests/create_ros_fixture.py @@ -240,7 +240,7 @@ def _make_ros2() -> None: def realsense_depth_frame(i: int) -> np.ndarray: """Expected pixels of depth frame ``i`` in a bag from :func:`make_realsense_bag`.""" - return (np.arange(RS_H * RS_W, dtype=np.uint16).reshape(RS_H, RS_W) * 7 + 100 * i) + return np.arange(RS_H * RS_W, dtype=np.uint16).reshape(RS_H, RS_W) * 7 + 100 * i def depth_pixels(i: int, encoding: str) -> np.ndarray: @@ -251,7 +251,7 @@ def depth_pixels(i: int, encoding: str) -> np.ndarray: def realsense_color_frame(i: int) -> np.ndarray: """Expected pixels of color frame ``i`` in a bag from :func:`make_realsense_bag`.""" - return (np.arange(RS_H * RS_W * 3, dtype=np.uint8).reshape(RS_H, RS_W, 3) + 10 * i) + return np.arange(RS_H * RS_W * 3, dtype=np.uint8).reshape(RS_H, RS_W, 3) + 10 * i def make_realsense_bag( @@ -326,7 +326,12 @@ def footer_bytes(value: float) -> bytes: else Header(stamp=stamp, frame_id="") ) for conn, enc, pixels, scale in [ - (conn_depth, depth_encoding, depth_pixels(i, depth_encoding), RS_DEPTH_UNITS), + ( + conn_depth, + depth_encoding, + depth_pixels(i, depth_encoding), + RS_DEPTH_UNITS, + ), (conn_color, "rgb8", realsense_color_frame(i), 0.0), ]: msg = Image( diff --git a/tests/test_bag_of_words.py b/tests/test_bag_of_words.py index 4c30e701..7f94fa7e 100644 --- a/tests/test_bag_of_words.py +++ b/tests/test_bag_of_words.py @@ -13,7 +13,6 @@ class TestBagOfWords(unittest.TestCase): - def test_retrieve(self): images = FileCollection("campus/*.png", mono=True) diff --git a/tests/test_bin.py b/tests/test_bin.py index 5e4311e8..cde1e03f 100644 --- a/tests/test_bin.py +++ b/tests/test_bin.py @@ -14,18 +14,21 @@ try: import rosbags # noqa: F401 + _rosbags_available = True except ImportError: _rosbags_available = False try: import pytesseract # noqa: F401 + _pytesseract_available = True except ImportError: _pytesseract_available = False try: import open3d # noqa: F401 + _open3d_available = True except ImportError: _open3d_available = False @@ -47,7 +50,6 @@ def _run(args: list[str], timeout: float | None = None) -> subprocess.CompletedP class TestMvtbtool(unittest.TestCase): - def test_help(self): result = _run(["machinevisiontoolbox.bin.mvtbtool", "--help"]) self.assertEqual(result.returncode, 0, msg=result.stderr.decode()) @@ -68,7 +70,6 @@ def test_smoke_test(self): class TestImtool(unittest.TestCase): - def test_help(self): result = _run(["machinevisiontoolbox.bin.imtool", "--help"]) self.assertEqual(result.returncode, 0, msg=result.stderr.decode()) @@ -88,7 +89,6 @@ def test_display_image(self): class TestTagtool(unittest.TestCase): - def test_help(self): result = _run(["machinevisiontoolbox.bin.tagtool", "--help"]) self.assertEqual(result.returncode, 0, msg=result.stderr.decode()) @@ -107,7 +107,6 @@ def test_display_image(self): @unittest.skipUnless(_rosbags_available, "rosbags not installed") class TestBagtool(unittest.TestCase): - def test_help(self): result = _run(["machinevisiontoolbox.bin.bagtool", "--help"]) self.assertEqual(result.returncode, 0, msg=result.stderr.decode()) @@ -115,7 +114,6 @@ def test_help(self): @unittest.skipUnless(_pytesseract_available, "pytesseract not installed") class TestOcrtool(unittest.TestCase): - def test_help(self): result = _run(["machinevisiontoolbox.bin.ocrtool", "--help"]) self.assertEqual(result.returncode, 0, msg=result.stderr.decode()) diff --git a/tests/test_camera.py b/tests/test_camera.py index 12350741..bdb37cd6 100644 --- a/tests/test_camera.py +++ b/tests/test_camera.py @@ -12,7 +12,6 @@ class TestCamera(unittest.TestCase): - def test_parameters(self): c = CentralCamera(f=0.2) @@ -418,5 +417,4 @@ def test_plot_unbound_without_pose_raises(self): # ----------------------------------------------------------------------- # if __name__ == "__main__": - unittest.main() diff --git a/tests/test_examples_run.py b/tests/test_examples_run.py index 78c81d16..bbc7b771 100644 --- a/tests/test_examples_run.py +++ b/tests/test_examples_run.py @@ -32,7 +32,13 @@ # examples that fetch from the internet: a network failure skips, not fails NETWORK = {"monalisa.py"} -NETWORK_ERRORS = ("URLError", "ConnectionError", "TimeoutError", "HTTPError", "gaierror") +NETWORK_ERRORS = ( + "URLError", + "ConnectionError", + "TimeoutError", + "HTTPError", + "gaierror", +) # morphdemo redraws the figure for every pixel, which is slow on a CI runner; a # few frames exercise the same code as all of them @@ -46,7 +52,13 @@ def test_example_runs(script): # UTF-8 output, since examples print maths symbols that the Windows default cannot encode env = dict(os.environ, MPLBACKEND="Agg", PYTHONUTF8="1", PYTHONIOENCODING="utf-8") result = subprocess.run( - [sys.executable, "-W", "error::DeprecationWarning", script, *ARGS.get(script, [])], + [ + sys.executable, + "-W", + "error::DeprecationWarning", + script, + *ARGS.get(script, []), + ], cwd=EXAMPLES, env=env, capture_output=True, @@ -56,4 +68,6 @@ def test_example_runs(script): if result.returncode != 0: if script in NETWORK and any(e in result.stderr for e in NETWORK_ERRORS): pytest.skip("network not available") - pytest.fail(f"{script} exited with {result.returncode}:\n{result.stderr[-2000:]}") + pytest.fail( + f"{script} exited with {result.returncode}:\n{result.stderr[-2000:]}" + ) diff --git a/tests/test_examples_smoke.py b/tests/test_examples_smoke.py index 6a5acbd4..abb92de7 100644 --- a/tests/test_examples_smoke.py +++ b/tests/test_examples_smoke.py @@ -14,7 +14,6 @@ class TestExamplesSmoke(unittest.TestCase): - def test_examples_exist(self): examples_dir = Path(__file__).resolve().parents[1] / "examples" scripts = sorted(examples_dir.glob("*.py")) diff --git a/tests/test_image_blobs.py b/tests/test_image_blobs.py index 20a9ee2b..2c1f581a 100644 --- a/tests/test_image_blobs.py +++ b/tests/test_image_blobs.py @@ -18,7 +18,6 @@ class TestBlobs(unittest.TestCase): - def test_blob_2x2_square(self): # 1 blob: 2x2 im = Image.String( @@ -813,5 +812,4 @@ def test_plot_MER_kwargs(self): # ------------------------------------------------------------------------ # if __name__ == "__main__": - unittest.main() diff --git a/tests/test_image_color.py b/tests/test_image_color.py index fab571e1..9a2185f6 100644 --- a/tests/test_image_color.py +++ b/tests/test_image_color.py @@ -10,7 +10,6 @@ class TestImageProcessingColor(unittest.TestCase): - def test_color2name(self): name = color2name([1, 0, 0]) self.assertIsInstance(name, str) @@ -267,7 +266,6 @@ def test_kmeans_no_args_raises(self): class TestBaseColorFunctions(unittest.TestCase): - def test_luminos_scalar(self): y = luminos(555e-9) # peak photopic luminosity (555 nm) ≈ 683 lm/W @@ -358,7 +356,6 @@ def test_colorspace_convert_rgb_to_luv(self): # ----------------------------------------------------------------------------# if __name__ == "__main__": - unittest.main() # import code diff --git a/tests/test_image_constants.py b/tests/test_image_constants.py index 8c29425c..beecdb39 100644 --- a/tests/test_image_constants.py +++ b/tests/test_image_constants.py @@ -162,15 +162,12 @@ def test_string_binary_and_numeric(self): ) ) - im = ( - Image.String( - r""" + im = Image.String( + r""" 001200 000345 """ - ) - - ord("0") - ) + ) - ord("0") self.assertEqual(im.size, (6, 2)) self.assertEqual(im.dtype, np.uint8) diff --git a/tests/test_image_fiducials.py b/tests/test_image_fiducials.py index 6ccfec86..0eb3a8ee 100644 --- a/tests/test_image_fiducials.py +++ b/tests/test_image_fiducials.py @@ -110,9 +110,7 @@ def test_board_estimatePose_ignores_other_markers(self): board = ArUcoBoard( layout=(2, 2), sidelength=0.04, separation=0.01, dict="4x4_50", firsttag=10 ) - camera = CentralCamera( - f=0.015, rho=1e-5, imagesize=(1000, 1000), pp=(500, 500) - ) + camera = CentralCamera(f=0.015, rho=1e-5, imagesize=(1000, 1000), pp=(500, 500)) # reference: only the board's own markers in view T0, stats0, ids0, markers0 = board.estimatePose( @@ -142,9 +140,7 @@ def test_board_estimatePose_no_board_markers(self): board = ArUcoBoard( layout=(2, 2), sidelength=0.04, separation=0.01, dict="4x4_50", firsttag=10 ) - camera = CentralCamera( - f=0.015, rho=1e-5, imagesize=(1000, 1000), pp=(500, 500) - ) + camera = CentralCamera(f=0.015, rho=1e-5, imagesize=(1000, 1000), pp=(500, 500)) # a marker that is not on the board, and a scene with no markers at all other = self._single_marker_scene("4x4_50", marker_id=3, side=200, canvas=1000) diff --git a/tests/test_image_morph.py b/tests/test_image_morph.py index be12fe1d..ffab1fb7 100644 --- a/tests/test_image_morph.py +++ b/tests/test_image_morph.py @@ -10,7 +10,6 @@ class TestImageProcessingMorph(unittest.TestCase): - def test_morph_scalar_se(self): # test simple case @@ -486,5 +485,4 @@ def test_close_bool(self): # ----------------------------------------------------------------------- # if __name__ == "__main__": - unittest.main() diff --git a/tests/test_image_point_features.py b/tests/test_image_point_features.py index 3b34f90c..349d0ebe 100644 --- a/tests/test_image_point_features.py +++ b/tests/test_image_point_features.py @@ -11,7 +11,6 @@ class TestImageCoreOperations(unittest.TestCase): - def test_copy(self): """Test image copying""" img = Image.Read("monalisa.png") @@ -117,7 +116,6 @@ def test_get_pixel(self): class TestImagePointFeatures(unittest.TestCase): - def test_sift(self): """Test SIFT feature detection""" img = Image.Read("monalisa.png", mono=True) @@ -150,7 +148,9 @@ def test_surf_nonfree_message(self): img = Image.Read("flowers1.png", mono=True) err = cv2.error("(-213:The function/feature is not implemented) patented") - with mock.patch.object(cv2.xfeatures2d, "SURF_create", side_effect=err, create=True): + with mock.patch.object( + cv2.xfeatures2d, "SURF_create", side_effect=err, create=True + ): with self.assertRaises(RuntimeError) as cm: img.SURF() self.assertIn("OPENCV_ENABLE_NONFREE", str(cm.exception)) @@ -165,7 +165,9 @@ def test_surf_without_contrib(self): from machinevisiontoolbox._cv2_contrib import _MissingContrib img = Image.Read("flowers1.png", mono=True) - with mock.patch.object(cv2, "xfeatures2d", _MissingContrib("xfeatures2d"), create=True): + with mock.patch.object( + cv2, "xfeatures2d", _MissingContrib("xfeatures2d"), create=True + ): with self.assertRaises(AttributeError) as cm: img.SURF() self.assertIn("opencv-contrib-python", str(cm.exception)) @@ -180,7 +182,10 @@ def test_surf_features(self): img = Image.Read("flowers1.png", mono=True) with mock.patch.object( - cv2.xfeatures2d, "SURF_create", side_effect=lambda **kw: cv2.SIFT_create(**kw), create=True + cv2.xfeatures2d, + "SURF_create", + side_effect=lambda **kw: cv2.SIFT_create(**kw), + create=True, ): surf = img.SURF() self.assertIsInstance(surf, SURFFeature) diff --git a/tests/test_image_processing.py b/tests/test_image_processing.py index a3183108..4b61e8b6 100644 --- a/tests/test_image_processing.py +++ b/tests/test_image_processing.py @@ -15,7 +15,6 @@ class TestImageProcessingBase(unittest.TestCase): - def test_LUT_basic(self): """Test lookup table application""" # Create simple image @@ -523,7 +522,6 @@ def test_LUT(self): class TestImageProcessingOperations(unittest.TestCase): - def test_clip(self): img = Image([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) out = img.clip(3, 7) @@ -638,7 +636,6 @@ def test_invert_float(self): class TestImageProcessingKernel(unittest.TestCase): - def test_similarity(self): a = np.array( @@ -700,5 +697,4 @@ def test_window(self): # ----------------------------------------------------------------------- # if __name__ == "__main__": - unittest.main() diff --git a/tests/test_image_processing_kernel.py b/tests/test_image_processing_kernel.py index 33872d2a..37664bc5 100644 --- a/tests/test_image_processing_kernel.py +++ b/tests/test_image_processing_kernel.py @@ -11,13 +11,16 @@ class TestImageProcessingKernel(unittest.TestCase): - def test_similarity(self): - a = np.array([[0.9280, 0.3879, 0.8679], - [0.1695, 0.3826, 0.7415], - [0.8837, 0.2715, 0.4479]]) - a = Image(a, dtype='float64') + a = np.array( + [ + [0.9280, 0.3879, 0.8679], + [0.1695, 0.3826, 0.7415], + [0.8837, 0.2715, 0.4479], + ] + ) + a = Image(a, dtype="float64") eps = 1e-6 # self.assertAlmostEqual(a.sad(a), eps) @@ -44,11 +47,15 @@ def test_similarity(self): # yet been implemented in mvt def test_window(self): - im = np.array([[3, 5, 8, 10, 9], - [7, 10, 3, 6, 3], - [7, 4, 6, 2, 9], - [2, 6, 7, 2, 3], - [2, 3, 9, 3, 10]]) + im = np.array( + [ + [3, 5, 8, 10, 9], + [7, 10, 3, 6, 3], + [7, 4, 6, 2, 9], + [2, 6, 7, 2, 3], + [2, 3, 9, 3, 10], + ] + ) img = Image(im) se = np.ones((1, 1)) # se must be same number of dimensions as input image for scipy @@ -58,11 +65,15 @@ def test_window(self): nt.assert_array_almost_equal(img.window(np.sum, se=se).A, im) se = np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]]) - out = np.array([[43, 47, 57, 56, 59], - [46, 43, 51, 50, 57], - [45, 48, 40, 39, 31], - [33, 40, 35, 49, 48], - [22, 40, 36, 53, 44]]) + out = np.array( + [ + [43, 47, 57, 56, 59], + [46, 43, 51, 50, 57], + [45, 48, 40, 39, 31], + [33, 40, 35, 49, 48], + [22, 40, 36, 53, 44], + ] + ) nt.assert_array_almost_equal(img.window(np.sum, se=se).A, out) # TODO @@ -81,7 +92,5 @@ def test_window(self): # ----------------------------------------------------------------------- # -if __name__ == '__main__': - +if __name__ == "__main__": unittest.main() - diff --git a/tests/test_image_region_features.py b/tests/test_image_region_features.py index 3b02f2a4..878dd171 100644 --- a/tests/test_image_region_features.py +++ b/tests/test_image_region_features.py @@ -10,7 +10,6 @@ class TestImageRegionFeatures(unittest.TestCase): - def test_mser_basic(self): """Test MSER feature detection""" im = Image.Read("castle.png") diff --git a/tests/test_image_sources.py b/tests/test_image_sources.py index 7459fa3a..9ded79e1 100644 --- a/tests/test_image_sources.py +++ b/tests/test_image_sources.py @@ -62,7 +62,6 @@ def _has_file(*args): class TestImageSources(unittest.TestCase): - def test_filecollection(self): # single str with wild card for folder of images # print('test_wildcardstr') @@ -241,7 +240,6 @@ def text(self, *_args, **_kwargs): class TestZipArchiveFormats(unittest.TestCase): - @staticmethod def _sample_members(tmpdir: Path) -> dict[str, bytes]: pgm = b"P5\n2 2\n255\n" + bytes([0, 255, 255, 0]) @@ -364,7 +362,6 @@ def _fake_run(cmd, **kwargs): @unittest.skipUnless(_torch_available, "PyTorch not installed") class TestTensorStack(unittest.TestCase): - def test_tensorstack_init_4d_rgb(self): """TensorStack initializes with (B, C, H, W) tensor.""" batch = torch.randn(5, 3, 64, 64) @@ -536,7 +533,6 @@ def test_tensorstack_cuda_tensor(self): @unittest.skipUnless(_labelme_available, "labelme not installed") class TestLabelMeReader(unittest.TestCase): - def test_labelme_read(self): """LabelMe returns image, polygons with attrs, and file flags.""" from machinevisiontoolbox import LabelMeReader @@ -551,9 +547,9 @@ def test_labelme_read(self): import cv2 as cv - assert cv.imwrite( - image_path, image_data - ), f"cv.imwrite failed: {image_path}" + assert cv.imwrite(image_path, image_data), ( + f"cv.imwrite failed: {image_path}" + ) import base64 diff --git a/tests/test_image_spatial_extra.py b/tests/test_image_spatial_extra.py index afe6ba81..af1fad9c 100644 --- a/tests/test_image_spatial_extra.py +++ b/tests/test_image_spatial_extra.py @@ -6,7 +6,6 @@ directly with NumPy, so nothing is mocked. """ - import cv2 import numpy as np import numpy.testing as nt diff --git a/tests/test_image_tensor.py b/tests/test_image_tensor.py index 07ace1ae..b70b0ddb 100644 --- a/tests/test_image_tensor.py +++ b/tests/test_image_tensor.py @@ -16,7 +16,6 @@ @unittest.skipUnless(_torch_available, "PyTorch not installed") class TestImageTensor(unittest.TestCase): - def test_to_tensor_shape_mono(self): """Mono image produces tensor of shape (1, H, W)""" img = Image.Zeros(size=(64, 64), dtype="uint8") diff --git a/tests/test_image_whole_features.py b/tests/test_image_whole_features.py index 724b77aa..b0071b41 100644 --- a/tests/test_image_whole_features.py +++ b/tests/test_image_whole_features.py @@ -12,9 +12,8 @@ class TestImageWholeFeatures(unittest.TestCase): # hist def test_hist(self): - im = ( - Image.String( - r""" + im = Image.String( + r""" 123456789 12345b789 123a56789 @@ -22,9 +21,7 @@ def test_hist(self): 123456c89 123456789 """ - ) - - ord("0") - ) + ) - ord("0") h = im.hist() @@ -551,7 +548,15 @@ def test_identical(self): def test_returns_float(self): h1, h2 = self._hist(1), self._hist(2) - for method in ("correlation", "chisqr", "intersection", "bhattacharyya", "chisqr_alt", "kl_div", "emd"): + for method in ( + "correlation", + "chisqr", + "intersection", + "bhattacharyya", + "chisqr_alt", + "kl_div", + "emd", + ): with self.subTest(method=method): self.assertIsInstance(h1.compare(h2, method), float) @@ -570,15 +575,27 @@ def test_asymmetry(self): h1, h2 = self._hist(1), self._hist(3) for method in ("chisqr", "kl_div"): with self.subTest(method=method): - self.assertNotAlmostEqual(h1.compare(h2, method), h2.compare(h1, method), places=3) - for method in ("correlation", "intersection", "bhattacharyya", "chisqr_alt", "emd"): + self.assertNotAlmostEqual( + h1.compare(h2, method), h2.compare(h1, method), places=3 + ) + for method in ( + "correlation", + "intersection", + "bhattacharyya", + "chisqr_alt", + "emd", + ): with self.subTest(method=method): - self.assertAlmostEqual(h1.compare(h2, method), h2.compare(h1, method), places=5) + self.assertAlmostEqual( + h1.compare(h2, method), h2.compare(h1, method), places=5 + ) def test_image_size_does_not_matter(self): small = Image(np.tile(np.arange(256, dtype=np.uint8), (4, 1))) large = Image(np.tile(np.arange(256, dtype=np.uint8), (16, 1))) - self.assertAlmostEqual(small.hist().compare(large.hist(), "correlation"), 1.0, places=5) + self.assertAlmostEqual( + small.hist().compare(large.hist(), "correlation"), 1.0, places=5 + ) self.assertAlmostEqual(small.hist().compare(large.hist(), "emd"), 0.0, places=5) def test_abbreviations(self): diff --git a/tests/test_pointcloud.py b/tests/test_pointcloud.py index 410acc65..5fef3b52 100644 --- a/tests/test_pointcloud.py +++ b/tests/test_pointcloud.py @@ -11,6 +11,7 @@ try: import open3d # noqa: F401 + open3d_available = True except ImportError: open3d_available = False diff --git a/tests/test_ros.py b/tests/test_ros.py index 5998c76b..ec4a0d82 100644 --- a/tests/test_ros.py +++ b/tests/test_ros.py @@ -127,7 +127,6 @@ def test_ambiguous_raises(self): @_skip_import @_skip_bags class TestRosBagRos1(unittest.TestCase): - def _bag(self, **kwargs): return ROSBag(str(ROS1_BAG), release="noetic", **kwargs) @@ -243,7 +242,6 @@ def test_format_local_time_returns_string(self): @_skip_import @_skip_bags class TestRosBagRos2(unittest.TestCase): - def _bag(self, **kwargs): return ROSBag(str(ROS2_BAG), release="humble", **kwargs) @@ -284,7 +282,6 @@ def test_imu_passthrough_has_topic_and_timestamp(self): class TestRosMessage(unittest.TestCase): - def _make(self, **kwargs): defaults = dict( topic="/test", @@ -334,7 +331,6 @@ def _make_mock_stream(output="image", message="sensor_msgs/CompressedImage"): @pytest.mark.skipif(not _roslibpy_importable, reason="roslibpy not installed") class TestRosTopicCallback(unittest.TestCase): - def _jpeg_msg(self, r=128, g=100, b=50): """Build a minimal roslibpy compressed-image message dict.""" import base64 @@ -423,7 +419,6 @@ def test_event_set_after_callback(self): @pytest.mark.skipif(not _roslibpy_importable, reason="roslibpy not installed") class TestRosTopicValidation(unittest.TestCase): - def test_invalid_output_value(self): with self.assertRaises(ValueError): _make_mock_stream(output="bad_value") @@ -560,7 +555,6 @@ def _gen(): class TestSyncRosStreams(unittest.TestCase): - def test_requires_two_streams(self): s = _fake_stream(1) with self.assertRaises(ValueError): diff --git a/tests/test_ros_depth_units.py b/tests/test_ros_depth_units.py index bee7d2e3..469ec9a3 100644 --- a/tests/test_ros_depth_units.py +++ b/tests/test_ros_depth_units.py @@ -43,7 +43,9 @@ def read(path, **kwargs): return depth, color, [w for w in caught if issubclass(w.category, RuntimeWarning)] -@pytest.mark.parametrize("value", [0, -1, 0.0, float("nan"), float("inf"), "metres", True]) +@pytest.mark.parametrize( + "value", [0, -1, 0.0, float("nan"), float("inf"), "metres", True] +) def test_depth_units_must_be_none_auto_or_a_positive_number(tmp_path, value): with pytest.raises(ValueError, match="depth_units"): ROSBag(tmp_path / "x.bag", depth_units=value) @@ -132,7 +134,9 @@ def test_32fc1_is_left_alone_apart_from_its_scale(tmp_path): gain, _, _ = read(tmp_path / "rs.bag", depth_units=2.0) for k in range(3): np.testing.assert_allclose(auto[k].array, depth_pixels(k, "32FC1"), rtol=1e-6) - np.testing.assert_allclose(gain[k].array, 2 * depth_pixels(k, "32FC1"), rtol=1e-6) + np.testing.assert_allclose( + gain[k].array, 2 * depth_pixels(k, "32FC1"), rtol=1e-6 + ) assert auto[k].array.dtype == np.float32 diff --git a/tests/test_ros_realsense.py b/tests/test_ros_realsense.py index e1fe4697..9de4b7d1 100644 --- a/tests/test_ros_realsense.py +++ b/tests/test_ros_realsense.py @@ -109,7 +109,9 @@ def serialize_image( @pytest.mark.parametrize("wire", WIRES) -@pytest.mark.parametrize("msgtype", ["sensor_msgs/msg/Image", "sensor_msgs/msg/CompressedImage"]) +@pytest.mark.parametrize( + "msgtype", ["sensor_msgs/msg/Image", "sensor_msgs/msg/CompressedImage"] +) @pytest.mark.parametrize("frame_id", ["", "c", "cam", "camera_1"]) # alignment @pytest.mark.parametrize("encoding", ["mono16", "rgb8", "mono8"]) @pytest.mark.parametrize("extra", [b"", b"\x00" * 4, b"\x6f\x12\x83\x3a", b"\x01" * 8]) @@ -130,7 +132,10 @@ def test_payload_end_rejects_what_is_not_an_image(wire): assert _image_payload_end(raw[:20], msgtype, cdr) is None # inside the header # the data array is not height * step bytes long, so this is not a valid Image for data_len in (3 * 10 - 1, 3 * 10 + 1, 0): - assert _image_payload_end(serialize_image(wire, data_len=data_len), msgtype, cdr) is None + assert ( + _image_payload_end(serialize_image(wire, data_len=data_len), msgtype, cdr) + is None + ) assert _image_payload_end(bytes(range(200)), msgtype, cdr) is None @@ -148,7 +153,9 @@ def test_footer_is_a_positive_finite_float32(order): assert _footer_depth_units(struct.pack(order + "f", bad), order) is None -@pytest.mark.parametrize("footer", [b"", b"\x00", b"\x6f\x12\x83", b"\x6f\x12\x83\x3a\x00"]) +@pytest.mark.parametrize( + "footer", [b"", b"\x00", b"\x6f\x12\x83", b"\x6f\x12\x83\x3a\x00"] +) def test_footer_must_be_four_bytes(footer): assert _footer_depth_units(footer) is None @@ -166,7 +173,9 @@ def test_footer_must_be_four_bytes(footer): @pytest.mark.parametrize("wire, footer, streaminfo, release", CASES) -def test_realsense_style_bag_is_read_exactly(tmp_path, wire, footer, streaminfo, release): +def test_realsense_style_bag_is_read_exactly( + tmp_path, wire, footer, streaminfo, release +): path = tmp_path / "rs.bag" make_realsense_bag(path, footer=footer, wire=wire, streaminfo=streaminfo, n=3) diff --git a/tests/test_star_import.py b/tests/test_star_import.py index dacb7241..c48fd25e 100644 --- a/tests/test_star_import.py +++ b/tests/test_star_import.py @@ -13,7 +13,6 @@ class TestStarImport(unittest.TestCase): - def setUp(self): """Execute the star-import in an isolated namespace.""" self.ns = {} diff --git a/tests/test_visual_servo.py b/tests/test_visual_servo.py index 82caa25f..c9f178e4 100644 --- a/tests/test_visual_servo.py +++ b/tests/test_visual_servo.py @@ -3,7 +3,6 @@ Smoke tests for Visual Servo classes. """ - import unittest import numpy as np @@ -13,7 +12,6 @@ class TestPbvs(unittest.TestCase): - def test_run(self): camera = CentralCamera.Default( @@ -32,7 +30,6 @@ def test_run(self): class TestIbvs(unittest.TestCase): - def test_run(self): camera = CentralCamera.Default(