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
7 changes: 5 additions & 2 deletions src/machinevisiontoolbox/ImageSpatial.py
Original file line number Diff line number Diff line change
Expand Up @@ -1551,8 +1551,11 @@ def similarity(self, T: Any, metric: str = "zncc") -> Any:
im = self._A
T_im = T._A
if metric[0] == "z":
T_im -= np.mean(T_im) # remove offset from template
im = im - np.mean(im) # remove offset from image
# remove the offset from the template and from the image, into new
# float32 arrays: the template belongs to the caller, and an 8-bit
# image cannot be changed in place by a float mean
T_im = T_im.astype(np.float32) - np.mean(T_im, dtype=np.float32)
im = im.astype(np.float32) - np.mean(im, dtype=np.float32)

try:
out = cv2.matchTemplate(image=im, templ=T_im, method=metricdict[metric])
Expand Down
26 changes: 15 additions & 11 deletions tests/test_image_spatial_extra.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,25 +511,29 @@ def test_template_is_unchanged_by_ncc(self, scene):
image.similarity(template, "ncc")
nt.assert_array_equal(template.array, before)

@pytest.mark.xfail(
strict=True,
reason="the z metrics subtract the template mean in place, which "
"changes the caller's template",
)
def test_template_is_unchanged_by_zncc(self, scene):
image, template = scene
before = template.array.copy()
image.similarity(template, "zncc")
nt.assert_array_equal(template.array, before)

@pytest.mark.xfail(
strict=True,
raises=Exception,
reason="the in-place mean subtraction fails on a uint8 image",
)
def test_zncc_on_uint8_images(self):
rng = np.random.default_rng(1)
arr = rng.integers(0, 255, (20, 20), dtype=np.uint8)
image = Image(arr)
out = image.similarity(Image(arr[5:8, 5:8].copy()), "zncc")
template = Image(arr[5:8, 5:8].copy())
out = image.similarity(template, "zncc")
assert out.shape == (18, 18)
v, u = np.unravel_index(np.argmax(out.array), out.shape)
assert (u, v) == (5, 5)
assert out.array[v, u] == pytest.approx(1.0, abs=1e-3)
# neither the image nor the template is changed
nt.assert_array_equal(image.array, arr)
nt.assert_array_equal(template.array, arr[5:8, 5:8])

def test_zssd_on_uint8_images(self):
rng = np.random.default_rng(2)
arr = rng.integers(0, 255, (20, 20), dtype=np.uint8)
out = Image(arr).similarity(Image(arr[5:8, 5:8].copy()), "zssd")
v, u = np.unravel_index(np.argmin(out.array), out.shape)
assert (u, v) == (5, 5)
Loading