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
22 changes: 14 additions & 8 deletions src/machinevisiontoolbox/ImagePointFeatures.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,11 @@ def gridify(self, nbins: int | tuple[int, int], nfeat: int) -> "BaseFeature2D":
.. warning:: Takes the first ``nfeat`` features in each grid cell, not the
``nfeat`` strongest. Sort the features by strength to achieve this.

.. versionchanged:: 2.5.0
The result keeps the descriptors and the scale, orientation and strength
of the features, and a feature at the right or bottom edge of the image
no longer raises ``IndexError``.

:seealso: :meth:`sort`
"""

Expand All @@ -323,21 +328,22 @@ def gridify(self, nbins: int | tuple[int, int], nfeat: int) -> "BaseFeature2D":
image = self._image
if image is None:
raise ValueError("no image associated with features")
binwidth = image.width // nw
binheight = image.height // nh

keep = []
keep: list[int] = []
bins = np.zeros((nh, nw), dtype="int")

for f in self:
ix = int(f.p[0].item() // binwidth)
iy = int(f.p[1].item() // binheight)
for i, f in enumerate(self):
# the last cell takes the pixels left over when the size is not a
# multiple of the number of cells
ix = min(int(f.p[0].item() * nw // image.width), nw - 1)
iy = min(int(f.p[1].item() * nh // image.height), nh - 1)

if bins[iy, ix] < nfeat:
keep.append(f)
keep.append(i)
bins[iy, ix] += 1

return self.__class__(keep)
# indexing keeps the descriptors and the flags, as slicing does
return self[keep]

def __add__(self, other: "BaseFeature2D | builtins.list | None") -> "BaseFeature2D":
"""
Expand Down
50 changes: 50 additions & 0 deletions tests/test_image_point_features_extra.py
Original file line number Diff line number Diff line change
Expand Up @@ -1150,3 +1150,53 @@
assert (f._has_scale, f._has_orient) == (False, False)
with pytest.raises(ValueError, match="no scale"):
f.scale


class TestGridify:

Check warning on line 1155 in tests/test_image_point_features_extra.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

tests/test_image_point_features_extra.py#L1155

class already defined line 258

Check warning on line 1155 in tests/test_image_point_features_extra.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

tests/test_image_point_features_extra.py#L1155

redefinition of unused 'TestGridify' from line 258 (F811)
@pytest.fixture
def orb(self):
return Image.Read("eiffel-1.png", mono=True).ORB(nfeat=500)

def test_result_has_keypoints_descriptors_and_flags(self, orb):
g = orb.gridify(4, 5)
assert 0 < len(g) < len(orb)
assert all(isinstance(k, cv2.KeyPoint) for k in g._kp)
assert g._descriptor.shape == (len(g), orb._descriptor.shape[1])
assert (g._has_scale, g._has_orient, g._has_strength) == (True, True, True)
assert g._feature_type == orb._feature_type
assert g._image is orb._image
assert len(g.scale) == len(g)

def test_features_keep_their_own_descriptors(self, orb):
g = orb.gridify(4, 5)
# each kept feature is one of the originals, with its own descriptor row
index = {tuple(k.pt): i for i, k in enumerate(orb._kp)}
for k, d in zip(g._kp, g._descriptor):
assert np.array_equal(d, orb._descriptor[index[tuple(k.pt)]])

def test_result_can_be_matched(self, orb):
g = orb.gridify(4, 5)
assert len(g.match(g)) == len(g)

def test_at_most_nfeat_per_cell(self, orb):
w, h = orb._image.width, orb._image.height
g = orb.gridify((4, 3), 2)
cells = {}
for k in g._kp:
c = (int(k.pt[0] * 4 // w), int(k.pt[1] * 3 // h))
cells[c] = cells.get(c, 0) + 1
assert max(cells.values()) <= 2

def test_features_at_the_far_edges(self):
# 1280 is not a multiple of 13, so the right edge is past the last cell
im = Image.Read("eiffel-1.png", mono=True)
kps = [cv2.KeyPoint(x, y, 7) for x, y in [(0, 0), (1279, 850), (1279, 0)]]
f = BaseFeature2D()
f._kp = kps
f._descriptor = np.zeros((3, 32), dtype=np.uint8)
f._image = im
assert len(f.gridify(13, 5)) == 3

def test_no_image(self):
with pytest.raises(ValueError, match="no image"):
BaseFeature2D().gridify(4, 5)
Loading