Fix big for peaks of equal height
authorStefan Huber <shuber@sthu.org>
Wed, 17 Apr 2024 14:27:09 +0000 (16:27 +0200)
committerStefan Huber <shuber@sthu.org>
Wed, 17 Apr 2024 14:27:09 +0000 (16:27 +0200)
The order of pixels on the pixel value was ambiguous and possibly
inconsistent with the order of neighborhood pixels. Make it a
unambiguous total order.

imagepers.py

index 3d03475e998804c6839a70beec25460c4d783e4f..a4cf21e79456fe3b819804e47a8aeed629785c68 100644 (file)
@@ -33,9 +33,13 @@ def iter_neighbors(p, w, h):
 def persistence(im):
     h, w = im.shape
 
-    # Get indices orderd by value from high to low
+    # Get indices orderd by value from high to low. As a tie-breaker, we use
+    # (value, index) as key.
     indices = [(i, j) for i in range(h) for j in range(w)]
-    indices.sort(key=lambda p: get(im, p), reverse=True)
+    # We add p as a secondary key to have an unambiguous total order below when
+    # we enumerate neighboring cells of cells and consistency regarding
+    # "oldest" component.
+    indices.sort(key=lambda p: (get(im, p), p), reverse=True)
 
     # Maintains the growing sets
     uf = union_find.UnionFind()
@@ -49,6 +53,9 @@ def persistence(im):
     for i, p in enumerate(indices):
         v = get(im, p)
         ni = [uf[q] for q in iter_neighbors(p, w, h) if q in uf]
+        # Sort by (value, index) as key. Note that this is the same sorting
+        # order as for indices. Otherwise we have an inconsistence notion of
+        # the "older" component!
         nc = sorted([(get_comp_birth(q), q) for q in set(ni)], reverse=True)
 
         if i == 0:
@@ -63,7 +70,7 @@ def persistence(im):
             # Merge all others with oldp
             for bl, q in nc[1:]:
                 if uf[q] not in groups0:
-                    #print(i, ": Merge", uf[q], "with", oldp, "via", p)
+                    # print(i, ": Merge", uf[q], "with", oldp, "via", p)
                     groups0[uf[q]] = (bl, bl-v, p)
                 uf.union(oldp, q)