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
31 changes: 19 additions & 12 deletions src/machinevisiontoolbox/Camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,11 @@ def __init__(
self._name = camtype
else:
if not isinstance(name, str):
raise TypeError(name, "name must be a string")
raise TypeError(f"name must be a string, got {name!r}")
self._name = name

if not isinstance(camtype, str):
raise TypeError(camtype, "camtype must be a string")
raise TypeError(f"camtype must be a string, got {camtype!r}")
self._camtype = camtype

if imagesize is None:
Expand Down Expand Up @@ -134,7 +134,7 @@ def __init__(
self._rhou = rho[0]
self._rhov = rho[1]
else:
raise ValueError(rho, "rho must be a 1- or 2-element vector")
raise ValueError(f"rho must be a 1- or 2-element vector, got {rho!r}")

if noise is not None:
self._noise = noise
Expand Down Expand Up @@ -250,7 +250,7 @@ def name(self, newname: str) -> None:
if isinstance(newname, str):
self._name = newname
else:
raise TypeError(newname, "name must be a string")
raise TypeError(f"name must be a string, got {newname!r}")

@property
def camtype(self) -> str:
Expand Down Expand Up @@ -283,7 +283,7 @@ def camtype(self, newcamtype: str) -> None:
if isinstance(newcamtype, str):
self._camtype = newcamtype
else:
raise TypeError(newcamtype, "camtype must be a string")
raise TypeError(f"camtype must be a string, got {newcamtype!r}")

@property
def imagesize(self) -> np.ndarray | None:
Expand Down Expand Up @@ -333,7 +333,9 @@ def imagesize(self, npix: ArrayLike) -> None:
# ignore color dimension in case it is given
self._imagesize = npix[:2]
else:
raise ValueError(npix, "imagesize must be a 1- or 2-element vector")
raise ValueError(
f"imagesize must be a 1- or 2-element vector, got {npix!r}"
)
if self._pp is None:
assert self._imagesize is not None
self._pp = self._imagesize / 2
Expand Down Expand Up @@ -460,7 +462,7 @@ def pp(self, pp: ArrayLike) -> None:
elif len(pp) == 2:
self._pp = pp
else:
raise ValueError(pp, "pp must be a 1- or 2-element vector")
raise ValueError(f"pp must be a 1- or 2-element vector, got {pp!r}")

@property
def u0(self) -> float:
Expand Down Expand Up @@ -2048,7 +2050,7 @@ def f(self, f: ArrayLike) -> None:
self._fu = f[0]
self._fv = f[1]
else:
raise ValueError(f, "f must be a 1- or 2-element vector")
raise ValueError(f"f must be a 1- or 2-element vector, got {f!r}")

@property
def fpix(self) -> np.ndarray:
Expand Down Expand Up @@ -2466,11 +2468,11 @@ def H(self, T: SE3, n: ArrayLike, d: float) -> np.ndarray:
:seealso: :meth:`points2H` :meth:`decomposeH`
"""
if d < 0:
raise ValueError(d, "plane distance d must be > 0")
raise ValueError(f"plane distance d must be > 0, got {d!r}")

n = _getvector(n)
if n[2] < 0:
raise ValueError(n, "normal must be away from camera (n[2] >= 0)")
raise ValueError(f"normal must be away from camera (n[2] >= 0), got {n!r}")

# T transform view 1 to view 2
T = SE3(T).inv()
Expand Down Expand Up @@ -2699,7 +2701,9 @@ def F(self, other: CentralCamera | SE3) -> np.ndarray:
return np.linalg.inv(K2).T @ E @ np.linalg.inv(K1)

else:
raise ValueError("bad type")
raise ValueError(
f"other must be a CentralCamera or SE3, got {type(other).__name__}"
)

@staticmethod
def points2F(
Expand Down Expand Up @@ -2916,7 +2920,10 @@ def E(self, other: CentralCamera | SE3 | np.ndarray) -> np.ndarray:
T21 = SE3(other.inv())

else:
raise ValueError("bad type")
raise ValueError(
"other must be a CentralCamera, SE3 or a 3x3 fundamental matrix, "
f"got {type(other).__name__}"
)

return smb.skew(T21.t) @ T21.R

Expand Down
2 changes: 1 addition & 1 deletion src/machinevisiontoolbox/ImageColor.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ def colorize(
else:
color_arr = argcheck.getvector(color).astype(self.dtype)
if self.iscolor:
raise ValueError(self._A, "Image must be greyscale")
raise ValueError(f"image must be greyscale, got {self.nplanes} planes")

out = self._A[..., np.newaxis] * color_arr

Expand Down
6 changes: 4 additions & 2 deletions src/machinevisiontoolbox/ImageCore.py
Original file line number Diff line number Diff line change
Expand Up @@ -2854,7 +2854,7 @@ def __getitem__(
return self.__class__(out, colororder=colororder)

else:
raise ValueError("invalid slice")
raise ValueError(f"invalid index or slice {keys!r}")

@staticmethod
def _lenkey(key: int | slice, max: int) -> int:
Expand Down Expand Up @@ -3879,7 +3879,9 @@ def _binop(left, right, op, logical=False) -> "Image":
np.stack(out, axis=2), colororder=right.colororder
)
else:
raise ValueError("planes mismatch")
raise ValueError(
f"images have different numbers of planes, {left.nplanes} and {right.nplanes}"
)
else:
# right is a scalar or numpy array
return left.__class__(op(left._A, right), colororder=left.colororder)
Expand Down
4 changes: 3 additions & 1 deletion src/machinevisiontoolbox/ImageFiducials.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,9 @@ def estimatePose(
)

if not retval:
raise ValueError("solvePnP failed")
raise ValueError(
f"solvePnP failed to find a pose from {len(objPoints)} points"
)
# print(f"rotation: {rvec.T}")
# print(f"translation: {tvec.T}")
self._tvec = tvec
Expand Down
8 changes: 4 additions & 4 deletions src/machinevisiontoolbox/ImageMorph.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def erode(
if not isinstance(n, int):
n = int(n)
if n <= 0:
raise ValueError(n, "n must be greater than 0")
raise ValueError(f"n must be greater than 0, got {n!r}")

if self.isbool:
img_array = self.array_as("uint8") # convert to uint8 for opencv
Expand Down Expand Up @@ -213,7 +213,7 @@ def dilate(
if not isinstance(n, int):
n = int(n)
if n <= 0:
raise ValueError(n, "n must be greater than 0")
raise ValueError(f"n must be greater than 0, got {n!r}")

if self.isbool:
img_array = self.array_as("uint8") # convert to uint8 for opencv
Expand Down Expand Up @@ -303,12 +303,12 @@ def morph(
# can also be a scalar

if not isinstance(op, str):
raise TypeError(op, "oper must be a string")
raise TypeError(f"oper must be a string, got {op!r}")

if not isinstance(n, int):
n = int(n)
if n <= 0:
raise ValueError(n, "n must be greater than 0")
raise ValueError(f"n must be greater than 0, got {n!r}")

if self.isbool:
img_array = self.array_as("uint8") # convert to uint8 for opencv
Expand Down
12 changes: 8 additions & 4 deletions src/machinevisiontoolbox/ImagePointFeatures.py
Original file line number Diff line number Diff line change
Expand Up @@ -1424,9 +1424,11 @@ def __getitem__(self, i) -> "FeatureMatch":
if self._inliers is not None:
inliers = [self._inliers[k] for k in i]
else:
raise ValueError("bad index dtype")
raise ValueError(f"index array must be integer or bool, got {i.dtype}")
else:
raise ValueError("bad index")
raise ValueError(
f"index must be an int, slice, sequence or array, got {type(i).__name__}"
)
return FeatureMatch(matches, self._kp1, self._kp2, inliers)

def __len__(self) -> int:
Expand Down Expand Up @@ -2196,7 +2198,7 @@ def _image2feature(
for k in kp:
k.class_id = id
else:
raise ValueError("bad id")
raise ValueError(f"id must be 'image', 'index' or an int, got {id!r}")

# do sorting in here

Expand Down Expand Up @@ -2504,7 +2506,9 @@ def ComboFeature(
# call it
kp = detector(self._A, **det_opts)
else:
raise ValueError("unknown detector")
raise ValueError(
f"detector must be a callable or one of {list(detectors)}, got {detector!r}"
)

raise NotImplementedError("ComboFeature is a work in progress")

Expand Down
16 changes: 10 additions & 6 deletions src/machinevisiontoolbox/ImageProcessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -543,12 +543,12 @@ def threshold(
elif auto == "percentile":
autothresh = np.percentile(arr, p)
else:
raise ValueError(auto, "unknown automatic threshold method")
raise ValueError(f"unknown automatic threshold method, got {auto!r}")

threshold = autothresh

if not argcheck.isscalar(threshold):
raise ValueError(threshold, "threshold must be a scalar")
raise ValueError(f"threshold must be a scalar, got {threshold!r}")

if mode == "binary":
imt = np.where(arr > threshold, true_value, false_value).astype(
Expand All @@ -565,7 +565,7 @@ def threshold(
elif mode in ("/tozero", "tozero_inv"):
imt = np.where(arr <= threshold, arr, 0)
else:
raise ValueError(mode, "unknown threshold method")
raise ValueError(f"unknown threshold method, got {mode!r}")

if mode in ("binary", "binary_inv"):
out = self.__class__(imt)
Expand Down Expand Up @@ -639,7 +639,7 @@ def threshold_interactive(

mode = mode.lower()
if mode not in ("binary", "tozero"):
raise ValueError(mode, "unknown threshold mode")
raise ValueError(f"unknown threshold mode, got {mode!r}")

img = self._A
img_min = float(np.min(img))
Expand Down Expand Up @@ -1262,9 +1262,13 @@ def paste(
top = int(top)

if (top + ph) > ch:
raise ValueError(ph, "pattern falls off bottom edge")
raise ValueError(
f"pattern falls off bottom edge: top {top} + height {ph} > image height {ch}"
)
if (left + pw) > cw:
raise ValueError(pw, "pattern falls off right edge")
raise ValueError(
f"pattern falls off right edge: left {left} + width {pw} > image width {cw}"
)

npc = pattern.nplanes
nc = self.nplanes
Expand Down
8 changes: 4 additions & 4 deletions src/machinevisiontoolbox/ImageReshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ def decimate(self, m: int = 2, sigma: float | None = None) -> Self:
:seealso: :meth:`replicate` :meth:`scale`
"""
if (m - np.ceil(m)) != 0:
raise ValueError(m, "decimation factor m must be an integer")
raise ValueError(f"decimation factor m must be an integer, got {m!r}")

if sigma is None:
sigma = m / 2
Expand Down Expand Up @@ -779,7 +779,7 @@ def samesize(self, image2: Any, bias: float = 0.5) -> Self:
"""
# check inputs
if bias < 0 or bias > 1:
raise ValueError(bias, "bias must be in range [0, 1]")
raise ValueError(f"bias must be in range [0, 1], got {bias!r}")

im = self._A

Expand Down Expand Up @@ -851,7 +851,7 @@ def scale(
"""
# check inputs
if not smb.isscalar(sfactor):
raise TypeError(sfactor, "factor is not a scalar")
raise TypeError(f"factor is not a scalar, got {sfactor!r}")

interp: int
if interpolation is None:
Expand Down Expand Up @@ -924,7 +924,7 @@ def rotate(self, angle: float, centre=None, center=None) -> Self:
# using-opencv/

if not smb.isscalar(angle):
raise ValueError(angle, "angle is not a valid scalar")
raise ValueError(f"angle is not a valid scalar, got {angle!r}")

if center is not None and centre is None:
centre = center
Expand Down
27 changes: 15 additions & 12 deletions src/machinevisiontoolbox/ImageSpatial.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,9 @@ def _bordertype_cv(
try:
return border_opt[border]
except KeyError:
raise ValueError(border, "border is not a valid option")
raise ValueError(
f"border must be one of {list(border_opt)}, got {border!r}"
)

@staticmethod
def _bordertype_sp(
Expand Down Expand Up @@ -122,7 +124,9 @@ def _bordertype_sp(
try:
return border_opt[border]
except KeyError:
raise ValueError(border, "border is not a valid option")
raise ValueError(
f"border must be one of {list(border_opt)}, got {border!r}"
)

def smooth(
self,
Expand Down Expand Up @@ -175,7 +179,7 @@ def smooth(
"""

if not argcheck.isscalar(sigma):
raise ValueError(sigma, "sigma must be a scalar")
raise ValueError(f"sigma must be a scalar, got {sigma!r}")

# make the smoothing kernel
K = Kernel.Gauss(sigma, h)
Expand Down Expand Up @@ -288,7 +292,7 @@ def convolve(
modeopt = ["valid", "same", "full"]

if mode not in modeopt:
raise ValueError(mode, "opt is not a valid option")
raise ValueError(f"mode must be one of {modeopt}, got {mode!r}")

self._opencv_type_check(
self._A, "multiple-channel", "CV_8U", "CV_16U", "CV_16S", "CV_32F", "CV_64F"
Expand Down Expand Up @@ -514,7 +518,7 @@ def window(
raise ValueError("single channel images only")

if not callable(func):
raise TypeError(func, "func not callable")
raise TypeError(f"func not callable, got {func!r}")

if h is not None and se is None:
w = 2 * h + 1
Expand Down Expand Up @@ -679,15 +683,14 @@ def pyramid(
)

if not argcheck.isscalar(sigma):
raise ValueError(sigma, "sigma must be a scalar")
raise ValueError(f"sigma must be a scalar, got {sigma!r}")

if N is None:
N = max(im.shape)
else:
if (not argcheck.isscalar(N)) and (N >= 0) and (N <= max(im.shape)):
raise ValueError(
N,
"N must be a scalar and 0 <= N <= max(im.shape)",
f"N must be a scalar and 0 <= N <= max(im.shape), got {N!r}",
)

# TODO options to accept different border types,
Expand Down Expand Up @@ -951,9 +954,9 @@ def rankfilter(
elif rank in ("med", "median"):
rank = n // 2
else:
raise ValueError(rank, "unknown rank name")
raise ValueError(f"unknown rank name, got {rank!r}")
elif not isinstance(rank, int):
raise TypeError(rank, "rank must be int or str")
raise TypeError(f"rank must be int or str, got {rank!r}")

if rank < 0:
raise ValueError("rank must be >= 0")
Expand Down Expand Up @@ -1166,7 +1169,7 @@ def labels_binary(
:meth:`labels_MSER`
"""
if not (connectivity in [4, 8]):
raise ValueError(connectivity, "connectivity must be 4 or 8")
raise ValueError(f"connectivity must be 4 or 8, got {connectivity!r}")

self._opencv_type_check(self._A, "single-channel", "CV_8U")
# make labels uint32s, unique and never recycled?
Expand All @@ -1176,7 +1179,7 @@ def labels_binary(
elif ltype == "uint16":
cvtype = cv2.CV_16U
else:
raise TypeError(ltype, "ltype must be either int32 or uint16")
raise TypeError(f"ltype must be either int32 or uint16, got {ltype!r}")

retval, labels = cv2.connectedComponents(
image=self.array_as("uint8"), connectivity=connectivity, ltype=cvtype
Expand Down
Loading