Utilisation de depth map
This commit is contained in:
1 parent
3ed0fa0987
commit
34984e96f7
14 files changed
+766
-54
No files matched your search
@@ -677,6 +677,192 @@ def iso_layers(field, levels=16, blur=0.0, min_area=0.0, tolerance=0.0,
|
||||
equalize)]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Numeros des planches
|
||||
#
|
||||
# Chaque piece d'une planche porte son numero, encadre, et chaque zone ou se
|
||||
# pose la planche suivante porte le numero de celle-ci. Les numeros sont
|
||||
# traces en segments droits, sans police : ils se gravent tels quels.
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
# Segments d'un chiffre dans une case de 0.5 x 1 : a haut, b droite haut,
|
||||
# c droite bas, d bas, e gauche bas, f gauche haut, g milieu.
|
||||
_SEGMENTS = {
|
||||
"a": ((0.0, 0.0), (0.5, 0.0)), "b": ((0.5, 0.0), (0.5, 0.5)),
|
||||
"c": ((0.5, 0.5), (0.5, 1.0)), "d": ((0.0, 1.0), (0.5, 1.0)),
|
||||
"e": ((0.0, 0.5), (0.0, 1.0)), "f": ((0.0, 0.0), (0.0, 0.5)),
|
||||
"g": ((0.0, 0.5), (0.5, 0.5)),
|
||||
}
|
||||
_DIGITS = {"0": "abcdef", "1": "bc", "2": "abged", "3": "abgcd", "4": "fgbc",
|
||||
"5": "afgcd", "6": "afgedc", "7": "abc", "8": "abcdefg", "9": "abcdfg"}
|
||||
_DIGIT_STEP = 0.8 # pas d'un chiffre au suivant, en hauteurs de chiffre
|
||||
_FRAME_MARGIN = 0.35 # marge du cadre autour du numero, idem
|
||||
|
||||
|
||||
def number_size(number, height, framed=False):
|
||||
"""Largeur et hauteur du numero trace par `number_lines`."""
|
||||
count = len(str(int(number)))
|
||||
width = height * (0.5 + _DIGIT_STEP * (count - 1))
|
||||
margin = 2 * _FRAME_MARGIN * height if framed else 0.0
|
||||
return width + margin, height + margin
|
||||
|
||||
|
||||
def number_lines(number, x, y, height, framed=False):
|
||||
"""Trace du numero centre en (x, y), chiffres hauts de `height`.
|
||||
|
||||
Renvoie une ligne `(closed, opened)` comme `contour_lines` : les segments
|
||||
des chiffres en lignes ouvertes, et le cadre (`framed`) en boucle fermee.
|
||||
"""
|
||||
text = str(int(number))
|
||||
width, _height = number_size(number, height)
|
||||
left, top = x - width / 2.0, y - height / 2.0
|
||||
opened = []
|
||||
for k, digit in enumerate(text):
|
||||
origin = np.array([left + k * _DIGIT_STEP * height, top])
|
||||
for name in _DIGITS[digit]:
|
||||
opened.append(origin + height * np.array(_SEGMENTS[name]))
|
||||
closed = []
|
||||
if framed:
|
||||
w, h = number_size(number, height, True)
|
||||
closed.append(np.array([(x - w / 2, y - h / 2), (x + w / 2, y - h / 2),
|
||||
(x + w / 2, y + h / 2), (x - w / 2, y + h / 2)]))
|
||||
return closed, opened
|
||||
|
||||
|
||||
def region_mask(rings, width, height, step):
|
||||
"""Grille de booleens : la region bornee par `rings` (regle pair-impair),
|
||||
echantillonnee tous les `step` echantillons. Renvoie `(mask, xs, ys)`,
|
||||
les abscisses et ordonnees des colonnes et des lignes de la grille."""
|
||||
xs = np.arange(step / 2.0, width - 1.0, step)
|
||||
ys = np.arange(step / 2.0, height - 1.0, step)
|
||||
mask = np.zeros((len(ys), len(xs)), dtype=bool)
|
||||
rings = [np.asarray(ring, dtype=float) for ring in rings if len(ring) >= 3]
|
||||
if not rings:
|
||||
return mask, xs, ys
|
||||
start = np.vstack(rings)
|
||||
end = np.vstack([np.roll(ring, -1, axis=0) for ring in rings])
|
||||
x0, y0, x1, y1 = start[:, 0], start[:, 1], end[:, 0], end[:, 1]
|
||||
for i, y in enumerate(ys):
|
||||
crossing = (y0 <= y) != (y1 <= y)
|
||||
if not crossing.any():
|
||||
continue
|
||||
a, b = y0[crossing], y1[crossing]
|
||||
at = x0[crossing] + (y - a) * (x1[crossing] - x0[crossing]) / (b - a)
|
||||
mask[i] = np.searchsorted(np.sort(at), xs) % 2 == 1
|
||||
return mask, xs, ys
|
||||
|
||||
|
||||
def mask_depth(mask):
|
||||
"""Pour chaque case du masque, sa distance au bord de la region, en
|
||||
cases (1 sur le bord, 0 dehors) : nombre d'erosions qu'elle supporte."""
|
||||
depth = np.zeros(mask.shape, dtype=int)
|
||||
current = np.pad(np.asarray(mask, dtype=bool), 1)
|
||||
while current.any():
|
||||
depth += current[1:-1, 1:-1]
|
||||
current[1:-1, 1:-1] = (current[1:-1, 1:-1] & current[:-2, 1:-1]
|
||||
& current[2:, 1:-1] & current[1:-1, :-2]
|
||||
& current[1:-1, 2:])
|
||||
return depth
|
||||
|
||||
|
||||
def mask_components(mask):
|
||||
"""Parties d'un seul tenant du masque (voisinage par les cotes) :
|
||||
tableau d'etiquettes, 0 hors du masque, puis 1, 2..., et leur nombre."""
|
||||
mask = np.asarray(mask, dtype=bool)
|
||||
if not mask.any():
|
||||
return np.zeros(mask.shape, dtype=int), 0
|
||||
# Chaque case part avec un numero a elle, puis le plus grand numero se
|
||||
# propage le long des lignes et des colonnes, dans les deux sens, jusqu'a
|
||||
# ce que plus rien ne bouge : toute une partie finit avec le meme numero.
|
||||
big = mask.size + 1
|
||||
labels = np.where(mask, np.arange(1, big, dtype=np.int64).reshape(mask.shape), 0)
|
||||
while True:
|
||||
before = labels
|
||||
for axis in (1, 0):
|
||||
for flip in (False, True):
|
||||
view = np.flip(labels, axis) if flip else labels
|
||||
inside = np.flip(mask, axis) if flip else mask
|
||||
# Numero de troncon : le maximum cumule ne passe pas d'un
|
||||
# troncon de cases au suivant.
|
||||
run = np.cumsum(~inside, axis=axis) * big
|
||||
view = np.where(inside, np.maximum.accumulate(view + run, axis=axis) - run, 0)
|
||||
labels = np.flip(view, axis) if flip else view
|
||||
if np.array_equal(labels, before):
|
||||
break
|
||||
_values, compact = np.unique(labels, return_inverse=True)
|
||||
compact = compact.reshape(mask.shape)
|
||||
if mask.all(): # pas de case a 0 : les etiquettes partent de 1
|
||||
compact = compact + 1
|
||||
return compact, int(compact.max())
|
||||
|
||||
|
||||
def _number_height(number, radius, largest, framed):
|
||||
"""Plus grande hauteur de chiffre, au plus `largest`, dont le numero
|
||||
tient dans un disque de rayon `radius`."""
|
||||
width, height = number_size(number, 1.0, framed)
|
||||
return min(largest, 2.0 * radius / float(np.hypot(width, height)))
|
||||
|
||||
|
||||
def board_labels(rings, following, number, width, height, largest, smallest,
|
||||
step=None):
|
||||
"""Emplacement des numeros a graver sur la planche `number`.
|
||||
|
||||
`rings` est le contour de la planche, `following` celui de la planche
|
||||
suivante de la pile (ou `None`). Renvoie `(own, next)`, deux listes de
|
||||
`(x, y, hauteur des chiffres)` en echantillons :
|
||||
- `next` : le numero de la planche suivante, au creux de chaque zone ou
|
||||
elle se pose ;
|
||||
- `own` : le numero de la planche, un par piece d'un seul tenant, a
|
||||
encadrer. Il se place de preference sous la planche suivante, a l'ecart
|
||||
du numero de celle-ci, pour etre cache une fois la pile collee ; sinon
|
||||
sur la partie qui reste visible.
|
||||
Les chiffres mesurent au plus `largest` ; une piece ou une zone trop
|
||||
etroite pour des chiffres de `smallest` ne recoit pas de numero.
|
||||
"""
|
||||
if step is None:
|
||||
step = max(1.0, max(width, height) / 200.0)
|
||||
region, xs, ys = region_mask(rings, width, height, step)
|
||||
taken = np.zeros(region.shape, dtype=bool)
|
||||
grid_y, grid_x = np.indices(region.shape)
|
||||
|
||||
def spots(mask, shown, framed):
|
||||
"""Un numero par partie de `mask`, au plus profond de celle-ci."""
|
||||
found = []
|
||||
depth = mask_depth(mask)
|
||||
labels, count = mask_components(mask)
|
||||
for label in range(1, count + 1):
|
||||
reach = np.where(labels == label, depth, 0)
|
||||
i, j = np.unravel_index(int(np.argmax(reach)), reach.shape)
|
||||
size = _number_height(shown, (reach[i, j] - 0.5) * step, largest, framed)
|
||||
if size < smallest:
|
||||
continue
|
||||
found.append((float(xs[j]), float(ys[i]), size, label))
|
||||
box = number_size(shown, size, framed)
|
||||
radius = 0.6 * float(np.hypot(*box)) / step + 1.0
|
||||
taken[(grid_x - j) ** 2 + (grid_y - i) ** 2 <= radius ** 2] = True
|
||||
return found, labels
|
||||
|
||||
covered = np.zeros(region.shape, dtype=bool)
|
||||
after = []
|
||||
if following:
|
||||
covered = region_mask(following, width, height, step)[0]
|
||||
after = [spot[:3] for spot in spots(covered, number + 1, False)[0]]
|
||||
|
||||
pieces, _count = mask_components(region)
|
||||
own, done = [], set()
|
||||
# D'abord sous la planche suivante (numero cache), puis a decouvert.
|
||||
for mask in (region & covered & ~taken, region & ~covered & ~taken):
|
||||
found, _labels = spots(mask, number, True)
|
||||
for x, y, size, _label in sorted(found, key=lambda spot: -spot[2]):
|
||||
j = int(np.argmin(np.abs(xs - x)))
|
||||
i = int(np.argmin(np.abs(ys - y)))
|
||||
piece = pieces[i, j]
|
||||
if piece and piece not in done:
|
||||
done.add(piece)
|
||||
own.append((x, y, size))
|
||||
return own, after
|
||||
|
||||
|
||||
def image_ring(width, height):
|
||||
"""Anneau du rectangle de l'image, en echantillons."""
|
||||
return np.array([(0.0, 0.0), (width - 1.0, 0.0),
|
||||
|
||||
Reference in new issue
Block a user