Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016S8V7WxoS7YRoM34BVBkeo
540 lines
21 KiB
Python
540 lines
21 KiB
Python
# coding=utf-8
|
|
"""
|
|
Noyau geometrique de l'extension « Board photo », sans dependance a inkex.
|
|
|
|
Testable avec pytest seul et reutilisable hors Inkscape (scripts, schema
|
|
des parametres). Seule dependance : numpy, fourni avec Inkscape 1.x.
|
|
|
|
Conventions :
|
|
- toutes les longueurs sont en millimetres ;
|
|
- repere SVG : origine en haut a gauche de la zone de travail, y vers le bas ;
|
|
- repere laser : origine en bas a gauche de la zone de travail, y vers le haut
|
|
(conversion par `laser_to_svg` / `svg_to_laser`, seul endroit ou l'on
|
|
retourne l'axe y) ;
|
|
- coordonnees image « continues » : le pixel (ligne r, colonne c) couvre le
|
|
carre [c, c+1] x [r, r+1], son centre est donc en (c + 0.5, r + 0.5) ;
|
|
- un contour (`rings`) est une liste d'anneaux, chaque anneau etant une liste
|
|
de points (x, y) fermee implicitement ; les trous suivent la regle pair-impair ;
|
|
- les 4 reperes de calibration sont toujours ranges dans l'ordre
|
|
haut-gauche, haut-droite, bas-droite, bas-gauche (repere SVG) ; le repere
|
|
« origine » (deux pastilles) est celui du bas-gauche, a l'origine laser.
|
|
"""
|
|
|
|
import math
|
|
|
|
import numpy as np
|
|
|
|
# Indices des reperes dans l'ordre standard.
|
|
TOP_LEFT, TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT = range(4)
|
|
ORIGIN_MARKER = BOTTOM_LEFT
|
|
|
|
# Geometrie d'un repere, en fraction du cote du carre.
|
|
DOT_DIAMETER = 0.30 # pastille unique des reperes ordinaires
|
|
ORIGIN_DOT_DIAMETER = 0.25 # deux pastilles du repere origine
|
|
ORIGIN_DOT_OFFSET = 0.18 # decalage de chaque pastille sur la diagonale
|
|
|
|
|
|
def parse_color(value, default=("#b3b3b3", 1.0)):
|
|
"""Couleur Inkscape (entier RGBA decimal ou 0x..., ou #rrggbb[aa]).
|
|
|
|
Renvoie (couleur CSS #rrggbb, opacite entre 0 et 1). Le parametre
|
|
« color » d'Inkscape arrive sous forme d'entier RGBA ; on le decode
|
|
nous-memes pour ne pas dependre de l'API couleur d'inkex, qui a change
|
|
entre les versions 1.x.
|
|
"""
|
|
text = str(value).strip()
|
|
try:
|
|
if text.startswith("#"):
|
|
digits = text[1:]
|
|
if len(digits) == 3:
|
|
digits = "".join(c * 2 for c in digits)
|
|
if len(digits) == 6:
|
|
digits += "ff"
|
|
if len(digits) != 8:
|
|
return default
|
|
number = int(digits, 16)
|
|
else:
|
|
number = int(text, 0)
|
|
except ValueError:
|
|
return default
|
|
number &= 0xFFFFFFFF
|
|
red, green, blue = (number >> 24) & 255, (number >> 16) & 255, (number >> 8) & 255
|
|
alpha = (number & 255) / 255.0
|
|
return "#{:02x}{:02x}{:02x}".format(red, green, blue), round(alpha, 4)
|
|
|
|
|
|
def polylines_to_d(polylines, precision=4, closed=False):
|
|
"""Donnees `d` d'un chemin SVG : une polyligne par sous-chemin."""
|
|
fmt = "{:.%df},{:.%df}" % (precision, precision)
|
|
parts = []
|
|
for polyline in polylines:
|
|
if len(polyline) < 2:
|
|
continue
|
|
parts.append("M " + fmt.format(*polyline[0]))
|
|
parts.extend("L " + fmt.format(*point) for point in polyline[1:])
|
|
if closed:
|
|
parts.append("Z")
|
|
return " ".join(parts)
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Reperes laser / SVG et disposition des reperes de calibration
|
|
# --------------------------------------------------------------------------
|
|
|
|
def laser_to_svg(point, height):
|
|
"""Point du repere laser (y vers le haut) -> repere SVG (y vers le bas)."""
|
|
return float(point[0]), float(height) - float(point[1])
|
|
|
|
|
|
def svg_to_laser(point, height):
|
|
"""Point du repere SVG -> repere laser ; la conversion est son propre inverse."""
|
|
return laser_to_svg(point, height)
|
|
|
|
|
|
def marker_layout(height, origin_x, origin_y, spacing_x, spacing_y):
|
|
"""Centres des 4 reperes en repere SVG, ordre HG, HD, BD, BG.
|
|
|
|
(origin_x, origin_y) est le centre du repere origine en repere laser,
|
|
(spacing_x, spacing_y) l'ecart entre centres de reperes.
|
|
"""
|
|
laser = [(origin_x, origin_y + spacing_y),
|
|
(origin_x + spacing_x, origin_y + spacing_y),
|
|
(origin_x + spacing_x, origin_y),
|
|
(origin_x, origin_y)]
|
|
return [laser_to_svg(p, height) for p in laser]
|
|
|
|
|
|
PHOTO_MARGIN = 1.5 # marge autour des reperes, en tailles de repere
|
|
|
|
|
|
def photo_extent(width, height, origin_x, origin_y, spacing_x, spacing_y, size,
|
|
resolution):
|
|
"""Rectangle (x0, y0, x1, y1) en mm, repere SVG, couvert par la photo redressee.
|
|
|
|
La zone de travail, agrandie pour montrer les reperes en entier (avec leur
|
|
zone claire) quand ils sont colles autour. Bornes alignees sur la grille
|
|
des pixels (multiples de 1 / resolution) : la zone de travail tombe sur
|
|
des pixels entiers de l'image.
|
|
"""
|
|
centers = marker_layout(height, origin_x, origin_y, spacing_x, spacing_y)
|
|
reach = PHOTO_MARGIN * size
|
|
xs = [c[0] for c in centers]
|
|
ys = [c[1] for c in centers]
|
|
x0, x1 = min(0.0, min(xs) - reach), max(float(width), max(xs) + reach)
|
|
y0, y1 = min(0.0, min(ys) - reach), max(float(height), max(ys) + reach)
|
|
res = float(resolution)
|
|
return (math.floor(x0 * res + 1e-9) / res, math.floor(y0 * res + 1e-9) / res,
|
|
math.ceil(x1 * res - 1e-9) / res, math.ceil(y1 * res - 1e-9) / res)
|
|
|
|
|
|
def layout_problems(width, height, origin_x, origin_y, spacing_x, spacing_y, size,
|
|
reach=None):
|
|
"""Liste des defauts de disposition (vide si les reperes tiennent dans la zone).
|
|
|
|
`reach` : demi-emprise autour de chaque centre qui doit tenir dans la zone
|
|
(par defaut le demi-cote du repere ; `guide_reach` pour les gabarits).
|
|
"""
|
|
problems = []
|
|
if min(width, height, spacing_x, spacing_y, size) <= 0:
|
|
problems.append("non_positive")
|
|
return problems
|
|
half = size / 2.0 if reach is None else reach
|
|
if (origin_x - half < 0 or origin_y - half < 0
|
|
or origin_x + spacing_x + half > width
|
|
or origin_y + spacing_y + half > height):
|
|
problems.append("outside")
|
|
if spacing_x < 2 * size or spacing_y < 2 * size:
|
|
problems.append("too_close")
|
|
return problems
|
|
|
|
|
|
def circle_ring(center, radius, segments=72):
|
|
"""Polygone regulier approchant un cercle (sens trigonometrique ecran)."""
|
|
cx, cy = center
|
|
return [(cx + radius * math.cos(2 * math.pi * k / segments),
|
|
cy + radius * math.sin(2 * math.pi * k / segments))
|
|
for k in range(segments)]
|
|
|
|
|
|
def marker_rings(center, size, origin=False):
|
|
"""Anneaux d'un repere : carre plein + pastille(s) claire(s) (pair-impair).
|
|
|
|
Le repere ordinaire porte une pastille centrale ; le repere origine en
|
|
porte deux sur la diagonale, ce qui permet de retrouver l'orientation
|
|
de la photo.
|
|
"""
|
|
cx, cy = center
|
|
half = size / 2.0
|
|
square = [(cx - half, cy - half), (cx + half, cy - half),
|
|
(cx + half, cy + half), (cx - half, cy + half)]
|
|
if origin:
|
|
radius = ORIGIN_DOT_DIAMETER * size / 2.0
|
|
offset = ORIGIN_DOT_OFFSET * size
|
|
dots = [circle_ring((cx - offset, cy - offset), radius),
|
|
circle_ring((cx + offset, cy + offset), radius)]
|
|
else:
|
|
dots = [circle_ring((cx, cy), DOT_DIAMETER * size / 2.0)]
|
|
return [square] + dots
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Reperes imprimes : feuille A4 a decouper et gabarits de pose
|
|
# --------------------------------------------------------------------------
|
|
|
|
A4 = (210.0, 297.0)
|
|
PIECE_FACTOR = 2.0 # cote d'une piece decoupee / cote du repere (zone claire)
|
|
TICK_LENGTH = 0.15 # longueur des traits d'alignement, en fraction du repere
|
|
|
|
|
|
def piece_side(size):
|
|
"""Cote de la piece de papier a decouper autour d'un repere."""
|
|
return PIECE_FACTOR * size
|
|
|
|
|
|
def sheet_layout(size, page=A4, margin=12.0, header=38.0, footer=22.0, gap=14.0):
|
|
"""Centres des 4 pieces sur une feuille, ordre HG, HD, BD, BG ; None si trop grand.
|
|
|
|
Grille 2 x 2 si elle tient (meme disposition que sur la surface : le
|
|
repere origine en bas a gauche), sinon une colonne. `gap` separe les
|
|
pieces et laisse la place d'une legende sous chacune.
|
|
"""
|
|
side = piece_side(size)
|
|
width = page[0] - 2 * margin
|
|
height = page[1] - 2 * margin - header - footer
|
|
if size <= 0:
|
|
return None
|
|
for columns in (2, 1):
|
|
rows = 4 // columns
|
|
grid_w = columns * side + (columns - 1) * gap
|
|
grid_h = rows * side + rows * gap
|
|
if grid_w <= width and grid_h <= height:
|
|
break
|
|
else:
|
|
return None
|
|
x0 = (page[0] - grid_w) / 2.0 + side / 2.0
|
|
y0 = margin + header + side / 2.0
|
|
pitch = side + gap
|
|
if columns == 2:
|
|
cells = [(0, 0), (1, 0), (1, 1), (0, 1)]
|
|
else:
|
|
cells = [(0, 0), (0, 1), (0, 2), (0, 3)]
|
|
return [(x0 + c * pitch, y0 + r * pitch) for c, r in cells]
|
|
|
|
|
|
def corner_layout(width, height, size):
|
|
"""Reperes colles autour de la zone de travail, le coin interieur de chaque
|
|
piece de papier touchant un angle de la zone (nid d'abeille).
|
|
|
|
Le centre de chaque repere est a une demi-piece (= taille du repere) de
|
|
l'angle, en X et en Y. Renvoie (origin_x, origin_y, spacing_x, spacing_y),
|
|
en mm, repere laser (origine a l'angle bas gauche de la zone).
|
|
"""
|
|
half = piece_side(size) / 2.0
|
|
return -half, -half, float(width) + 2 * half, float(height) + 2 * half
|
|
|
|
|
|
def piece_ticks(center, size):
|
|
"""Traits d'alignement au milieu de chaque bord de la piece, vers le centre.
|
|
|
|
Ils se posent sur la croix du gabarit grave : le centre du repere tombe
|
|
alors exactement sur la position attendue.
|
|
"""
|
|
cx, cy = center
|
|
half = piece_side(size) / 2.0
|
|
inner = half - TICK_LENGTH * size
|
|
return [[(cx - half, cy), (cx - inner, cy)], [(cx + inner, cy), (cx + half, cy)],
|
|
[(cx, cy - half), (cx, cy - inner)], [(cx, cy + inner), (cx, cy + half)]]
|
|
|
|
|
|
def piece_outline(center, size):
|
|
"""Contour ferme de la piece (ligne de decoupe, ou gabarit de pose)."""
|
|
cx, cy = center
|
|
half = piece_side(size) / 2.0
|
|
ring = [(cx - half, cy - half), (cx + half, cy - half),
|
|
(cx + half, cy + half), (cx - half, cy + half)]
|
|
return ring + [ring[0]]
|
|
|
|
|
|
def guide_reach(size):
|
|
"""Demi-emprise d'un gabarit de pose : piece + croix qui depasse de size / 2."""
|
|
return piece_side(size) / 2.0 + size / 2.0
|
|
|
|
|
|
def guide_lines(center, size, overshoot=None):
|
|
"""Gabarit de pose : contour de la piece et croix qui depasse de chaque cote."""
|
|
cx, cy = center
|
|
half = piece_side(size) / 2.0
|
|
reach = half + (size / 2.0 if overshoot is None else overshoot)
|
|
return [piece_outline(center, size),
|
|
[(cx - reach, cy), (cx - half, cy)], [(cx + half, cy), (cx + reach, cy)],
|
|
[(cx, cy - reach), (cx, cy - half)], [(cx, cy + half), (cx, cy + reach)]]
|
|
|
|
|
|
def scale_bar(start, length=100.0, step=10.0, tick=3.0, vertical=False):
|
|
"""Barre de controle d'impression : trait de `length` mm gradue tous les `step`.
|
|
|
|
Horizontale, graduations vers le haut ; verticale (vers le bas depuis
|
|
`start`), graduations vers la gauche.
|
|
"""
|
|
x0, y0 = start
|
|
count = int(round(length / step))
|
|
if vertical:
|
|
lines = [[(x0, y0), (x0, y0 + length)]]
|
|
else:
|
|
lines = [[(x0, y0), (x0 + length, y0)]]
|
|
for k in range(count + 1):
|
|
h = tick * (1.6 if k in (0, count) else 1.0)
|
|
if vertical:
|
|
y = y0 + k * step
|
|
lines.append([(x0, y), (x0 - h, y)])
|
|
else:
|
|
x = x0 + k * step
|
|
lines.append([(x, y0), (x, y0 - h)])
|
|
return lines
|
|
|
|
|
|
def print_correction(measured_x, measured_y, nominal=100.0):
|
|
"""Facteurs d'agrandissement qui compensent une imprimante qui reduit.
|
|
|
|
Une barre de `nominal` mm mesuree `measured` mm apres impression : on
|
|
dessine `nominal / measured` fois plus grand pour qu'elle ressorte juste.
|
|
"""
|
|
return nominal / float(measured_x), nominal / float(measured_y)
|
|
|
|
|
|
def stretch_rings(rings, fx, fy, center):
|
|
"""Etire les anneaux de (fx, fy) autour de `center`."""
|
|
cx, cy = center
|
|
return [[(cx + (x - cx) * fx, cy + (y - cy) * fy) for x, y in ring] for ring in rings]
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Homographie (projection plane) a partir de 4 correspondances
|
|
# --------------------------------------------------------------------------
|
|
|
|
def _normalizer(points):
|
|
"""Similitude qui centre les points et ramene leur distance moyenne a sqrt(2).
|
|
|
|
Normalisation de Hartley : rend la resolution numerique stable quel que
|
|
soit l'ordre de grandeur des coordonnees (pixels contre millimetres).
|
|
"""
|
|
pts = np.asarray(points, dtype=float)
|
|
center = pts.mean(axis=0)
|
|
spread = np.sqrt(((pts - center) ** 2).sum(axis=1)).mean()
|
|
scale = math.sqrt(2) / spread if spread > 0 else 1.0
|
|
return np.array([[scale, 0, -scale * center[0]],
|
|
[0, scale, -scale * center[1]],
|
|
[0, 0, 1]])
|
|
|
|
|
|
def homography(src, dst):
|
|
"""Matrice 3x3 qui envoie exactement 4 points `src` sur 4 points `dst`.
|
|
|
|
Leve ValueError si la configuration est degeneree (3 points alignes).
|
|
"""
|
|
src = np.asarray(src, dtype=float)
|
|
dst = np.asarray(dst, dtype=float)
|
|
if src.shape != (4, 2) or dst.shape != (4, 2):
|
|
raise ValueError("4 points attendus")
|
|
ts, td = _normalizer(src), _normalizer(dst)
|
|
s = apply_homography(ts, src)
|
|
d = apply_homography(td, dst)
|
|
rows, rhs = [], []
|
|
for (x, y), (u, v) in zip(s, d):
|
|
rows.append([x, y, 1, 0, 0, 0, -u * x, -u * y])
|
|
rows.append([0, 0, 0, x, y, 1, -v * x, -v * y])
|
|
rhs += [u, v]
|
|
a = np.array(rows)
|
|
if abs(np.linalg.det(a)) < 1e-12:
|
|
raise ValueError("points degeneres")
|
|
h = np.append(np.linalg.solve(a, np.array(rhs)), 1.0).reshape(3, 3)
|
|
matrix = np.linalg.inv(td) @ h @ ts
|
|
return matrix / matrix[2, 2]
|
|
|
|
|
|
def apply_homography(matrix, points):
|
|
"""Applique une homographie a une liste de points (renvoie un tableau Nx2)."""
|
|
pts = np.asarray(points, dtype=float).reshape(-1, 2)
|
|
homog = np.hstack([pts, np.ones((len(pts), 1))]) @ np.asarray(matrix).T
|
|
return homog[:, :2] / homog[:, 2:3]
|
|
|
|
|
|
def local_scale(matrix, point):
|
|
"""Facteur d'echelle local (moyenne geometrique) de l'homographie en un point."""
|
|
x, y = point
|
|
eps = 1.0
|
|
p = apply_homography(matrix, [(x, y), (x + eps, y), (x, y + eps)])
|
|
jac = np.array([p[1] - p[0], p[2] - p[0]]) / eps
|
|
return math.sqrt(abs(np.linalg.det(jac)))
|
|
|
|
|
|
def is_convex_quad(points):
|
|
"""Vrai si les 4 points (dans l'ordre) forment un quadrilatere convexe."""
|
|
pts = np.asarray(points, dtype=float)
|
|
signs = []
|
|
for k in range(4):
|
|
a, b, c = pts[k], pts[(k + 1) % 4], pts[(k + 2) % 4]
|
|
cross = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
|
|
signs.append(cross)
|
|
return all(s > 0 for s in signs) or all(s < 0 for s in signs)
|
|
|
|
|
|
def order_corners(points):
|
|
"""Range 4 points (repere image, y vers le bas) en HG, HD, BD, BG.
|
|
|
|
Tri par angle autour du barycentre : robuste a une rotation de la
|
|
photo jusqu'a 45 degres ; au-dela, c'est le repere origine qui
|
|
retablit l'orientation (`rotate_to_origin`).
|
|
"""
|
|
pts = [tuple(map(float, p)) for p in points]
|
|
cx = sum(p[0] for p in pts) / 4.0
|
|
cy = sum(p[1] for p in pts) / 4.0
|
|
# atan2 en y vers le bas : HG ~ -135 deg, HD ~ -45, BD ~ 45, BG ~ 135.
|
|
return sorted(pts, key=lambda p: math.atan2(p[1] - cy, p[0] - cx))
|
|
|
|
|
|
def rotate_to_origin(ordered, origin_index):
|
|
"""Decale cycliquement 4 points ordonnes pour que `origin_index` passe en BG."""
|
|
shift = (origin_index - ORIGIN_MARKER) % 4
|
|
return [ordered[(k + shift) % 4] for k in range(4)]
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Contours d'un masque binaire
|
|
# --------------------------------------------------------------------------
|
|
|
|
# Rotation d'un quart de tour dans le sens horaire a l'ecran (y vers le bas).
|
|
def _turn_right(direction):
|
|
dx, dy = direction
|
|
return -dy, dx
|
|
|
|
|
|
def mask_to_rings(mask):
|
|
"""Contours d'un masque binaire (tableau 2D) en coordonnees image continues.
|
|
|
|
Suit les aretes entre pixels allumes et eteints (le premier plan reste a
|
|
droite du sens de parcours), puis prend le milieu de chaque arete : on
|
|
obtient un contour qui suit la frontiere a mieux que le demi-pixel, sans
|
|
marches d'escalier. Aux sommets en « damier », on tourne a droite, ce qui
|
|
separe deux pixels qui ne se touchent que par un coin.
|
|
"""
|
|
m = np.pad(np.asarray(mask, dtype=bool), 1)
|
|
edges = {}
|
|
|
|
def add(rows, cols, start, direction):
|
|
for r, c in zip(rows.tolist(), cols.tolist()):
|
|
# (r, c) indices dans le masque borde : pixel d'origine (r-1, c-1).
|
|
x0, y0 = c - 1 + start[0], r - 1 + start[1]
|
|
edges.setdefault((x0, y0), []).append(direction)
|
|
|
|
inner = m[1:-1, 1:-1]
|
|
# Arete du haut, parcourue vers la droite ; bas vers la gauche ;
|
|
# droite vers le bas ; gauche vers le haut (sens horaire a l'ecran).
|
|
r, c = np.nonzero(inner & ~m[:-2, 1:-1])
|
|
add(r + 1, c + 1, (0, 0), (1, 0))
|
|
r, c = np.nonzero(inner & ~m[2:, 1:-1])
|
|
add(r + 1, c + 1, (1, 1), (-1, 0))
|
|
r, c = np.nonzero(inner & ~m[1:-1, 2:])
|
|
add(r + 1, c + 1, (1, 0), (0, 1))
|
|
r, c = np.nonzero(inner & ~m[1:-1, :-2])
|
|
add(r + 1, c + 1, (0, 1), (0, -1))
|
|
|
|
rings = []
|
|
while edges:
|
|
start = next(iter(edges))
|
|
direction = edges[start][0]
|
|
vertex = start
|
|
ring = []
|
|
while True:
|
|
outgoing = edges.get(vertex)
|
|
if not outgoing or (ring and vertex == start):
|
|
break
|
|
if len(outgoing) == 1:
|
|
chosen = outgoing[0]
|
|
else:
|
|
# Sommet en damier : on tourne a droite.
|
|
right = _turn_right(direction)
|
|
chosen = right if right in outgoing else outgoing[0]
|
|
outgoing.remove(chosen)
|
|
if not outgoing:
|
|
del edges[vertex]
|
|
ring.append((vertex[0] + chosen[0] / 2.0, vertex[1] + chosen[1] / 2.0))
|
|
vertex = (vertex[0] + chosen[0], vertex[1] + chosen[1])
|
|
direction = chosen
|
|
if len(ring) >= 3:
|
|
rings.append(ring)
|
|
return rings
|
|
|
|
|
|
def _dp(points, tolerance):
|
|
"""Douglas-Peucker iteratif sur une polyligne ouverte (extremites gardees)."""
|
|
pts = np.asarray(points, dtype=float)
|
|
keep = np.zeros(len(pts), dtype=bool)
|
|
keep[0] = keep[-1] = True
|
|
stack = [(0, len(pts) - 1)]
|
|
while stack:
|
|
first, last = stack.pop()
|
|
if last - first < 2:
|
|
continue
|
|
a, b = pts[first], pts[last]
|
|
seg = pts[first + 1:last]
|
|
ab = b - a
|
|
norm = math.hypot(ab[0], ab[1])
|
|
if norm == 0:
|
|
dist = np.hypot(seg[:, 0] - a[0], seg[:, 1] - a[1])
|
|
else:
|
|
dist = np.abs(ab[0] * (seg[:, 1] - a[1]) - ab[1] * (seg[:, 0] - a[0])) / norm
|
|
index = int(np.argmax(dist))
|
|
if dist[index] > tolerance:
|
|
split = first + 1 + index
|
|
keep[split] = True
|
|
stack.append((first, split))
|
|
stack.append((split, last))
|
|
return [tuple(p) for p in pts[keep]]
|
|
|
|
|
|
def simplify_ring(ring, tolerance):
|
|
"""Simplifie un anneau ferme (Douglas-Peucker) ; renvoie au moins 3 points."""
|
|
if tolerance <= 0 or len(ring) <= 4:
|
|
return list(ring)
|
|
pts = np.asarray(ring, dtype=float)
|
|
# Coupe l'anneau entre deux points eloignes pour simplifier deux moities.
|
|
far = int(np.argmax(np.hypot(pts[:, 0] - pts[0, 0], pts[:, 1] - pts[0, 1])))
|
|
if far == 0:
|
|
return list(ring)
|
|
first = _dp(list(pts[:far + 1]), tolerance)
|
|
second = _dp(list(pts[far:]) + [tuple(pts[0])], tolerance)
|
|
result = first[:-1] + second[:-1]
|
|
return result if len(result) >= 3 else list(ring)
|
|
|
|
|
|
def ring_area(ring):
|
|
"""Aire signee (formule du lacet) ; le signe depend du sens de parcours."""
|
|
pts = np.asarray(ring, dtype=float)
|
|
x, y = pts[:, 0], pts[:, 1]
|
|
return 0.5 * float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1)))
|
|
|
|
|
|
def ring_centroid(ring):
|
|
"""Barycentre de la surface delimitee par un anneau."""
|
|
pts = np.asarray(ring, dtype=float)
|
|
x, y = pts[:, 0], pts[:, 1]
|
|
xn, yn = np.roll(x, -1), np.roll(y, -1)
|
|
cross = x * yn - xn * y
|
|
area = cross.sum() / 2.0
|
|
if area == 0:
|
|
return float(x.mean()), float(y.mean())
|
|
return (float(((x + xn) * cross).sum() / (6 * area)),
|
|
float(((y + yn) * cross).sum() / (6 * area)))
|
|
|
|
|
|
def scale_rings(rings, factor, offset=(0.0, 0.0)):
|
|
"""Multiplie les coordonnees des anneaux puis les decale."""
|
|
ox, oy = offset
|
|
return [[(x * factor + ox, y * factor + oy) for x, y in ring] for ring in rings]
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Verification du placement des formes sur la planche
|
|
# --------------------------------------------------------------------------
|