Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 9 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/machinevisiontoolbox/BagOfWords.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 0 additions & 4 deletions src/machinevisiontoolbox/BundleAdjust.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
16 changes: 11 additions & 5 deletions src/machinevisiontoolbox/Camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -1255,7 +1255,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(
Expand Down Expand Up @@ -2989,7 +2991,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)
Expand Down
10 changes: 8 additions & 2 deletions src/machinevisiontoolbox/ImageCore.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion src/machinevisiontoolbox/ImageIO.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/machinevisiontoolbox/ImagePointFeatures.py
Original file line number Diff line number Diff line change
Expand Up @@ -1583,7 +1583,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:
Expand Down
11 changes: 5 additions & 6 deletions src/machinevisiontoolbox/ImageProcessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -1332,12 +1330,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
Expand Down Expand Up @@ -1414,7 +1414,6 @@ def invert(self) -> Self:


if __name__ == "__main__":

pass

# tests = Path(__file__).parent.parent.parent / "tests"
Expand Down
8 changes: 2 additions & 6 deletions src/machinevisiontoolbox/ImageRegionFeatures.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
6 changes: 2 additions & 4 deletions src/machinevisiontoolbox/ImageSpatial.py
Original file line number Diff line number Diff line change
Expand Up @@ -725,8 +725,7 @@ def canny(
percentile: float = ...,
k: float = ...,
hist: Literal[False] = ...,
) -> Any:
...
) -> Any: ...

@overload
def canny(
Expand All @@ -738,8 +737,7 @@ def canny(
k: float = ...,
*,
hist: Literal[True],
) -> "tuple[Any, CannyHistogram]":
...
) -> "tuple[Any, CannyHistogram]": ...

def canny(
self,
Expand Down
22 changes: 18 additions & 4 deletions src/machinevisiontoolbox/ImageWholeFeatures.py
Original file line number Diff line number Diff line change
Expand Up @@ -1245,7 +1245,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

Expand Down Expand Up @@ -1317,7 +1319,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
Expand Down Expand Up @@ -1345,7 +1349,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,
Expand Down Expand Up @@ -1557,7 +1568,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:
Expand Down
4 changes: 3 additions & 1 deletion src/machinevisiontoolbox/Kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 0 additions & 1 deletion src/machinevisiontoolbox/PointCloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -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: "
Expand Down
9 changes: 4 additions & 5 deletions src/machinevisiontoolbox/Sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -3599,7 +3599,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:
Expand Down Expand Up @@ -3739,9 +3741,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:
Expand Down Expand Up @@ -3871,7 +3871,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:
Expand Down
4 changes: 3 additions & 1 deletion src/machinevisiontoolbox/VisualServo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
13 changes: 11 additions & 2 deletions src/machinevisiontoolbox/base/graphics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -980,7 +987,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

Expand Down
4 changes: 1 addition & 3 deletions src/machinevisiontoolbox/bin/imtool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading
Loading