version initiale

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016S8V7WxoS7YRoM34BVBkeo
This commit is contained in:
AlexandClaude Opus 5.5 committed 2026-09-25 17:14:49 +02:00
commit 3c95582a5c
28 files changed
+6570

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
# Cache Python et outils
__pycache__/
*.pyc
.pytest_cache/
.venv/
# Archives de distribution
*.zip
# SVG intermediaires du schema (regeneres par docs/schema_parametres.py)
docs/*.svg
+470
View File
@@ -0,0 +1,470 @@
# Photo de planche — extension Inkscape
<table>
<tr>
<td width="50%" valign="top">
<img src="docs/apercu-import.png" alt="Photo de planche redressée sur une zone de travail de 400 × 400 mm, avec les 4 repères de calibration aux coins et le contour vectorisé de la planche et de ses trous en surimpression" width="420">
</td>
<td valign="top">
Extension Inkscape 1.x pour réutiliser des planches déjà entamées (chutes,
panneaux percés) à la découpeuse laser. On photographie la planche posée sur
la surface de travail ; l'extension repère les **4 repères de calibration**
collés aux angles du nid d'abeille, redresse la photo et la place sur une page de la taille
exacte de la zone de travail : **1 mm sur la photo = 1 mm dans le document**.
Le contour de la planche et ses trous sont vectorisés sur un calque verrouillé.
On positionne ensuite les formes à découper par superposition, dans le calque
« Découpes », puis on les envoie à la laser avec *Export to LaserGRBL* : le bas
gauche de la page est l'origine laser.
</td>
</tr>
</table>
## Sommaire
- [Fonctionnalités](#fonctionnalités)
- [Installation](#installation)
- [Utilisation](#utilisation)
- [Paramètres](#paramètres)
- [Précision et limites](#précision-et-limites)
- [Structure du projet](#structure-du-projet)
- [Développement](#développement)
## Fonctionnalités
- **Deux entrées de menu** dans *Extensions > AlexDesign* :
- **Imprimer les repères de calibration** : dessine les 4 repères, au choix à graver une
fois pour toutes sur la surface de travail, ou sur une **feuille A4 à
imprimer** (grille à découper) accompagnée de **gabarits de pose** à graver
pour coller chaque repère à sa position exacte ;
- **Importer et calibrer** : photo → image redressée à l'échelle + contour et
trous vectorisés ; avec les repères collés aux angles du nid d'abeille,
origine laser et échelle sont déduites automatiquement.
- **Échelle garantie par construction** : homographie calculée sur les 4
repères, photo rééchantillonnée sur toute la zone de travail et insérée avec
`preserveAspectRatio="none"` sur un rectangle de `largeur × hauteur` mm.
- **Repère laser** : coordonnées saisies en mm depuis l'origine laser, en bas à
gauche de la zone de travail ; la page du document est réglée à la taille de
la zone.
- **Orientation automatique** : le repère origine porte deux pastilles, les
autres une seule ; la photo peut être prise dans n'importe quel sens.
- **Repli manuel** : si les repères ne sont pas trouvés, la photo brute est
placée avec 4 viseurs à amener sur les repères, puis on relance.
- **Échelle du document conservée** : un document en px garde ses objets
intacts, seule la page change de taille.
- **Calques dédiés** (du bas vers le haut) : « Photo de la planche » et
« Contour de la planche » (verrouillés), « Découpes » (calque actif).
Relancer l'import remplace la
photo et le contour sans toucher aux découpes.
- **Photo locale ou distante** : fichier photo, ou prise de vue déclenchée sur
une machine distante (caméra fixe au-dessus de la laser) par son adresse IP,
via un petit serveur de capture HTTP (routes `/capture` et `/old`).
- Traitement d'image sans OpenCV ni scipy : numpy et Pillow, déjà fournis avec
le Python d'Inkscape ; environ 2 s pour une photo de 4 Mpx.
- Interface traduite en français et en anglais, selon la langue d'Inkscape
(anglais pour toute autre langue).
- Script de déploiement PowerShell.
## Installation
Aucune dépendance externe : l'extension utilise `inkex`, `numpy` et `Pillow`,
tous fournis avec Inkscape 1.x (vérifié avec Inkscape 1.4 : Python 3.12,
numpy 2.3, Pillow 12).
### Windows (script)
Fermer Inkscape, puis dans PowerShell, depuis le dossier du projet :
```powershell
.\deploy.ps1 # installe ou met à jour
.\deploy.ps1 -Uninstall # désinstalle
.\deploy.ps1 -Force # déploie même si Inkscape est ouvert
```
Les fichiers sont copiés dans `%APPDATA%\inkscape\extensions\Planche photo`.
Redémarrer Inkscape.
### Manuelle
Copier dans un sous-dossier du répertoire des extensions utilisateur :
- `board_photo_import.inx/.py`, `board_photo_markers.inx/.py` ;
- `board_photo_core.py`, `board_photo_vision.py`, `board_photo_common.py`,
`board_photo_remote.py` ;
- `images/parameters_en.png` et le dossier `locale/`.
| Système | Dossier des extensions |
| ------- | ---------------------------------------------- |
| Windows | `%APPDATA%\inkscape\extensions` |
| Linux | `~/.config/inkscape/extensions` |
| macOS | `~/Library/Application Support/org.inkscape.Inkscape/config/inkscape/extensions` |
## Utilisation
### 1. Installer les repères (une seule fois)
Nouveau document, **Extensions > AlexDesign > Photo de planche : imprimer les
repères de calibration** (*Board photo: print calibration markers*). Renseigner la zone de
travail et la position des repères, puis choisir la **Sortie**.
**Repères aux angles du nid d'abeille (recommandé)** : imprimer la feuille A4
(ci-dessous), découper les 4 pièces et les coller **autour** du nid d'abeille,
le coin intérieur de chaque pièce touchant un angle du nid, le repère à deux
pastilles en bas à gauche (schéma, panneau 1). Rien d'autre à mesurer : dans
« Importer et calibrer », position « Autour du nid d'abeille » (défaut),
l'angle bas gauche du nid est l'origine laser et l'écart entre repères vaut la
taille du nid plus deux fois la taille des repères (440 × 440 mm pour un nid de
400 × 400 et des repères de 20 mm). La photo calibrée déborde de la page pour
montrer les repères ; la page reste la zone de travail et le contour de la
planche n'est cherché que dedans (l'image n'est jamais exportée vers la laser).
Les autres montages (repères dans la zone de travail) se règlent en position
« Personnalisée » :
**Repères gravés** (sortie « Repères à graver sur la surface ») : graver le
calque « Repères de calibration » en remplissage, sur des plaques claires
(contreplaqué, carton) fixées à la surface de travail, avec une zone claire
d'environ deux fois la taille d'un repère autour de chacun. C'est la laser qui
les positionne : leur position est exacte dans son propre repère.
**Repères imprimés** :
<table>
<tr>
<td width="40%" valign="top">
<img src="docs/apercu-feuille-a4.png" alt="Feuille A4 : titre et consignes, 4 repères de 20 mm dans des pièces carrées de 40 mm à découper en pointillés, traits d'alignement au milieu de chaque bord, légende de chaque pièce et barres de contrôle de 100 mm (horizontale en bas, verticale à droite)" width="300">
</td>
<td valign="top">
1. Sortie « Feuille A4 à imprimer » : la page passe en A4 et reçoit les 4
repères dans une grille 2 × 2 (même disposition que sur la surface, repère
origine en bas à gauche), chacun dans une pièce de deux fois sa taille à
découper le long des pointillés, avec des traits d'alignement au milieu de
chaque bord.
2. Imprimer **en taille réelle (100 %)**, sans « ajuster à la page » (voir
[Imprimer à la bonne échelle](#imprimer-à-la-bonne-échelle)) ; vérifier à
la règle que les deux barres (horizontale en bas, verticale à droite)
mesurent bien 100 mm. Découper les 4 pièces.
3. Dans un document de la taille de la zone de travail, sortie « Gabarits de
pose » : contour de chaque pièce et croix passant par le centre du repère,
en traits rouges fins. Les graver légèrement sur la surface (ou sur des
plaques fixées).
4. Coller chaque pièce dans son gabarit, ses traits d'alignement dans le
prolongement de la croix : le centre du repère tombe à sa position exacte.
</td>
</tr>
</table>
Dans les deux cas, ne plus déplacer les repères : ils donnent l'échelle de
chaque photo.
#### Imprimer à la bonne échelle
Le fichier est exact : la page PDF fait 210 × 297 mm et les barres 100 mm. Une
barre plus courte à l'impression (typiquement 97 mm) vient du pilote ou de la
boîte d'impression, qui réduit la page pour la faire tenir dans la zone
imprimable (« Ajuster à la page », « Réduire les pages trop grandes »,
« Ajuster à la zone imprimable »). Ce n'est pas un problème de DPI.
1. Exporter la feuille en PDF (*Fichier > Enregistrer une copie…*, type PDF)
plutôt que d'imprimer depuis Inkscape.
2. L'imprimer depuis le lecteur PDF en **Taille réelle** / **100 %**, sans
ajustement.
3. Si les barres ne font toujours pas 100 mm (pilote qui réduit malgré tout),
saisir leurs longueurs mesurées dans l'onglet **Feuille imprimée** et
régénérer la feuille : le dessin est agrandi d'autant (100 / 97 = 103,1 %
pour 97 mm), la correction est rappelée en tête de feuille. Réimprimer avec
les mêmes réglages et vérifier les barres.
Un léger écart d'échelle d'impression ne décale pas pour autant les repères :
une pièce un peu plus petite reste centrée sur la croix de son gabarit, et
c'est le centre du repère qui sert à la calibration. En revanche, au-delà de
5 %, l'import signale une taille de repère incohérente.
### 2. Importer une planche
1. Poser la planche **sans masquer les repères**, photographier du dessus (le
plus à la verticale possible, toute la zone dans le cadre).
2. Sans rien sélectionner, **Extensions > AlexDesign > Photo de planche :
importer et calibrer** (*Board photo: import and calibrate*), onglet
« Photo » : choisir le fichier, ou la source **Appareil distant** et
l'adresse de la machine qui porte la caméra (voir
[Caméra distante](#caméra-distante)). Garder les **mêmes réglages de zone
de travail** que pour les repères.
3. Appliquer. Un message indique la précision (mm par pixel de la photo) et le
nombre de trous trouvés. La page fait la taille de la zone de travail, la
photo et le contour sont en place, le calque « Découpes » est actif.
#### Caméra distante
La photo peut être prise par une caméra fixe reliée à une autre machine
(Raspberry Pi…), qui fait tourner un serveur de capture HTTP. L'extension
appelle :
| Route | Rôle |
| ----- | ---- |
| `GET /capture` | Prend une nouvelle photo et la renvoie (`image/jpeg`). |
| `GET /old` | Renvoie la dernière photo prise, sans en prendre de nouvelle. |
Un serveur Flask avec OpenCV qui expose ces deux routes sur le port 5000
convient tel quel. En cas d'erreur, le message renvoyé par le serveur
(« Error: Could not access the camera »…) est affiché dans Inkscape.
Dans l'onglet « Photo » : *Source de la photo* = *Appareil distant*, adresse
`192.168.1.20` (ou `192.168.1.20:5000`, ou une URL `http://…`), port, choix
entre nouvelle photo et dernière photo, délai d'attente. Les proxys du système
sont ignorés (la caméra est sur le réseau local). Une transmission interrompue
est retentée une fois automatiquement.
Conseils pour le serveur de capture :
- **Résolution** : c'est elle qui fixe la précision. En 1024 × 768, une zone de
400 mm occupe au mieux ~700 px de haut, soit environ 0,5 à 0,6 mm par pixel
(valeur affichée après l'import). Demander la résolution maximale de la
caméra (1920 × 1080, 2592 × 1944…) améliore la précision d'autant.
- **Premières images** : beaucoup de webcams livrent des premières images
sombres ou floues, le temps que l'exposition automatique se règle. Lire et
jeter quelques images avant de garder celle qui est enregistrée.
- Libérer la caméra (`camera.release()`) aussi dans les chemins d'erreur, sinon
les appels suivants peuvent échouer avec « Could not access the camera ».
- Fixer la caméra au-dessus de la laser : les repères n'ont pas à être
parfaitement cadrés au même endroit d'une photo à l'autre, mais les 4 doivent
être visibles.
Si la détection échoue, la photo brute est placée dans le calque
« Calibration manuelle » avec 4 viseurs rouges : amener chaque viseur au centre
d'un repère (en zoomant), sélectionner le contenu du calque (Ctrl+A) et
relancer l'extension.
### 3. Placer et découper
1. Dessiner ou coller les formes dans le calque « Découpes », en les posant sur
les zones pleines de la planche (le contour et les trous servent de guide).
2. Envoyer à la laser avec **Extensions > Export > Export to LaserGRBL**.
#### Export vers LaserGRBL
L'extension *Export to LaserGRBL* (v1.21) écrit le G-code en mm, **origine au
coin bas gauche de la page** : la page ayant la taille de la zone de travail,
ce coin est l'origine laser, et les pièces gardent leur place et leur taille,
que le document soit en mm ou en px. Elle exporte tout le document (calques
masqués compris) et retient chaque chemin, rectangle, cercle ou ellipse dont
la couleur de contour ou de remplissage *propre* est l'une de ses trois
couleurs (gravure, découpe intérieure, découpe extérieure, réglées dans
`export_lasergrbl.ini` ou mémorisées dans le document).
Les formes d'aide de « Photo de planche » (contour de la planche, viseurs)
ne portent donc aucune couleur à elles : elles
héritent celle de leur calque, s'affichent pareil, mais ne sont **jamais
exportées**, même rouges, et il n'est pas nécessaire de masquer ces calques.
La photo (image) n'est pas exportée non plus.
Pour que l'export soit juste :
- garder *Mettre la page à la taille de la zone de travail* coché (l'origine du
G-code est le bas gauche de la page ; l'import avertit sinon) ;
- partir d'un document dont la page commence en 0, 0 (le remplissage de
l'export ignore un viewBox décalé) ;
- n'utiliser que des chemins, rectangles, cercles et ellipses (*Chemin > Objet
en chemin* pour le reste), d'une couleur d'export opaque portée par la forme
elle-même, et ne pas placer de formes remplies dans un groupe déplacé.
Pour lire dans Inkscape les coordonnées dans le repère de la laser (origine en
bas à gauche), décocher *Préférences > Interface > Origine en haut à gauche avec
l'axe des y vers le bas*.
### Conseils
| Symptôme | Réglage |
| -------- | ------- |
| « détection automatique des repères a échoué » | Repères masqués, reflets ou trop petits : photo plus proche, éclairage diffus, ou calibration manuelle. |
| « Un repère mesure … mm au lieu de … mm » | Taille des repères différente de celle imprimée (mesurer un carré noir), ou pièces ne touchant pas exactement les angles du nid. |
| « le repère origine n'a pas été reconnu » | Pastilles du repère origine peu visibles : la photo est supposée droite, vérifier que l'import n'est pas tourné. |
| « Aucune planche trouvée » | Changer la *Teinte de la planche*, ou régler le *Seuil* à la main. |
| Contour qui déborde sur le nid d'abeille, trous parasites | Augmenter le *Lissage* ou l'*Aire minimale d'un trou*. |
| Document trop lourd | Baisser la *Résolution* (px/mm) ou la *Qualité JPEG*. |
## Paramètres
![Schéma des paramètres](docs/parametres.png)
### Importer et calibrer — onglet Zone de travail
Ces réglages sont identiques dans « Repères de calibration », qui propose en
plus la **Sortie** : repères à graver sur la surface (défaut), feuille A4 à
imprimer, ou gabarits de pose. Les gabarits (pièce de deux fois la taille du
repère et croix) demandent que chaque centre de repère soit à au moins
1,5 fois la taille du repère des bords (30 mm pour des repères de 20 mm) ; la
feuille A4 accepte des repères jusqu'à 40 mm.
| Paramètre (onglet Feuille imprimée) | Défaut | Rôle |
| --------- | ------ | ---- |
| Longueur mesurée de la barre horizontale (mm) | 100 | Longueur réelle de la barre X après impression ; sous 100, la feuille est élargie pour compenser. |
| Longueur mesurée de la barre verticale (mm) | 100 | Idem pour la barre Y. Valeurs admises : 80 à 120 mm. |
| Paramètre | Défaut | Rôle |
| --------- | ------ | ---- |
| Largeur (mm) | 400 | Largeur du nid d'abeille = zone de travail de la laser. |
| Hauteur (mm) | 400 | Hauteur du nid d'abeille. |
| Mettre la page à la taille de la zone de travail | coché | Page = zone de travail ; l'échelle des objets existants est conservée. |
| Position des repères (import seulement) | Autour du nid d'abeille | Coin intérieur de chaque pièce sur un angle du nid : origine et écart déduits. *Personnalisée* : valeurs ci-dessous. |
| Taille des repères (mm) | 20 | Côté du carré noir (pièce de papier : deux fois plus grande) ; sert aussi à contrôler l'échelle mesurée. |
| Centre du repère origine X (mm) | 30 | Position personnalisée : distance de l'origine laser au centre du repère à deux pastilles, selon X ; négative si le repère est hors de la zone. |
| Centre du repère origine Y (mm) | 30 | Idem selon Y, vers le haut. |
| Écart entre repères X (mm) | 340 | Position personnalisée : distance entre centres de repères, selon X. |
| Écart entre repères Y (mm) | 340 | Idem selon Y. |
### Importer et calibrer — onglets Photo et Détection de la planche
| Paramètre | Défaut | Rôle |
| --------- | ------ | ---- |
| Source de la photo | Fichier photo | Fichier photo, ou appareil distant (serveur de capture). |
| Photo de la planche | — | Photo prise du dessus, les 4 repères visibles (JPEG, PNG, TIFF…). L'orientation EXIF est respectée. |
| Adresse de la machine distante | — | IP, IP:port ou URL du serveur de capture. |
| Port | 5000 | Port du serveur (ignoré si l'adresse en contient un). |
| Image | Prendre une nouvelle photo | `/capture`, ou reprendre la dernière photo prise (`/old`). |
| Délai d'attente (s) | 20 | Temps maximal d'attente de la photo. |
| Résolution de la photo calibrée (px/mm) | 4 | 4 px/mm = 0,25 mm par pixel. |
| Qualité JPEG | 85 | Compression de la photo incorporée. |
| Vectoriser le contour et les trous de la planche | coché | Décocher pour n'importer que la photo. |
| Teinte de la planche | Plus claire que le fond | Ou plus foncée (planche sombre sur surface claire). |
| Seuil (0 = automatique) | 0 | Niveau de gris planche / fond ; 0 = méthode d'Otsu. |
| Lissage (mm) | 0,5 | Ouverture puis fermeture morphologiques : retire poussières et petites encoches. |
| Aire minimale d'un trou (mm²) | 4 | Les trous plus petits sont bouchés. |
| Tolérance du contour (mm) | 0,3 | Écart maximal de la simplification (Douglas-Peucker). |
| Couleur du contour | bleu `#1971c2` | Trait et remplissage léger du contour. |
## Précision et limites
- **Précision** : de l'ordre d'un pixel de la photo au niveau de la surface
de travail (affiché après l'import). Sur photo synthétique en perspective
(2400 × 1800 px, flou et bruit), les centres et diamètres des trous sont
retrouvés à 0,15 mm près ; les tests exigent 0,5 mm.
- **Distorsion de l'objectif** non corrigée : l'homographie suppose une
projection parfaite. Éviter les grands angles ; les smartphones corrigent en
général déjà leur distorsion.
- **Épaisseur de la planche** ignorée : sa face supérieure, plus proche de
l'objectif, paraît légèrement agrandie par rapport aux repères (environ
épaisseur / hauteur de prise de vue, soit 0,6 % pour 6 mm à 1 m). Photographier
de haut réduit l'écart.
- La planche ne doit pas masquer les repères, qui doivent rester sur une zone
claire.
## Structure du projet
```text
board_photo_import.inx / .py Importer et calibrer (photo, contour, calques)
board_photo_markers.inx / .py Imprimer les repères de calibration : feuille A4 (ou gravure, gabarits)
board_photo_core.py Géométrie pure (numpy) : repères, homographie,
contours, vérification ; sans inkex
board_photo_vision.py Traitement d'image (numpy + Pillow) : composantes
connexes, détection des repères, redressement,
vectorisation ; sans inkex
board_photo_common.py Outils inkex partagés : page, calques, aplatissement
board_photo_remote.py Photo demandée au serveur de capture distant (urllib)
i18n.py Extraction / mise à jour / compilation des traductions
po/ board_photo.pot, en.po, fr.po
locale/<langue>/LC_MESSAGES/ Catalogues compilés board_photo.mo
images/parameters_en.png Schéma de l'onglet « Diagram » (déployé)
docs/schema_parametres.py Générateur du schéma (fr pour le README, en pour le dialogue)
docs/parametres.png Schéma du README
docs/apercu-import.png Aperçu d'un import (photo synthétique)
docs/apercu-feuille-a4.png Aperçu de la feuille A4 de repères à imprimer
tests/synthetic.py Photo synthétique : planche trouée en perspective
tests/fake_camera.py Faux serveur de capture (/capture, /old) pour les tests
tests/data/ Documents vides en mm et en px, vraie photo à petits
repères (caméra distante 800 x 600)
test_board_photo.py Tests pytest
deploy.ps1 Déploiement / désinstallation Windows
```
### API du noyau (`board_photo_core`)
| Fonction | Rôle |
| -------- | ---- |
| `laser_to_svg(point, height)` / `svg_to_laser(...)` | Conversion repère laser (y vers le haut) ↔ repère SVG. |
| `marker_layout(height, origin_x, origin_y, spacing_x, spacing_y)` | Centres des 4 repères, ordre HG, HD, BD, BG (repère origine = BG). |
| `corner_layout(width, height, size)` | Origine et écart des repères dont les pièces touchent les angles du nid d'abeille. |
| `photo_extent(width, height, origin_x, origin_y, spacing_x, spacing_y, size, resolution)` | Rectangle couvert par la photo redressée : zone de travail agrandie jusqu'aux repères qui l'entourent. |
| `layout_problems(width, height, ...)` | Défauts de disposition des repères (`outside`, `too_close`, `non_positive`). |
| `marker_rings(center, size, origin=False)` | Anneaux d'un repère : carré + pastille(s), pair-impair. |
| `sheet_layout(size, page=A4, ...)` | Centres des 4 pièces sur la feuille imprimée (2 × 2 ou une colonne), `None` si trop grand. |
| `piece_side(size)` / `piece_outline(center, size)` / `piece_ticks(center, size)` | Pièce à découper (deux fois le repère) et ses traits d'alignement. |
| `guide_lines(center, size)` / `guide_reach(size)` | Gabarit de pose (contour + croix) et son emprise autour du centre. |
| `scale_bar(start, length=100, vertical=False)` | Barre graduée de contrôle d'impression. |
| `print_correction(measured_x, measured_y)` / `stretch_rings(rings, fx, fy, center)` | Correction d'une imprimante qui réduit : facteurs 100 / mesure et étirement. |
| `homography(src, dst)` / `apply_homography(matrix, points)` | Homographie exacte sur 4 points (normalisation de Hartley). |
| `local_scale(matrix, point)` | Échelle locale d'une homographie. |
| `order_corners(points)` / `rotate_to_origin(ordered, index)` | Ordonne 4 points et fixe l'orientation par le repère origine. |
| `mask_to_rings(mask)` | Contours d'un masque binaire (milieux des arêtes de pixels). |
| `simplify_ring(ring, tolerance)` | Simplification Douglas-Peucker d'un anneau fermé. |
| `ring_area(ring)` / `ring_centroid(ring)` | Aire signée et barycentre. |
`board_photo_vision` fournit `load_photo`, `label_components`, `fill_holes`,
`otsu_threshold`, `detect_markers`, `dots_near`, `rectify` et `extract_board`.
## Développement
```powershell
python -m venv .venv
.venv\Scripts\activate
pip install pytest numpy pillow lxml tinycss2 cssselect
python -m pytest -q # 57 passés, 20 ignorés (sans inkex)
$env:PYTHONPATH = 'C:\Program Files\Inkscape\share\inkscape\extensions'
python -m pytest -q # 77 passés
```
Les tests couvrent :
- le noyau : conversion de repère, disposition des repères, homographie,
contours, simplification, vérification du placement (9 cas), disposition de
la feuille A4, traits d'alignement, gabarits, barres de contrôle et
correction d'impression ;
- le traitement d'image : composantes connexes, trous, seuil d'Otsu, grille
de pixels du redressement (aucun décalage d'un demi-pixel), détection des
repères dans les 4 orientations, repères imprimés collés sur leur gabarit,
et **test d'échelle** complet sur photo synthétique en perspective (trous à
0,5 mm près) ;
- le bout en bout des deux entrées de menu : repères gravés, feuille A4 (tailles
imprimées exactes, barres de 100 mm, dessin dans la page, correction
d'imprimante), gabarits de pose, document en mm et en px, import
répété, erreurs, repli et calibration manuelle, repères aux angles du nid
d'abeille (origine et écart déduits, photo débordant de la page) ;
- l'**export LaserGRBL simulé** (sélection des formes et coordonnées du G-code de
l'extension v1.21) : seules les formes de « Découpes » partent, à la bonne
place et à la bonne taille en document mm et px ; photo et contour ne sont
pas exportés ;
- la caméra distante, contre un faux serveur lancé dans son propre processus :
adresses acceptées, nouvelle et dernière photo, erreur 500 du serveur,
réponse qui n'est pas une image, transmission coupée (nouvelle tentative),
machine injoignable ;
- les traductions et la cohérence des `.inx` (paramètres ↔ arguments et
défauts, réglages de zone de travail identiques entre import et repères).
### Traductions
```bash
python i18n.py # extract + update + compile
python i18n.py extract # po/board_photo.pot depuis les .inx et les .py
python i18n.py update # reporte le modèle dans po/en.po et po/fr.po
python i18n.py compile # po/*.po -> locale/*/LC_MESSAGES/board_photo.mo
```
Les textes source (`.inx` et appels `_()`) sont en anglais ; les deux `.inx`
partagent le domaine `board_photo`. Après modification d'un texte : lancer
`python i18n.py`, compléter les `msgstr` vides de `po/fr.po`, relancer. Pour
une nouvelle langue : l'ajouter à `LANGUAGES` dans `i18n.py`.
### Schéma des paramètres
```bash
python docs/schema_parametres.py # fr (docs/parametres.png, 1400 px)
# + en (images/parameters_en.png, 900 px)
```
Le schéma est dessiné avec les fonctions du noyau (disposition et dessin des
repères, homographie). L'export PNG passe par
`C:\Program Files\Inkscape\bin\inkscape.com`.
+173
View File
@@ -0,0 +1,173 @@
# coding=utf-8
"""
Outils inkex partages par les entrees de menu « Board photo ».
Page a la taille de la zone de travail, calques reperes par un attribut
`data-board-photo`. Les textes
affiches restent dans les scripts (appels _() extraits par i18n.py).
"""
import re
import inkex
DATA = "data-board-photo" # attribut qui marque nos calques et chemins
OUTLINE_SHAPE = "outline-path" # valeur portee par le chemin du contour
# Sur le calque de la photo : zone de travail (mm) utilisee pour la calibrer, « l h ».
AREA_ATTR = "data-board-photo-area"
# Enfants de la racine qui ne sont pas du dessin : on insere les calques
# du fond juste apres eux.
_NOT_DRAWING = {"defs", "namedview", "metadata", "title", "desc", "style", "script"}
def mm_scale(svg):
"""Unites utilisateur par millimetre du document."""
return svg.unittouu("1mm")
def length_uu(svg, value, default=0.0):
"""Attribut de longueur d'un element en unites utilisateur.
Sans unite, la valeur est deja en unites utilisateur ; `unittouu` la
prendrait pour des px et la convertirait a tort.
"""
text = str(value if value is not None else "").strip()
if not text:
return default
if re.match(r"^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$", text):
return float(text)
return svg.unittouu(text)
def prepare_page(svg, width, height, set_page=True):
"""Page de `width` x `height` mm ; renvoie (uu par mm, origine x, origine y).
L'echelle utilisateur existante est conservee (le viewBox suit la
nouvelle taille) : les objets deja presents gardent leurs dimensions.
"""
scale = mm_scale(svg)
box = svg.get("viewBox")
ox = oy = 0.0
if box:
values = [float(v) for v in box.replace(",", " ").split()]
if len(values) == 4:
ox, oy = values[0], values[1]
if set_page:
svg.set("width", "{}mm".format(fmt(width)))
svg.set("height", "{}mm".format(fmt(height)))
svg.set("viewBox", "{} {} {} {}".format(
fmt(ox), fmt(oy), fmt(width * scale), fmt(height * scale)))
pages = svg.namedview.findall(inkex.addNS("page", "inkscape"))
if len(pages) == 1:
pages[0].set("width", fmt(width * scale))
pages[0].set("height", fmt(height * scale))
return scale, ox, oy
def fmt(value):
return "{:.6f}".format(value).rstrip("0").rstrip(".")
# Couleur des viseurs, portee par leur calque (voir `paint_layer`).
TARGET_COLOR = "#ff0000"
def paint_layer(layer, fill="none", stroke="none"):
"""Donne au calque les couleurs de remplissage et de contour de ses formes.
L'extension « Export to LaserGRBL » grave ou decoupe chaque chemin selon
les couleurs `fill` / `stroke` de son propre attribut style, sans tenir
compte des calques masques : nos formes d'aide (contour de la planche,
viseurs, rapport) ne portent donc aucune couleur a elles et heritent
celles de leur calque. Affichees a l'identique, jamais exportees.
"""
layer.style = inkex.Style({"fill": fill, "stroke": stroke})
return layer
def target(cx, cy, radius, scale, label):
"""Viseur (croix dans un cercle) centre en (cx, cy), unites utilisateur.
Sans couleur propre : le poser dans un calque colore par `paint_layer`.
"""
path = inkex.PathElement()
path.set("d", ("M {x0},{cy} L {x1},{cy} M {cx},{y0} L {cx},{y1} "
"M {x1},{cy} A {r},{r} 0 1 1 {x0},{cy} "
"A {r},{r} 0 1 1 {x1},{cy} Z").format(
x0=fmt(cx - radius), x1=fmt(cx + radius), y0=fmt(cy - radius),
y1=fmt(cy + radius), cx=fmt(cx), cy=fmt(cy), r=fmt(radius)))
path.style = inkex.Style({"stroke-width": str(0.4 * scale)})
path.label = label
return path
def center_of(elem):
"""Centre de la boite englobante d'un element, en coordonnees du document."""
return elem.bounding_box(elem.getparent().composed_transform()).center
def find_all(svg, key):
"""Elements dont l'attribut data-board-photo vaut `key`."""
return svg.xpath("//*[@{}='{}']".format(DATA, key))
def remove_layers(svg, key):
for elem in find_all(svg, key):
elem.delete()
def new_layer(label, key, locked=False):
layer = inkex.Layer.new(label)
layer.set(DATA, key)
if locked:
layer.set("sodipodi:insensitive", "true")
return layer
def insert_bottom(svg, layer):
"""Place un calque sous tout le dessin existant."""
index = 0
for index, child in enumerate(svg):
tag = child.TAG if hasattr(child, "TAG") else ""
local = str(child.tag).rsplit("}", 1)[-1]
if local not in _NOT_DRAWING and tag not in _NOT_DRAWING:
break
else:
index = len(svg)
svg.insert(index, layer)
def set_current_layer(svg, layer):
"""Calque actif a l'ouverture : l'utilisateur dessine directement dedans."""
svg.namedview.set(inkex.addNS("current-layer", "inkscape"), layer.get_id())
# --------------------------------------------------------------------------
# « Export to LaserGRBL » : origine du G-code au coin bas gauche de la page
# (viewBox), le remplissage ignorant l'abscisse du viewBox ; la page doit donc
# etre la zone de travail et commencer en 0 0.
# --------------------------------------------------------------------------
def page_problems(svg):
"""Defauts de la page qui decaleraient le G-code.
`viewbox_offset` : viewBox ne commencant pas en 0 0 (le remplissage de
l'export ignore ce decalage) ; `page_size` : page differente de la zone
de travail de la photo calibree (l'origine du G-code est le bas gauche
de la page).
"""
problems = []
box = svg.get_viewbox()
if abs(box[0]) > 1e-6 or abs(box[1]) > 1e-6:
problems.append("viewbox_offset")
photos = find_all(svg, "photo")
area = photos[0].get(AREA_ATTR) if photos else None
if area:
width, height = (float(v) for v in area.split())
page_w = svg.unit_to_viewport(box[2], "mm")
page_h = svg.unit_to_viewport(box[3], "mm")
if abs(page_w - width) > 0.01 or abs(page_h - height) > 0.01:
problems.append("page_size")
return problems
+539
View File
@@ -0,0 +1,539 @@
# 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
# --------------------------------------------------------------------------
+156
View File
@@ -0,0 +1,156 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Textes source en anglais, traduits par le catalogue « board_photo »
(locale/<langue>/LC_MESSAGES/board_photo.mo), commun aux entrées
de menu. Après toute modification d'un texte : python i18n.py, puis
compléter po/fr.po et relancer.
Les réglages de l'onglet « Work area » doivent rester identiques à ceux
de board_photo_markers.inx (mêmes noms, mêmes défauts).
-->
<inkscape-extension translationdomain="board_photo"
xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<name>Board photo: import and calibrate</name>
<id>fr.alexp.board_photo.import</id>
<param name="tab" type="notebook">
<page name="work_area" gui-text="Work area">
<label appearance="header">Honeycomb = laser work area (mm)</label>
<param name="work_width" type="float" precision="1" min="10" max="5000"
gui-text="Width (mm):">400.0</param>
<param name="work_height" type="float" precision="1" min="10" max="5000"
gui-text="Height (mm):">400.0</param>
<param name="set_page" type="bool"
gui-text="Set the page to the work area size">true</param>
<separator/>
<label appearance="header">Calibration markers</label>
<param name="marker_placement" type="optiongroup" appearance="radio"
gui-text="Marker position:">
<option value="corners">Around the honeycomb: the inner corner of each paper piece touches a corner of the honeycomb</option>
<option value="custom">Custom: centre of the origin marker and spacing below</option>
</param>
<param name="marker_size" type="float" precision="1" min="5" max="200"
gui-text="Marker size (mm):"
gui-description="Side of the black square; the paper piece is twice as large">20.0</param>
<label>Around the honeycomb, everything is deduced: the bottom left corner of the honeycomb is the laser origin (bottom left of the page), and the spacing is the honeycomb size plus twice the marker size. The values below are only used for a custom position.</label>
<param name="origin_x" type="float" precision="2" min="-1000" max="5000"
gui-text="Origin marker centre X (mm):"
gui-description="Distance from the laser origin to the centre of the two-dot marker, along X; negative when the markers are around the work area (left of the origin)">30.0</param>
<param name="origin_y" type="float" precision="2" min="-1000" max="5000"
gui-text="Origin marker centre Y (mm):"
gui-description="Distance from the laser origin to the centre of the two-dot marker, along Y (upwards); negative when the markers are around the work area (below the origin)">30.0</param>
<param name="spacing_x" type="float" precision="2" min="1" max="5000"
gui-text="Spacing between markers X (mm):">340.0</param>
<param name="spacing_y" type="float" precision="2" min="1" max="5000"
gui-text="Spacing between markers Y (mm):">340.0</param>
</page>
<page name="photo" gui-text="Photo">
<param name="photo_source" type="optiongroup" appearance="radio"
gui-text="Photo source:">
<option value="file">Photo file</option>
<option value="remote">Remote camera (capture server)</option>
</param>
<separator/>
<label appearance="header">Photo file</label>
<param name="photo" type="path" mode="file"
filetypes="jpg,jpeg,png,tif,tiff,bmp,webp"
gui-text="Photo of the board:"
gui-description="Photo taken from above, showing the 4 markers"></param>
<separator/>
<label appearance="header">Remote camera</label>
<param name="remote_host" type="string"
gui-text="Address of the remote machine (IP or IP:port):"
gui-description="Machine running the capture server, for example 192.168.1.20"></param>
<param name="remote_port" type="int" min="1" max="65535"
gui-text="Port:">5000</param>
<param name="remote_endpoint" type="optiongroup" appearance="combo"
gui-text="Picture:">
<option value="capture">Take a new photo (/capture)</option>
<option value="old">Use the last photo taken (/old)</option>
</param>
<param name="remote_timeout" type="int" min="1" max="300"
gui-text="Timeout (s):">20</param>
<separator/>
<param name="resolution" type="float" precision="1" min="1" max="20"
gui-text="Resolution of the calibrated photo (px/mm):"
gui-description="4 px/mm = 0.25 mm per pixel; higher values make a heavier document">4.0</param>
<param name="jpeg_quality" type="int" min="30" max="100"
gui-text="JPEG quality:">85</param>
</page>
<page name="board" gui-text="Board detection">
<param name="vectorize" type="bool"
gui-text="Vectorize the board outline and holes">true</param>
<param name="board_tone" type="optiongroup" appearance="combo"
gui-text="Board tone:">
<option value="lighter">Lighter than the bed (light wood on honeycomb)</option>
<option value="darker">Darker than the bed (dark board on light surface)</option>
</param>
<param name="threshold" type="int" min="0" max="255"
gui-text="Threshold (0 = automatic):"
gui-description="Grey level between board and bed; 0 computes it automatically (Otsu)">0</param>
<param name="smoothing" type="float" precision="2" min="0" max="10"
gui-text="Smoothing (mm):"
gui-description="Removes specks and fills small notches smaller than about twice this value">0.5</param>
<param name="min_hole_area" type="float" precision="1" min="0" max="10000"
gui-text="Minimum hole area (mm²):"
gui-description="Smaller holes are ignored (filled)">4.0</param>
<param name="simplify" type="float" precision="2" min="0" max="5"
gui-text="Outline tolerance (mm):"
gui-description="Maximum deviation allowed when simplifying the outline">0.3</param>
<param name="outline_color" type="color" appearance="colorbutton"
gui-text="Outline colour:">426885887</param>
</page>
<!-- Schéma généré par docs/schema_parametres.py, en anglais :
Inkscape ne traduit pas le chemin d'une image. -->
<page name="diagram" gui-text="Diagram">
<image width="900" height="694">images/parameters_en.png</image>
</page>
<page name="help" gui-text="Help">
<label xml:space="preserve">1. Print the 4 markers (Board photo: print
calibration markers, A4 sheet) and stick
them at the corners of the honeycomb.
2. Lay the board on the bed and take a photo
from above showing the 4 markers.
3. With nothing selected, choose the photo
file, or the address of the remote camera
(capture server), and apply: the photo is
straightened and
placed at the exact scale of the work area,
with the board outline and holes.
4. Draw or place the shapes in the "Cuts"
layer, on the board, then export them with
"Export to LaserGRBL".
If the markers are not found, the raw photo
is placed with 4 red targets: move them onto
the marker centres, select the layer content
(Ctrl+A) and apply again.
Markers around the honeycomb (default): stick
the 4 printed pieces so that the inner corner
of each piece touches a corner of the
honeycomb, the two-dot marker at the bottom
left. The bottom left corner of the honeycomb
is then the laser origin, i.e. the bottom left
of the page, as expected by the export to
LaserGRBL.
Coordinates are in mm from the laser origin
(bottom left of the work area).</label>
</page>
</param>
<effect needs-live-preview="false">
<object-type>all</object-type>
<effects-menu>
<submenu name="AlexDesign"/>
</effects-menu>
</effect>
<script>
<command location="inx" interpreter="python">board_photo_import.py</command>
</script>
</inkscape-extension>
+401
View File
@@ -0,0 +1,401 @@
#!/usr/bin/env python3
# coding=utf-8
"""
Extension Inkscape : importe la photo d'une planche posee sur la surface de
travail d'une decoupeuse laser, a l'echelle exacte de la zone de travail.
Les 4 reperes de calibration (voir « Board photo: print calibration markers ») sont
detectes sur la photo, qui est redressee par homographie puis inseree sur la
page (1 mm photo = 1 mm document) ; le contour de la planche et ses trous
sont vectorises. Si la detection echoue, la photo brute est inseree avec 4
viseurs a poser sur les reperes : on relance alors l'extension sur cette
selection (calibration manuelle).
Traitement d'image dans board_photo_vision, geometrie dans board_photo_core,
sans dependance a inkex.
"""
import base64
import os
import sys
from urllib.parse import unquote, urlparse
import inkex
from inkex.localization import localize
# L'extension vit dans son propre sous-dossier des extensions Inkscape, qui
# n'est pas forcement dans sys.path : on l'y ajoute pour trouver ses modules.
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import board_photo_common as common # noqa: E402
import board_photo_core as core # noqa: E402
import board_photo_remote as remote # noqa: E402
import board_photo_vision as vision # noqa: E402
# Installe _() dans les builtins : catalogue « board_photo » de la langue
# de l'interface (Inkscape transmet domaine et dossier par l'environnement),
# textes anglais d'origine sinon.
localize()
# Au-dela, la taille mesuree des reperes trahit une erreur de reglage
# (positions ou taille des reperes) ou une mauvaise detection.
MARKER_SIZE_TOLERANCE = 0.05
class BoardPhotoImport(inkex.EffectExtension):
"""Photo calibree + contour vectorise de la planche, sur des calques dedies."""
def add_arguments(self, pars):
# Un argument par <param> du .inx, memes noms et memes valeurs par defaut.
pars.add_argument("--tab", default="work_area")
pars.add_argument("--work_width", type=float, default=400.0)
pars.add_argument("--work_height", type=float, default=400.0)
pars.add_argument("--origin_x", type=float, default=30.0)
pars.add_argument("--origin_y", type=float, default=30.0)
pars.add_argument("--spacing_x", type=float, default=340.0)
pars.add_argument("--spacing_y", type=float, default=340.0)
pars.add_argument("--marker_size", type=float, default=20.0)
pars.add_argument("--marker_placement", default="corners")
pars.add_argument("--set_page", type=inkex.Boolean, default=True)
pars.add_argument("--photo_source", default="file")
pars.add_argument("--photo", default="")
pars.add_argument("--remote_host", default="")
pars.add_argument("--remote_port", type=int, default=5000)
pars.add_argument("--remote_endpoint", default="capture")
pars.add_argument("--remote_timeout", type=int, default=20)
pars.add_argument("--resolution", type=float, default=4.0)
pars.add_argument("--jpeg_quality", type=int, default=85)
pars.add_argument("--vectorize", type=inkex.Boolean, default=True)
pars.add_argument("--board_tone", default="lighter")
pars.add_argument("--threshold", type=int, default=0)
pars.add_argument("--smoothing", type=float, default=0.5)
pars.add_argument("--min_hole_area", type=float, default=4.0)
pars.add_argument("--simplify", type=float, default=0.3)
pars.add_argument("--outline_color", default="426885887")
# ------------------------------------------------------------------
# Point d'entree
# ------------------------------------------------------------------
def effect(self):
opt = self.options
self.notes = []
if opt.marker_placement == "corners":
# Pieces de papier aux angles du nid d'abeille : positions deduites.
opt.origin_x, opt.origin_y, opt.spacing_x, opt.spacing_y = \
core.corner_layout(opt.work_width, opt.work_height, opt.marker_size)
problems = core.layout_problems(opt.work_width, opt.work_height, opt.origin_x,
opt.origin_y, opt.spacing_x, opt.spacing_y,
opt.marker_size)
if "non_positive" in problems:
inkex.errormsg(_("Work area, marker spacing and marker size must be "
"strictly positive."))
return
# Des reperes autour de la zone de travail (hors de portee de la laser)
# calibrent aussi bien la photo : seule leur gravure l'interdit
# (« print calibration markers »).
selection = list(self.svg.selection.values())
if selection:
found = self.manual_points(selection)
if found is None:
return
photo, points, oriented, manual_layer = found
areas = None
else:
photo = self.open_photo()
if photo is None:
return
gray = vision.gray_array(photo)
try:
detected = vision.detect_markers(gray)
except vision.MarkerError as error:
self.insert_manual(photo, error)
return
points, oriented, areas = (detected["points"], detected["oriented"],
detected["areas"])
manual_layer = None
self.calibrate(photo, points, oriented, areas)
if manual_layer is not None:
manual_layer.delete()
# ------------------------------------------------------------------
# Sources de la photo
# ------------------------------------------------------------------
def open_photo(self):
if self.options.photo_source == "remote":
return self.remote_photo()
path = (self.options.photo or "").strip()
if not path:
inkex.errormsg(_("Choose the photo of the board in the \"Photo\" tab "
"(or select a photo and 4 markers for a manual "
"calibration)."))
return None
if not os.path.isfile(path):
inkex.errormsg(_("Photo not found: {}").format(path))
return None
try:
return vision.load_photo(path)
except (OSError, ValueError):
inkex.errormsg(_("This file cannot be read as an image: {}").format(path))
return None
def remote_photo(self):
"""Photo demandee au serveur de capture de la machine distante."""
opt = self.options
try:
url = remote.remote_url(opt.remote_host, opt.remote_port, opt.remote_endpoint)
data = remote.fetch_photo(url, opt.remote_timeout)
except remote.RemoteError as error:
messages = {
"no_host": _("Enter the address of the remote machine in the "
"\"Photo\" tab (for example 192.168.1.20)."),
"bad_host": _("Invalid remote address: {}"),
"unreachable": _("The remote machine cannot be reached ({}): check "
"its address, that the capture server is running "
"and that the port is open."),
"timeout": _("The remote machine did not answer in time ({}): "
"increase the timeout or check the network."),
"interrupted": _("The transfer of the photo was interrupted ({}), "
"even after a second attempt: check the network "
"and try again."),
"http": _("The capture server returned an error: {}"),
"not_image": _("The capture server did not return an image: {}"),
"too_large": _("The image returned by the capture server is too "
"large ({})."),
}
message = messages.get(error.reason, _("Remote capture failed: {}"))
inkex.errormsg(message.format(error.detail or error.reason))
return None
try:
photo = vision.load_photo(data)
except (OSError, ValueError):
inkex.errormsg(_("The capture server did not return a readable image "
"({}).").format(url))
return None
self.notes.append(_("Photo received from {} ({} x {} px).").format(
url, photo.width, photo.height))
return photo
def image_photo(self, image):
"""Contenu d'un element <image> : donnees incorporees ou fichier lie."""
href = image.get("xlink:href") or image.get("href") or ""
try:
if href.startswith("data:"):
return vision.load_photo(base64.b64decode(href.split(",", 1)[1]))
if href.startswith("file:"):
href = unquote(urlparse(href).path).lstrip("/") if os.name == "nt" \
else unquote(urlparse(href).path)
return vision.load_photo(self.absolute_href(href))
except (OSError, ValueError, IndexError):
return None
def manual_points(self, selection):
"""Calibration manuelle : une photo et 4 viseurs poses sur les reperes."""
images = [e for e in selection if isinstance(e, inkex.Image)]
others = [e for e in selection if not isinstance(e, inkex.Image)]
if len(images) != 1 or len(others) != 4:
inkex.errormsg(_("Manual calibration: select the photo and exactly 4 "
"small shapes centred on the markers (for example "
"Ctrl+A in the \"Manual calibration\" layer). "
"Deselect everything to import a new photo."))
return None
image = images[0]
photo = self.image_photo(image)
if photo is None:
inkex.errormsg(_("The selected image cannot be read (embed it, or "
"check that the linked file still exists)."))
return None
# Du document vers les pixels de la photo, a travers la transformation
# de l'image et de ses parents.
to_local = -image.composed_transform()
x = common.length_uu(self.svg, image.get("x"))
y = common.length_uu(self.svg, image.get("y"))
width = common.length_uu(self.svg, image.get("width"))
height = common.length_uu(self.svg, image.get("height"))
if width <= 0 or height <= 0:
inkex.errormsg(_("The selected image has no size."))
return None
points = []
for elem in others:
local = to_local.apply_to_point(common.center_of(elem))
points.append(((local.x - x) * photo.width / width,
(local.y - y) * photo.height / height))
dots = vision.dots_near(vision.gray_array(photo), points)
ordered = vision.orient_points(points, [d or 0 for d in dots])
layer = image.getparent()
manual_layer = layer if layer is not None and layer.get(common.DATA) == "manual" \
else None
return photo, ordered["points"], ordered["oriented"], manual_layer
def insert_manual(self, photo, error):
"""Detection impossible : photo brute + 4 viseurs a poser sur les reperes."""
opt = self.options
scale, ox, oy = common.prepare_page(self.svg, opt.work_width, opt.work_height,
opt.set_page)
common.remove_layers(self.svg, "manual")
layer = common.paint_layer(common.new_layer(_("Manual calibration"), "manual"),
stroke=common.TARGET_COLOR)
self.svg.add(layer)
common.set_current_layer(self.svg, layer)
# Photo ajustee a la page, proportions conservees.
fit = min(opt.work_width / photo.width, opt.work_height / photo.height)
width, height = photo.width * fit * scale, photo.height * fit * scale
image = self.make_image(photo, ox, oy, width, height)
layer.add(image)
# Viseurs vers les coins de la photo, a deplacer sur les reperes.
radius = opt.marker_size * 0.4 * scale
for fx, fy in ((0.1, 0.1), (0.9, 0.1), (0.9, 0.9), (0.1, 0.9)):
layer.add(common.target(ox + fx * width, oy + fy * height, radius, scale,
_("Marker target")))
reason = {"none": _("no dark shape found"),
"too_few": _("{} marker(s) found out of 4").format(error.found),
"layout": _("the markers found do not form a rectangle")}
inkex.errormsg(_("Automatic marker detection failed ({}).").format(
reason.get(error.reason, error.reason)))
inkex.errormsg(_("The raw photo was placed in the \"Manual calibration\" "
"layer with 4 red targets: move each target onto the "
"centre of a marker (zoom in), select the layer "
"content (Ctrl+A) and run this extension again."))
# ------------------------------------------------------------------
# Calibration et calques
# ------------------------------------------------------------------
def calibrate(self, photo, points, oriented, areas):
opt = self.options
targets = core.marker_layout(opt.work_height, opt.origin_x, opt.origin_y,
opt.spacing_x, opt.spacing_y)
if not core.is_convex_quad(points):
inkex.errormsg(_("The 4 marker positions do not form a convex "
"quadrilateral: check them and try again."))
return
try:
matrix = core.homography(points, targets)
except ValueError:
inkex.errormsg(_("The 4 marker positions are aligned: check them "
"and try again."))
return
warnings = []
if not oriented:
warnings.append(_("The origin marker (two dots) was not recognised: "
"the photo is assumed upright (origin at the "
"bottom left of the photo)."))
if areas:
sizes = [(area ** 0.5) * core.local_scale(matrix, point)
for area, point in zip(areas, points)]
worst = max(sizes, key=lambda s: abs(s - opt.marker_size))
if abs(worst - opt.marker_size) > MARKER_SIZE_TOLERANCE * opt.marker_size:
warnings.append(_("A marker measures {:.1f} mm instead of {:.1f} mm: "
"check the marker positions and size in the "
"\"Work area\" tab.").format(worst, opt.marker_size))
# Photo agrandie autour de la zone de travail pour montrer les reperes
# colles autour ; la planche n'est cherchee que dans la zone de travail.
extent = core.photo_extent(opt.work_width, opt.work_height, opt.origin_x,
opt.origin_y, opt.spacing_x, opt.spacing_y,
opt.marker_size, opt.resolution)
rectified, valid = vision.rectify(photo, matrix, extent[2] - extent[0],
extent[3] - extent[1], opt.resolution,
offset=extent[:2])
board = None
if opt.vectorize:
half = opt.marker_size
exclude = [(x - half, y - half, x + half, y + half) for x, y in targets]
col = int(round(-extent[0] * opt.resolution))
row = int(round(-extent[1] * opt.resolution))
area_w, area_h = vision.output_size(opt.work_width, opt.work_height,
opt.resolution)
board = vision.extract_board(
vision.gray_array(rectified)[row:row + area_h, col:col + area_w],
valid[row:row + area_h, col:col + area_w], opt.resolution,
lighter=opt.board_tone == "lighter", threshold=opt.threshold,
smoothing=opt.smoothing, min_hole_area=opt.min_hole_area,
simplify=opt.simplify, exclude=exclude)
if board is None:
warnings.append(_("No board found on the photo: try the other "
"\"Board tone\" or set the threshold by hand."))
scale, ox, oy = common.prepare_page(self.svg, opt.work_width, opt.work_height,
opt.set_page)
self.write_layers(rectified, board, scale, ox, oy, extent)
if "page_size" in common.page_problems(self.svg):
warnings.append(_("The page is not the size of the work area: the export "
"to LaserGRBL takes the bottom left of the page as the "
"laser origin, so tick \"Set the page to the work area "
"size\" before cutting."))
# Precision : taille d'un pixel de la photo au centre de la zone.
centre = (opt.work_width / 2.0, opt.work_height / 2.0)
pixel = 1.0 / core.local_scale(core.homography(targets, points), centre)
summary = _("Board photo calibrated: {:.2f} mm per photo pixel.").format(pixel)
summary = " ".join(self.notes + [summary])
if board is not None:
summary += " " + _("{} hole(s) found.").format(board["holes"])
for message in warnings:
inkex.errormsg(message)
inkex.errormsg(summary)
def make_image(self, picture, x, y, width, height):
data = vision.encode_image(picture, quality=self.options.jpeg_quality)
image = inkex.Image()
image.set("xlink:href", "data:image/jpeg;base64," +
base64.b64encode(data).decode("ascii"))
for name, value in (("x", x), ("y", y), ("width", width), ("height", height)):
image.set(name, common.fmt(value))
# Etirement exact sur le rectangle : c'est ce qui garantit l'echelle.
image.set("preserveAspectRatio", "none")
image.style = inkex.Style({"image-rendering": "optimizeQuality"})
return image
def write_layers(self, rectified, board, scale, ox, oy, extent=None):
opt = self.options
for key in ("photo", "outline"):
common.remove_layers(self.svg, key)
photo_layer = common.new_layer(_("Board photo"), "photo", locked=True)
common.insert_bottom(self.svg, photo_layer)
x0, y0, x1, y1 = extent or (0.0, 0.0, opt.work_width, opt.work_height)
image = self.make_image(rectified, ox + x0 * scale, oy + y0 * scale,
(x1 - x0) * scale, (y1 - y0) * scale)
image.label = _("Calibrated photo")
photo_layer.add(image)
# Zone de travail de la calibration (controle de la page avant export).
photo_layer.set(common.AREA_ATTR, "{} {}".format(
common.fmt(opt.work_width), common.fmt(opt.work_height)))
if board is not None:
color, opacity = core.parse_color(opt.outline_color)
outline_layer = common.paint_layer(
common.new_layer(_("Board outline"), "outline", locked=True),
fill=color, stroke=color)
photo_layer.addnext(outline_layer)
path = inkex.PathElement()
path.set("d", core.polylines_to_d(
core.scale_rings(board["rings"], scale, (ox, oy)), closed=True))
path.style = inkex.Style({
"fill-opacity": str(round(0.18 * opacity, 4)),
"fill-rule": "evenodd",
"stroke-opacity": str(opacity), "stroke-width": str(0.3 * scale)})
path.set(common.DATA, common.OUTLINE_SHAPE)
path.label = _("Board outline ({} holes)").format(board["holes"])
outline_layer.add(path)
cuts = common.find_all(self.svg, "cuts")
if cuts:
cuts_layer = cuts[0]
else:
cuts_layer = common.new_layer(_("Cuts"), "cuts")
self.svg.add(cuts_layer)
common.set_current_layer(self.svg, cuts_layer)
if __name__ == "__main__":
BoardPhotoImport().run()
+98
View File
@@ -0,0 +1,98 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Textes source en anglais, traduits par le catalogue « board_photo »
(commun aux entrées de menu). Après toute modification d'un
texte : python i18n.py, puis compléter po/fr.po et relancer.
Les réglages de l'onglet « Work area » doivent rester identiques à ceux
de board_photo_import.inx (mêmes noms, mêmes défauts).
-->
<inkscape-extension translationdomain="board_photo"
xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<name>Board photo: print calibration markers</name>
<id>fr.alexp.board_photo.markers</id>
<param name="tab" type="notebook">
<page name="work_area" gui-text="Work area">
<param name="mode" type="optiongroup" appearance="combo" gui-text="Output:">
<option value="bed">Markers to engrave on the bed</option>
<option value="sheet">A4 sheet to print (markers to cut out)</option>
<option value="guides">Placement guides to engrave on the bed (for printed markers)</option>
</param>
<separator/>
<label appearance="header">Laser work area (mm)</label>
<param name="work_width" type="float" precision="1" min="10" max="5000"
gui-text="Width (mm):">400.0</param>
<param name="work_height" type="float" precision="1" min="10" max="5000"
gui-text="Height (mm):">400.0</param>
<param name="set_page" type="bool"
gui-text="Set the page to the work area size">true</param>
<separator/>
<label appearance="header">Calibration markers, inside or around the work area (laser origin at the bottom left)</label>
<param name="origin_x" type="float" precision="2" min="-1000" max="5000"
gui-text="Origin marker centre X (mm):"
gui-description="Distance from the laser origin to the centre of the two-dot marker, along X; negative when the markers are around the work area (left of the origin)">30.0</param>
<param name="origin_y" type="float" precision="2" min="-1000" max="5000"
gui-text="Origin marker centre Y (mm):"
gui-description="Distance from the laser origin to the centre of the two-dot marker, along Y (upwards); negative when the markers are around the work area (below the origin)">30.0</param>
<param name="spacing_x" type="float" precision="2" min="1" max="5000"
gui-text="Spacing between markers X (mm):">340.0</param>
<param name="spacing_y" type="float" precision="2" min="1" max="5000"
gui-text="Spacing between markers Y (mm):">340.0</param>
<param name="marker_size" type="float" precision="1" min="5" max="200"
gui-text="Marker size (mm):">20.0</param>
</page>
<page name="print" gui-text="Printed sheet">
<label xml:space="preserve">Print the sheet at actual size (100 %,
no "fit to page"), preferably from a PDF
(File > Save a Copy > PDF). Then measure
both 100 mm bars.
Only if the printer still shrinks the sheet,
enter the measured lengths below: the sheet
is enlarged to compensate. Print it again
and check that the bars now measure 100 mm.</label>
<param name="print_x" type="float" precision="1" min="80" max="120"
gui-text="Measured length of the horizontal bar (mm):">100.0</param>
<param name="print_y" type="float" precision="1" min="80" max="120"
gui-text="Measured length of the vertical bar (mm):">100.0</param>
</page>
<page name="diagram" gui-text="Diagram">
<image width="900" height="694">images/parameters_en.png</image>
</page>
<page name="help" gui-text="Help">
<label xml:space="preserve">Engraved markers: engrave them once, filled,
on light plates fixed to the bed, keeping a
light area of twice the marker size around
each one.
Printed markers:
1. "A4 sheet": print at 100 % (no fit to
page), check the 100 mm bar, cut out the
4 pieces along the dashed lines.
2. "Placement guides": engrave them lightly
on the bed (thin red lines).
3. Stick each piece inside its guide, the
ticks of the piece on the cross.
The markers must stay in place: every photo
is scaled from them. The marker with two dots
is the origin marker, at the bottom left
(laser origin). Use the same settings in
"Board photo: import and calibrate".</label>
</page>
</param>
<effect needs-live-preview="false">
<object-type>all</object-type>
<effects-menu>
<submenu name="AlexDesign"/>
</effects-menu>
</effect>
<script>
<command location="inx" interpreter="python">board_photo_markers.py</command>
</script>
</inkscape-extension>
+228
View File
@@ -0,0 +1,228 @@
#!/usr/bin/env python3
# coding=utf-8
"""
Extension Inkscape : dessine les 4 reperes de calibration de la surface de
travail de la decoupeuse laser, selon trois sorties :
- « bed » (parametre mode) : reperes a graver directement sur la surface ; graves par la
laser elle-meme, ils sont exactement la ou l'import les attend ;
- « sheet » : feuille A4 a imprimer, reperes en grille a decouper, avec une
barre de 100 mm pour controler l'echelle d'impression ;
- « guides » : gabarits de pose a graver sur la surface (contour de la piece
et croix) pour coller les reperes imprimes a leur position exacte.
Le repere origine (deux pastilles, en bas a gauche = origine laser) donne
l'orientation de la photo.
Geometrie dans board_photo_core, sans dependance a inkex.
"""
import os
import sys
import inkex
from inkex.localization import localize
# L'extension vit dans son propre sous-dossier des extensions Inkscape, qui
# n'est pas forcement dans sys.path : on l'y ajoute pour trouver ses modules.
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import board_photo_common as common # noqa: E402
import board_photo_core as core # noqa: E402
# Installe _() dans les builtins : catalogue « board_photo » de la langue
# de l'interface, textes anglais d'origine sinon.
localize()
SHEET_MARGIN = 12.0 # marge de la feuille imprimee (mm)
class BoardPhotoMarkers(inkex.EffectExtension):
"""Reperes a graver, feuille A4 a imprimer, ou gabarits de pose."""
def add_arguments(self, pars):
# Un argument par <param> du .inx, memes noms et memes valeurs par defaut.
pars.add_argument("--tab", default="work_area")
pars.add_argument("--mode", default="bed")
pars.add_argument("--work_width", type=float, default=400.0)
pars.add_argument("--work_height", type=float, default=400.0)
pars.add_argument("--origin_x", type=float, default=30.0)
pars.add_argument("--origin_y", type=float, default=30.0)
pars.add_argument("--spacing_x", type=float, default=340.0)
pars.add_argument("--spacing_y", type=float, default=340.0)
pars.add_argument("--marker_size", type=float, default=20.0)
pars.add_argument("--set_page", type=inkex.Boolean, default=True)
pars.add_argument("--print_x", type=float, default=100.0)
pars.add_argument("--print_y", type=float, default=100.0)
def effect(self):
opt = self.options
if opt.mode == "sheet":
self.print_sheet()
return
# Un gabarit de pose (piece + croix) est plus grand que le repere seul.
reach = core.guide_reach(opt.marker_size) if opt.mode == "guides" else None
problems = core.layout_problems(opt.work_width, opt.work_height, opt.origin_x,
opt.origin_y, opt.spacing_x, opt.spacing_y,
opt.marker_size, reach)
if "non_positive" in problems:
inkex.errormsg(_("Work area, marker spacing and marker size must be "
"strictly positive."))
return
if "outside" in problems and reach is not None:
inkex.errormsg(_("The placement guides do not fit in the work area: keep "
"every marker centre at least {:g} mm from the edges "
"(1.5 x the marker size).").format(reach))
return
if "outside" in problems:
inkex.errormsg(_("The markers do not fit in the work area, so the laser "
"cannot engrave them: reduce the spacing or move the "
"origin marker. Markers placed around the work area "
"(negative origin, larger spacing) are printed instead "
"(\"Output\": A4 sheet) and stuck in place by hand."))
return
if "too_close" in problems:
inkex.errormsg(_("The markers are too close to each other: the spacing "
"must be at least twice the marker size."))
return
scale, ox, oy = common.prepare_page(self.svg, opt.work_width, opt.work_height,
opt.set_page)
centers = core.marker_layout(opt.work_height, opt.origin_x, opt.origin_y,
opt.spacing_x, opt.spacing_y)
if opt.mode == "guides":
self.draw_guides(centers, scale, ox, oy)
return
common.remove_layers(self.svg, "markers")
layer = common.new_layer(_("Calibration markers"), "markers")
self.svg.add(layer)
convert = self.converter(scale, ox, oy)
for index, center in enumerate(centers):
self.add_marker(layer, center, index == core.ORIGIN_MARKER, convert)
# ------------------------------------------------------------------
# Elements dessines
# ------------------------------------------------------------------
@staticmethod
def converter(scale, ox, oy, stretch=(1.0, 1.0), center=(0.0, 0.0)):
"""Fonction anneaux en mm -> anneaux en unites du document.
`stretch` agrandit autour de `center` (correction d'imprimante).
"""
def convert(rings):
rings = core.stretch_rings(rings, stretch[0], stretch[1], center)
return core.scale_rings(rings, scale, (ox, oy))
return convert
def add_marker(self, layer, center, origin, convert):
"""Un chemin plein pair-impair par repere (carre + pastilles)."""
rings = core.marker_rings(center, self.options.marker_size, origin=origin)
path = inkex.PathElement()
path.set("d", core.polylines_to_d(convert(rings), closed=True))
path.style = inkex.Style({"fill": "#000000", "fill-rule": "evenodd",
"stroke": "none"})
path.label = _("Origin marker") if origin else _("Marker")
layer.add(path)
@staticmethod
def add_lines(layer, polylines, style, convert, label):
"""Un chemin de traits (polylignes en mm) dans le calque."""
path = inkex.PathElement()
path.set("d", core.polylines_to_d(convert(polylines)))
path.style = style
path.label = label
layer.add(path)
def draw_guides(self, centers, scale, ox, oy):
"""Gabarits de pose : contour de chaque piece et croix passant par son centre."""
size = self.options.marker_size
common.remove_layers(self.svg, "guides")
layer = common.new_layer(_("Marker placement guides"), "guides")
self.svg.add(layer)
style = inkex.Style({"fill": "none", "stroke": "#ff0000",
"stroke-width": str(0.1 * scale)})
convert = self.converter(scale, ox, oy)
for index, center in enumerate(centers):
label = _("Origin marker") if index == core.ORIGIN_MARKER else _("Marker")
self.add_lines(layer, core.guide_lines(center, size), style, convert, label)
def print_sheet(self):
"""Feuille A4 : les 4 reperes en grille a decouper, legendes et barres de 100 mm."""
opt = self.options
size = opt.marker_size
centers = core.sheet_layout(size, margin=SHEET_MARGIN)
if centers is None:
inkex.errormsg(_("These markers are too large for an A4 sheet: reduce the "
"marker size, or engrave them directly on the bed."))
return
if not (80 <= opt.print_x <= 120 and 80 <= opt.print_y <= 120):
inkex.errormsg(_("The measured bar lengths must be between 80 and 120 mm."))
return
width, height = core.A4
# La feuille impose sa page : c'est elle que l'on imprime a 100 %.
scale, ox, oy = common.prepare_page(self.svg, width, height, True)
common.remove_layers(self.svg, "sheet")
layer = common.new_layer(_("Calibration markers (print)"), "sheet")
self.svg.add(layer)
# Correction d'imprimante : tout le dessin est agrandi autour du centre
# de la page, pour que les barres ressortent a 100 mm une fois imprimees.
fx, fy = core.print_correction(opt.print_x, opt.print_y)
convert = self.converter(scale, ox, oy, (fx, fy), (width / 2.0, height / 2.0))
def text(x, y, content, font=3.5, bold=False, anchor="start"):
px, py = convert([[(x, y)]])[0][0]
node = inkex.TextElement()
node.set("x", common.fmt(px))
node.set("y", common.fmt(py))
node.text = content
node.style = inkex.Style({
"font-family": "sans-serif", "font-size": common.fmt(font * fy * scale),
"font-weight": "bold" if bold else "normal", "text-anchor": anchor,
"fill": "#000000"})
layer.add(node)
m = SHEET_MARGIN
text(m, m + 7, _("Calibration markers - print at 100 %"), 6, True)
text(m, m + 15, _("Print at actual size (no \"fit to page\"), then check that "
"both bars measure 100 mm."))
text(m, m + 21, _("Cut along the dashed lines and stick each piece outside a "
"corner of the honeycomb, its inner corner on that corner."))
line = _("Marker size: {:g} mm").format(size)
if (fx, fy) != (1.0, 1.0):
line += " - " + _("printer correction: X {:.1f} %, Y {:.1f} %").format(
100 * fx, 100 * fy)
text(m, m + 27, line)
cut = inkex.Style({"fill": "none", "stroke": "#868e96",
"stroke-width": str(0.2 * scale),
"stroke-dasharray": "{0},{0}".format(common.fmt(1.5 * scale))})
black = inkex.Style({"fill": "none", "stroke": "#000000",
"stroke-width": str(0.3 * scale)})
names = [_("Top left"), _("Top right"), _("Bottom right"),
_("Origin - bottom left")]
half = core.piece_side(size) / 2.0
for index, center in enumerate(centers):
origin = index == core.ORIGIN_MARKER
self.add_lines(layer, [core.piece_outline(center, size)], cut, convert,
_("Cutting line"))
self.add_lines(layer, core.piece_ticks(center, size), black, convert,
_("Alignment ticks"))
self.add_marker(layer, center, origin, convert)
text(center[0], center[1] + half + 5, names[index], 3.2, origin, "middle")
# Deux barres : une imprimante peut reduire differemment en X et en Y.
bar_y = height - m - 6
self.add_lines(layer, core.scale_bar((m, bar_y)), black, convert,
_("Scale bar X"))
text(m + 104, bar_y, _("100 mm (X)"), 3.5, True)
bar_x = width - m + 4
top = m + 45
self.add_lines(layer, core.scale_bar((bar_x, top), vertical=True), black, convert,
_("Scale bar Y"))
text(bar_x, top + 106, _("100 mm (Y)"), 3.5, True, "end")
if __name__ == "__main__":
BoardPhotoMarkers().run()
+129
View File
@@ -0,0 +1,129 @@
# coding=utf-8
"""
Recuperation de la photo sur une machine distante (serveur HTTP de capture).
Le serveur (par exemple un petit serveur Flask sur la machine qui porte la
camera) expose :
- /capture : prend une nouvelle photo et la renvoie (image/jpeg) ;
- /old : renvoie la derniere photo prise, sans en prendre de nouvelle.
Bibliotheque standard seulement (urllib), sans dependance a inkex.
"""
import http.client
import socket
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit, urlunsplit
from urllib.request import ProxyHandler, Request, build_opener
DEFAULT_PORT = 5000
ENDPOINTS = {"capture": "/capture", "old": "/old"}
MAX_BYTES = 64 * 1024 * 1024 # garde-fou : une photo ne depasse pas 64 Mo
class RemoteError(Exception):
"""Echec de la recuperation ; `reason` est un code court, `detail` le message."""
def __init__(self, reason, detail=""):
Exception.__init__(self, reason)
self.reason = reason
self.detail = detail
def remote_url(host, port=DEFAULT_PORT, endpoint="capture"):
"""URL de la photo : accepte « 192.168.1.20 », « 192.168.1.20:5000 » ou une URL.
Un port ecrit dans l'adresse l'emporte sur `port` ; le chemin eventuel
de l'adresse est remplace par celui du point d'acces choisi.
"""
text = (host or "").strip()
if not text:
raise RemoteError("no_host")
if endpoint not in ENDPOINTS:
raise RemoteError("bad_endpoint", endpoint)
if "://" not in text:
if text.count(":") > 1 and not text.startswith("["):
text = "[{}]".format(text) # IPv6 nue : « fe80::1 »
text = "http://" + text
parts = urlsplit(text)
try:
explicit_port = parts.port
except ValueError:
raise RemoteError("bad_host", host)
hostname = parts.hostname
if not hostname or parts.scheme not in ("http", "https"):
raise RemoteError("bad_host", host)
if ":" in hostname: # IPv6 : crochets obligatoires
hostname = "[{}]".format(hostname)
netloc = "{}:{}".format(hostname, explicit_port or int(port))
return urlunsplit((parts.scheme, netloc, ENDPOINTS[endpoint], "", ""))
def _read_limited(response, chunk=256 * 1024):
"""Lit la reponse par blocs, jusqu'a MAX_BYTES + 1 octets au plus.
Un read(MAX_BYTES + 1) allouerait d'emblee un tampon de 64 Mo : la
lecture par blocs borne la memoire a la taille reelle de la photo.
"""
parts, total = [], 0
while total <= MAX_BYTES:
block = response.read(chunk)
if not block:
break
parts.append(block)
total += len(block)
return b"".join(parts)
def _fetch_once(url, timeout):
"""Une tentative : ouverture (erreurs de connexion) puis lecture (coupures)."""
opener = build_opener(ProxyHandler({}))
request = Request(url, headers={"User-Agent": "Inkscape board_photo"})
try:
response = opener.open(request, timeout=timeout)
except HTTPError as error:
# Le serveur explique l'echec dans le corps (« Error: Could not access
# the camera ») : on le fait suivre a l'utilisateur.
body = error.read(500).decode("utf-8", "replace").strip()
raise RemoteError("http", "{} {}".format(error.code, body).strip())
except (socket.timeout, TimeoutError):
raise RemoteError("timeout", url)
except URLError as error:
if isinstance(error.reason, (socket.timeout, TimeoutError)):
raise RemoteError("timeout", url)
raise RemoteError("unreachable", str(error.reason))
except OSError as error:
raise RemoteError("unreachable", str(error))
# Connexion etablie : une erreur a partir d'ici est une transmission
# interrompue (reseau instable, coupure), pas une machine injoignable.
with response:
content_type = response.headers.get_content_type()
expected = response.headers.get("Content-Length")
try:
data = _read_limited(response)
except (OSError, http.client.HTTPException) as error:
raise RemoteError("interrupted", str(error) or type(error).__name__)
if len(data) > MAX_BYTES:
raise RemoteError("too_large", url)
if expected and expected.isdigit() and len(data) < int(expected):
raise RemoteError("interrupted", "{} / {}".format(len(data), expected))
if not content_type.startswith("image/"):
text = data[:200].decode("utf-8", "replace").strip()
raise RemoteError("not_image", text)
return data
def fetch_photo(url, timeout=20.0, retries=1):
"""Telecharge la photo ; renvoie ses octets ou leve RemoteError.
Les proxys du systeme sont ignores : la camera est sur le reseau local,
un proxy d'entreprise ne saurait pas la joindre. Une transmission
interrompue est retentee `retries` fois ; les autres erreurs (machine
injoignable, erreur du serveur) sont remontees tout de suite.
"""
for attempt in range(retries + 1):
try:
return _fetch_once(url, timeout)
except RemoteError as error:
if error.reason != "interrupted" or attempt == retries:
raise
+521
View File
@@ -0,0 +1,521 @@
# coding=utf-8
"""
Traitement d'image de l'extension « Board photo », sans dependance a inkex.
Detection des reperes de calibration, redressement de la photo et
vectorisation de la planche. Dependances : numpy et Pillow, tous deux
fournis avec le Python d'Inkscape 1.x (pas d'OpenCV ni de scipy : les
composantes connexes sont calculees ici, par plages de pixels).
Memes conventions que board_photo_core : millimetres, repere SVG (y vers le
bas), coordonnees image continues (centre du pixel (r, c) en (c+0.5, r+0.5)).
"""
import io
import itertools
import math
import numpy as np
from PIL import Image, ImageFilter, ImageOps
import board_photo_core as core
# Photo reduite a ce cote maximal pour la recherche des reperes (rapide, et
# le centre est ensuite affine en pleine resolution).
SEARCH_SIDE = 1600
# Passes du seuil adaptatif : (diviseur du cote de l'image donnant le rayon
# du voisinage, ecart de gris). La premiere convient aux reperes bien visibles ;
# les suivantes, plus locales, aux petits reperes (photo basse resolution ou
# prise de loin) colles a des pieces sombres qui assombrissent le voisinage.
ADAPTIVE_PASSES = ((12, 20), (32, 20), (32, 10), (64, 20), (64, 10))
# Moment d'inertie normalise (Ixx + Iyy) / aire^2 : 1/6 pour un carre, quelle
# que soit sa taille ; une perspective moderee le change peu.
SQUARE_MOMENT = 1.0 / 6.0
# Ecart minimal (niveaux de gris) entre planche et fond pour vectoriser.
MIN_CONTRAST = 25
class MarkerError(Exception):
"""Reperes introuvables ; `reason` est un code court, `found` le nombre vu."""
def __init__(self, reason, found=0):
Exception.__init__(self, reason)
self.reason = reason
self.found = found
# --------------------------------------------------------------------------
# Chargement
# --------------------------------------------------------------------------
def load_photo(source):
"""Ouvre une photo (chemin ou octets), redressee selon son EXIF, en RVB."""
if isinstance(source, (bytes, bytearray)):
source = io.BytesIO(source)
image = Image.open(source)
image = ImageOps.exif_transpose(image)
return image.convert("RGB")
def gray_array(image):
"""Niveaux de gris (0-255) en tableau numpy uint8."""
return np.asarray(image.convert("L"), dtype=np.uint8)
def encode_image(image, fmt="JPEG", quality=90):
"""Octets d'une image PIL (JPEG par defaut), pour l'incorporer au SVG."""
buffer = io.BytesIO()
if fmt == "JPEG":
image.convert("RGB").save(buffer, "JPEG", quality=int(quality), optimize=True)
else:
image.save(buffer, fmt)
return buffer.getvalue()
# --------------------------------------------------------------------------
# Composantes connexes (par plages de pixels, vectorise)
# --------------------------------------------------------------------------
def label_components(mask, connectivity=4):
"""Etiquette les composantes connexes d'un masque booleen 2D.
Renvoie (labels, count, areas) : image d'etiquettes int32 (0 = fond,
1..count), nombre de composantes et aire de chacune (areas[0] = 0).
Travaille sur les plages horizontales de pixels, bien moins nombreuses
que les pixels : c'est assez rapide sans scipy.
"""
mask = np.asarray(mask, dtype=bool)
h, w = mask.shape
stride = w + 2
padded = np.zeros((h, w + 2), dtype=np.int8)
padded[:, 1:-1] = mask
diff = np.diff(padded, axis=1)
rows, starts = np.nonzero(diff == 1)
_rows_end, ends = np.nonzero(diff == -1) # meme ordre que les debuts
count_runs = len(rows)
if count_runs == 0:
return np.zeros((h, w), dtype=np.int32), 0, np.zeros(1)
# Plages de la ligne precedente qui touchent chaque plage : recherche
# dichotomique sur des cles (ligne, colonne) globalement triees.
k = 1 if connectivity == 8 else 0
start_keys = rows * stride + starts
end_keys = rows * stride + ends
lo = np.searchsorted(end_keys, (rows - 1) * stride + starts - k, side="right")
hi = np.searchsorted(start_keys, (rows - 1) * stride + ends + k, side="left")
counts = np.clip(hi - lo, 0, None)
total = int(counts.sum())
if total:
pi = np.repeat(np.arange(count_runs), counts)
offsets = np.arange(total) - np.repeat(np.cumsum(counts) - counts, counts)
pj = np.repeat(lo, counts) + offsets
else:
pi = pj = np.zeros(0, dtype=np.int64)
# Fusion par accrochage au plus petit representant + compression des
# chemins, jusqu'a stabilite (quelques iterations).
parent = np.arange(count_runs)
while True:
ri, rj = parent[pi], parent[pj]
low = np.minimum(ri, rj)
new = parent.copy()
np.minimum.at(new, ri, low)
np.minimum.at(new, rj, low)
while True:
jumped = new[new]
if np.array_equal(jumped, new):
break
new = jumped
if np.array_equal(new, parent):
break
parent = new
roots, run_labels = np.unique(parent, return_inverse=True)
run_labels = run_labels.astype(np.int64) + 1
count = len(roots)
lengths = ends - starts
areas = np.bincount(run_labels, weights=lengths, minlength=count + 1)
# Peinture des plages : +label au debut, -label a la fin, puis somme cumulee.
paint = np.zeros((h, w + 1), dtype=np.int64)
np.add.at(paint, (rows, starts), run_labels)
np.add.at(paint, (rows, ends), -run_labels)
labels = np.cumsum(paint, axis=1)[:, :w].astype(np.int32)
return labels, count, areas
def component_boxes(labels, count):
"""Boites englobantes (r0, c0, r1, c1 exclus) de chaque etiquette 1..count."""
rr, cc = np.nonzero(labels)
lab = labels[rr, cc]
r0 = np.full(count + 1, labels.shape[0])
c0 = np.full(count + 1, labels.shape[1])
r1 = np.zeros(count + 1, dtype=np.int64)
c1 = np.zeros(count + 1, dtype=np.int64)
np.minimum.at(r0, lab, rr)
np.minimum.at(c0, lab, cc)
np.maximum.at(r1, lab, rr + 1)
np.maximum.at(c1, lab, cc + 1)
return r0, c0, r1, c1
def fill_holes(mask, connectivity=8, min_area=0):
"""Bouche les trous d'un masque.
Renvoie (masque plein, [masques des trous d'au moins `min_area` pixels]).
Les petits trous sont bouches mais pas renvoyes : on evite de construire
un masque par grain de bruit.
"""
mask = np.asarray(mask, dtype=bool)
labels, count, areas = label_components(~mask, connectivity)
border = set(np.concatenate([labels[0], labels[-1], labels[:, 0],
labels[:, -1]]).tolist())
inner = np.array([k not in border for k in range(count + 1)])
inner[0] = False
filled = mask | inner[labels]
holes = [labels == k for k in np.nonzero(inner & (areas >= min_area))[0].tolist()]
return filled, holes
def otsu_threshold(values):
"""Seuil d'Otsu (0-255) d'un ensemble de niveaux de gris."""
hist = np.bincount(np.asarray(values, dtype=np.uint8).ravel(), minlength=256)
hist = hist.astype(float)
total = hist.sum()
if total == 0:
return 128
levels = np.arange(256)
weight0 = np.cumsum(hist)
weight1 = total - weight0
sum0 = np.cumsum(hist * levels)
mean0 = np.divide(sum0, weight0, out=np.zeros(256), where=weight0 > 0)
mean1 = np.divide(sum0[-1] - sum0, weight1, out=np.zeros(256), where=weight1 > 0)
between = weight0 * weight1 * (mean0 - mean1) ** 2
return int(np.argmax(between))
# --------------------------------------------------------------------------
# Detection des reperes de calibration
# --------------------------------------------------------------------------
def _shape_measures(filled):
"""Barycentre (x, y continus), moment normalise et rapport d'allongement."""
rr, cc = np.nonzero(filled)
area = float(len(rr))
x, y = cc + 0.5, rr + 0.5
mx, my = x.mean(), y.mean()
cov = np.cov(np.vstack([x, y]), bias=True) if area > 1 else np.eye(2)
eig = np.linalg.eigvalsh(cov)
moment = (cov[0, 0] + cov[1, 1]) / area if area else 0.0
ratio = eig[0] / eig[1] if eig[1] > 0 else 0.0
return (mx, my), moment, ratio, area
def analyse_marker(mask):
"""Examine une composante sombre isolee (masque recadre).
Renvoie un dictionnaire (barycentre, nombre de pastilles, aire pleine,
ecart au carre ideal) si la forme ressemble a un repere, None sinon.
"""
filled, holes = fill_holes(mask)
(cx, cy), moment, ratio, area = _shape_measures(filled)
if area < 36:
return None
rows, cols = filled.shape
if area / float(rows * cols) < 0.42 or ratio < 0.45:
return None
if not 0.14 <= moment <= 0.20:
return None
dots = []
for hole in holes:
hole_area = float(hole.sum())
if hole_area < 0.008 * area:
continue
(hx, hy), _m, _r, _a = _shape_measures(hole)
if math.hypot(hx - cx, hy - cy) > 0.4 * math.sqrt(area):
return None
dots.append(hole_area)
if len(dots) not in (1, 2):
return None
if not 0.02 <= sum(dots) / area <= 0.2:
return None
return {"center": (cx, cy), "dots": len(dots), "area": area,
"score": abs(moment - SQUARE_MOMENT)}
def _dark_mask_adaptive(gray, radius, offset=20):
"""Pixels nettement plus sombres que leur voisinage (seuil adaptatif)."""
image = Image.fromarray(gray)
local = np.asarray(image.filter(ImageFilter.BoxBlur(radius)), dtype=np.int16)
return gray.astype(np.int16) < local - offset
def _best_four(candidates):
"""Parmi les candidats, les 4 qui forment le plus grand quadrilatere convexe.
Les reperes ont tous la meme taille : on ecarte les combinaisons dont les
aires varient de plus d'un facteur 4 (perspective forte comprise).
"""
pool = sorted(candidates, key=lambda c: c["score"])[:12]
best, best_area = None, 0.0
for combo in itertools.combinations(pool, 4):
areas = [c["area"] for c in combo]
if max(areas) > 4 * min(areas):
continue
ordered = core.order_corners([c["center"] for c in combo])
if not core.is_convex_quad(ordered):
continue
quad = abs(core.ring_area(ordered))
if quad > best_area:
best, best_area = combo, quad
return list(best) if best else None
def _refine(gray, center, half):
"""Affine un repere en pleine resolution autour de `center` (seuil d'Otsu local)."""
h, w = gray.shape
cx, cy = center
r0, r1 = max(0, int(cy - half)), min(h, int(cy + half) + 1)
c0, c1 = max(0, int(cx - half)), min(w, int(cx + half) + 1)
crop = gray[r0:r1, c0:c1]
if crop.size == 0:
return None
dark = crop < otsu_threshold(crop)
labels, count, areas = label_components(dark, 8)
if not count:
return None
# Le centre tombe souvent sur une pastille claire : on essaie, de la plus
# petite a la plus grande, les composantes sombres dont la boite englobe
# le centre, et l'on garde la premiere qui a la forme d'un repere.
lr, lc = cy - r0, cx - c0
b0, a0, b1, a1 = component_boxes(labels, count)
around = [k for k in range(1, count + 1)
if b0[k] <= lr < b1[k] and a0[k] <= lc < a1[k]]
for k in sorted(around, key=lambda k: areas[k]):
box = labels[b0[k]:b1[k], a0[k]:a1[k]] == k
info = analyse_marker(box)
if info is not None:
x, y = info["center"]
info["center"] = (x + a0[k] + c0, y + b0[k] + r0)
return info
return None
def _same_marker(a, b):
"""Vrai si deux candidats designent le meme repere (passes successives)."""
(ax, ay), (bx, by) = a["center"], b["center"]
return math.hypot(ax - bx, ay - by) < 0.5 * math.sqrt(min(a["area"], b["area"]))
def _marker_candidates(small, factor, divisor, offset):
"""Formes de repere trouvees par une passe du seuil adaptatif.
`small` : photo reduite d'un facteur `factor` ; les centres et aires
renvoyes sont ramenes a la pleine resolution.
"""
sh, sw = small.shape
dark = _dark_mask_adaptive(small, max(4, max(sh, sw) // divisor), offset)
labels, count, areas = label_components(dark, 8)
if not count:
return []
min_area = 64
max_area = sh * sw / 40.0
r0, c0, r1, c1 = component_boxes(labels, count)
candidates = []
for k in np.nonzero((areas >= min_area) & (areas <= max_area))[0].tolist():
bh, bw = r1[k] - r0[k], c1[k] - c0[k]
if bh < 8 or bw < 8 or not 0.4 <= bw / float(bh) <= 2.5:
continue
crop = labels[r0[k]:r1[k], c0[k]:c1[k]] == k
info = analyse_marker(crop)
if info is None:
continue
x, y = info["center"]
info["center"] = ((x + c0[k]) / factor, (y + r0[k]) / factor)
info["area"] /= factor * factor
info["half"] = 0.9 * max(bh, bw) / factor
candidates.append(info)
return candidates
def detect_markers(gray):
"""Trouve les 4 reperes dans une photo (tableau de gris pleine resolution).
Renvoie un dictionnaire : `points` (4 centres en coordonnees image,
ordre HG, HD, BD, BG du repere SVG), `areas` (aires pleines en pixels),
`oriented` (vrai si le repere origine a fixe l'orientation). Leve
MarkerError sinon.
"""
h, w = gray.shape
factor = min(1.0, SEARCH_SIDE / float(max(h, w)))
if factor < 1.0:
small_img = Image.fromarray(gray).resize(
(max(1, round(w * factor)), max(1, round(h * factor))), Image.BOX)
small = np.asarray(small_img, dtype=np.uint8)
else:
small = gray
candidates = []
for divisor, offset in ADAPTIVE_PASSES:
for info in _marker_candidates(small, factor, divisor, offset):
if not any(_same_marker(info, other) for other in candidates):
candidates.append(info)
chosen = _best_four(candidates) if len(candidates) >= 4 else None
if chosen is not None:
break
if len(candidates) < 4:
raise MarkerError("too_few", len(candidates))
if chosen is None:
raise MarkerError("layout", len(candidates))
refined = []
for info in chosen:
better = _refine(gray, info["center"], info["half"]) if factor < 1.0 else None
refined.append(better or info)
return orient_points([r["center"] for r in refined],
[r["dots"] for r in refined],
[r["area"] for r in refined])
def orient_points(points, dots, areas=None):
"""Range les centres en HG, HD, BD, BG et fixe l'orientation par le repere origine."""
if areas is None:
areas = [0.0] * len(points)
items = list(zip(points, dots, areas))
angle_order = core.order_corners(points)
items.sort(key=lambda item: angle_order.index(tuple(map(float, item[0]))))
origins = [k for k, item in enumerate(items) if item[1] == 2]
oriented = len(origins) == 1
if oriented:
items = core.rotate_to_origin(items, origins[0])
return {"points": [item[0] for item in items],
"dots": [item[1] for item in items],
"areas": [item[2] for item in items],
"oriented": oriented}
def dots_near(gray, points):
"""Nombre de pastilles du repere autour de chaque point (placement manuel).
La taille de recherche vient de l'ecart entre points ; renvoie None pour
un point ou aucun repere n'est reconnu.
"""
pts = np.asarray(points, dtype=float)
spacing = min(math.hypot(*(pts[i] - pts[j]))
for i in range(len(pts)) for j in range(i + 1, len(pts)))
half = max(10.0, spacing / 8.0)
result = []
for point in points:
info = _refine(gray, point, half)
result.append(info["dots"] if info else None)
return result
# --------------------------------------------------------------------------
# Redressement
# --------------------------------------------------------------------------
def output_size(width_mm, height_mm, resolution):
"""Taille en pixels de l'image redressee (au moins 1 x 1)."""
return (max(1, int(round(width_mm * resolution))),
max(1, int(round(height_mm * resolution))))
def rectify(image, image_to_mm, width_mm, height_mm, resolution, fill=(255, 255, 255),
offset=(0.0, 0.0)):
"""Photo redressee couvrant exactement le rectangle `width_mm` x `height_mm`
dont le coin haut gauche est en `offset` (mm, repere SVG ; zone de travail
par defaut).
`image_to_mm` : homographie coordonnees image -> millimetres (repere SVG).
Le pixel (i, j) du resultat couvre offset + [j, j+1] x [i, i+1] / resolution mm.
Renvoie (image, masque des pixels couverts par la photo).
"""
out_w, out_h = output_size(width_mm, height_mm, resolution)
# Pillow attend l'application inverse : sortie (pixels) -> entree (pixels).
to_mm = np.array([[width_mm / out_w, 0.0, offset[0]],
[0.0, height_mm / out_h, offset[1]],
[0.0, 0.0, 1.0]])
inverse = np.linalg.inv(image_to_mm) @ to_mm
inverse = inverse / inverse[2, 2]
coeffs = tuple(inverse.ravel()[:8].tolist())
result = image.transform((out_w, out_h), Image.PERSPECTIVE, coeffs,
Image.BICUBIC, fillcolor=fill)
coverage = Image.new("L", image.size, 255).transform(
(out_w, out_h), Image.PERSPECTIVE, coeffs, Image.NEAREST, fillcolor=0)
return result, np.asarray(coverage) > 0
# --------------------------------------------------------------------------
# Vectorisation de la planche
# --------------------------------------------------------------------------
def _morph(mask, size, operation):
"""Ouverture ('open') ou fermeture ('close') par un carre de cote `size` px."""
if size < 3:
return mask
image = Image.fromarray(mask.astype(np.uint8) * 255)
first, second = ((ImageFilter.MinFilter, ImageFilter.MaxFilter) if operation == "open"
else (ImageFilter.MaxFilter, ImageFilter.MinFilter))
image = image.filter(first(size)).filter(second(size))
return np.asarray(image) > 127
def extract_board(gray, valid, resolution, lighter=True, threshold=0,
smoothing=0.5, min_hole_area=4.0, simplify=0.2, exclude=()):
"""Contour et trous de la planche sur une image redressee (grille en mm).
`valid` : pixels couverts par la photo ; `exclude` : rectangles
(x0, y0, x1, y1) en mm ignores (zones des reperes). Renvoie un
dictionnaire : `rings` (anneau exterieur puis trous, en mm), `holes`
(nombre), `threshold` (seuil utilise), `area` (mm2) ; None si aucune
planche n'est trouvee.
"""
gray = np.asarray(gray, dtype=np.uint8)
valid = np.asarray(valid, dtype=bool).copy()
h, w = gray.shape
for x0, y0, x1, y1 in exclude:
c0, c1 = max(0, int(math.floor(x0 * resolution))), min(w, int(math.ceil(x1 * resolution)))
r0, r1 = max(0, int(math.floor(y0 * resolution))), min(h, int(math.ceil(y1 * resolution)))
valid[r0:r1, c0:c1] = False
if not valid.any():
return None
values = gray[valid]
level = int(threshold) if threshold and threshold > 0 else otsu_threshold(values)
# Sans contraste entre les deux classes, pas de planche discernable (photo
# uniforme, ou seuil manuel hors de la plage des gris).
low, high = values[values <= level], values[values > level]
if not len(low) or not len(high) or float(high.mean()) - float(low.mean()) < MIN_CONTRAST:
return None
board = (gray > level) if lighter else (gray <= level)
board &= valid
size = 2 * int(round(smoothing * resolution)) + 1
board = _morph(_morph(board, size, "open"), size, "close")
labels, count, areas = label_components(board, 4)
if not count:
return None
main = int(np.argmax(areas))
pixel_area = 1.0 / (resolution * resolution)
if areas[main] * pixel_area < 100.0: # moins de 1 cm2 : pas de planche
return None
rr, cc = np.nonzero(labels == main)
r0, r1 = rr.min(), rr.max() + 1
c0, c1 = cc.min(), cc.max() + 1
# Marge d'un pixel pour que le fond exterieur touche toujours le bord du cadre.
comp = np.pad(labels[r0:r1, c0:c1] == main, 1)
outer_mask, kept = fill_holes(comp, 8, min_area=min_hole_area / pixel_area)
def to_mm(ring):
return [((x + c0 - 1) / resolution, (y + r0 - 1) / resolution) for x, y in ring]
def main_ring(mask):
rings = core.mask_to_rings(mask)
ring = max(rings, key=lambda r: abs(core.ring_area(r)))
return core.simplify_ring(to_mm(ring), simplify)
rings = [main_ring(outer_mask)] + [main_ring(hole) for hole in kept]
area = abs(core.ring_area(rings[0])) - sum(abs(core.ring_area(r)) for r in rings[1:])
return {"rings": rings, "holes": len(kept), "threshold": level, "area": area}
+115
View File
@@ -0,0 +1,115 @@
<#
.SYNOPSIS
Déploie l'extension « Photo de planche » (2 entrées de menu) dans Inkscape.
.DESCRIPTION
Copie les deux entrées de menu (board_photo_import, board_photo_markers :
.inx + .py), les modules board_photo_core,
board_photo_vision, board_photo_common et board_photo_remote, le schéma de l'onglet
« Diagram » (images\parameters_en.png) et les traductions
compilées (locale\<langue>\LC_MESSAGES\board_photo.mo) dans un
sous-dossier dédié du répertoire des extensions utilisateur d'Inkscape
(Inkscape explore récursivement ce répertoire). Refuse de s'exécuter si
Inkscape est ouvert : les extensions ne sont chargées qu'au démarrage.
.PARAMETER ExtensionsDir
Répertoire des extensions Inkscape. Par défaut : %APPDATA%\inkscape\extensions
.PARAMETER FolderName
Nom du sous-dossier de l'extension. Par défaut : Planche photo
.PARAMETER Uninstall
Supprime le sous-dossier de l'extension au lieu de le créer.
.PARAMETER Force
Déploie même si Inkscape est en cours d'exécution.
.EXAMPLE
.\deploy.ps1
.\deploy.ps1 -Uninstall
.\deploy.ps1 -FolderName 'autre-nom'
#>
[CmdletBinding()]
param(
[string] $ExtensionsDir = (Join-Path $env:APPDATA 'inkscape\extensions'),
[string] $FolderName = 'Planche photo',
[switch] $Uninstall,
[switch] $Force
)
$ErrorActionPreference = 'Stop'
$files = @(
'board_photo_import.inx', 'board_photo_import.py',
'board_photo_markers.inx', 'board_photo_markers.py',
'board_photo_core.py', 'board_photo_vision.py', 'board_photo_common.py',
'board_photo_remote.py',
'images\parameters_en.png'
)
$localeDir = 'locale'
$source = $PSScriptRoot
$destination = Join-Path $ExtensionsDir $FolderName
# --- Inkscape doit être fermé : les extensions sont lues au démarrage ---------
$running = Get-Process -Name 'inkscape' -ErrorAction SilentlyContinue
if ($running -and -not $Force) {
Write-Error "Inkscape est ouvert. Fermez-le puis relancez le script (ou utilisez -Force)."
exit 1
}
# --- Désinstallation ---------------------------------------------------------
if ($Uninstall) {
if (Test-Path -LiteralPath $destination) {
Remove-Item -LiteralPath $destination -Recurse -Force
Write-Host "Supprimé : $destination" -ForegroundColor Green
}
else {
Write-Host "Rien à supprimer : $destination n'existe pas." -ForegroundColor Yellow
}
exit 0
}
# --- Vérification des sources ------------------------------------------------
$missing = $files | Where-Object { -not (Test-Path -LiteralPath (Join-Path $source $_)) }
if (-not (Test-Path -LiteralPath (Join-Path $source $localeDir))) {
$missing = @($missing) + "$localeDir\ (lancer : python i18n.py)"
}
if ($missing) {
Write-Error "Fichier(s) introuvable(s) dans $source : $($missing -join ', ')"
exit 1
}
# --- Copie -------------------------------------------------------------------
if (-not (Test-Path -LiteralPath $destination)) {
New-Item -ItemType Directory -Path $destination -Force | Out-Null
Write-Host "Dossier créé : $destination"
}
foreach ($file in $files) {
$from = Join-Path $source $file
$to = Join-Path $destination $file
$action = if (Test-Path -LiteralPath $to) { 'remplacé' } else { 'copié ' }
New-Item -ItemType Directory -Path (Split-Path $to) -Force | Out-Null
Copy-Item -LiteralPath $from -Destination $to -Force
Write-Host " $action $file"
}
# Traductions : le dossier est remplacé en entier (langue retirée => supprimée)
$localeTo = Join-Path $destination $localeDir
if (Test-Path -LiteralPath $localeTo) {
Remove-Item -LiteralPath $localeTo -Recurse -Force
}
Copy-Item -LiteralPath (Join-Path $source $localeDir) -Destination $localeTo -Recurse
$languages = Get-ChildItem -LiteralPath $localeTo -Directory | ForEach-Object Name
Write-Host " copié $localeDir\ ($($languages -join ', '))"
# Le cache Python d'une version précédente peut masquer les fichiers copiés
$pycache = Join-Path $destination '__pycache__'
if (Test-Path -LiteralPath $pycache) {
Remove-Item -LiteralPath $pycache -Recurse -Force
}
Write-Host ""
Write-Host "Extension déployée dans $destination" -ForegroundColor Green
Write-Host "Redémarrez Inkscape, puis : Extensions > AlexDesign > Photo de planche : ..."
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 674 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

+358
View File
@@ -0,0 +1,358 @@
#!/usr/bin/env python3
# coding=utf-8
"""
Genere le schema explicatif des parametres de l'extension.
python docs/schema_parametres.py # les deux versions
python docs/schema_parametres.py fr # docs/parametres.svg + .png (README)
python docs/schema_parametres.py en # docs/parameters_en.svg
# + images/parameters_en.png (onglet
# « Diagram » de la boite de dialogue)
Les formes sont calculees par board_photo_core (memes fonctions que l'extension :
disposition et dessin des reperes, homographie), le schema reste donc fidele au
resultat reel. L'export PNG passe par inkscape.com, qui attend la fin de
l'export (contrairement au raccourci Chocolatey « inkscape »).
"""
import math
import os
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, ROOT)
import board_photo_core as core # noqa: E402
W, H = 1400, 1080 # 4 panneaux de 700 x 540
PW, PH = 700, 540
INK = "#343a40" # element principal
DIM = "#d9480f" # cotes
DIM2 = "#1971c2" # cotes secondaires
EDGE = "#212529" # contour des formes
FONT = "font-family:Arial,Helvetica,sans-serif"
INKSCAPE = [r"C:\Program Files\Inkscape\bin\inkscape.com", "/usr/bin/inkscape",
"/Applications/Inkscape.app/Contents/MacOS/inkscape"]
# Version par langue : textes, fichiers produits, largeur du PNG et agrandissement
# des textes (la version anglaise est affichee reduite dans la boite de dialogue :
# 900 px de large, textes x 1.25 pour rester lisibles).
VERSIONS = {
"fr": {
"svg": os.path.join(HERE, "parametres.svg"),
"png": os.path.join(HERE, "parametres.png"),
"png_width": 1400,
"font_scale": 1.0,
"text": {
"title1": "Zone de travail et repères",
"width": "Largeur", "height": "Hauteur",
"spacing_x": "Écart X", "spacing_y": "Écart Y",
"origin": "Origine (0, 0)",
"frame": "hors de portée de la laser",
"note1": ["Chaque pièce de papier touche un angle du nid d'abeille :",
"l'angle bas gauche est l'origine laser, l'écart vaut la",
"largeur (hauteur) + 2 × la taille des repères."],
"title2": "Repères à graver ou imprimer",
"ordinary": "Repère", "origin_marker": "Repère origine",
"size": "Taille", "light": "zone claire",
"note2": ["Gravés sur une plaque claire, ou imprimés (feuille A4),",
"découpés et collés sur leur gabarit de pose gravé."],
"title3": "Photo redressée à l'échelle",
"photo": "Photo (perspective)", "calibrated": "Page = zone de travail",
"note3": ["Les 4 repères donnent l'homographie : 1 mm sur la",
"photo = 1 mm dans le document (résolution en px/mm)."],
"title4": "Contour et trous",
"hole": "trou", "ignored": "ignoré (< aire mini)",
"note4": ["Contour et trous vectorisés (calque verrouillé),",
"pour placer les découpes sur la planche."],
},
},
"en": {
"svg": os.path.join(HERE, "parameters_en.svg"),
"png": os.path.join(ROOT, "images", "parameters_en.png"),
"png_width": 900,
"font_scale": 1.25,
"text": {
"title1": "Work area and markers",
"width": "Width", "height": "Height",
"spacing_x": "Spacing X", "spacing_y": "Spacing Y",
"origin": "Origin (0, 0)",
"frame": "out of the laser's reach",
"note1": ["Each paper piece touches a corner of the honeycomb:",
"bottom left = laser origin; spacing = width (height)",
"+ 2 x the marker size."],
"title2": "Markers to engrave or print",
"ordinary": "Marker", "origin_marker": "Origin marker",
"size": "Size", "light": "light area",
"note2": ["Engraved on a light plate, or printed (A4),",
"cut out and stuck on their placement guide."],
"title3": "Photo straightened to scale",
"photo": "Photo (perspective)", "calibrated": "Page = work area",
"note3": ["The 4 markers give the homography:",
"1 mm on the photo = 1 mm in the document."],
"title4": "Outline and holes",
"hole": "hole", "ignored": "ignored (< min area)",
"note4": ["Outline and holes vectorized (locked layer),",
"to place the cuts on the board."],
},
},
}
out = []
T = {}
FS = 1.0
def fmt(v):
return "{:.2f}".format(v).rstrip("0").rstrip(".")
def pts(polyline):
return " ".join("{},{}".format(fmt(x), fmt(y)) for x, y in polyline)
def polyline(points, color, width, extra=""):
out.append('<polyline points="{}" fill="none" stroke="{}" stroke-width="{}" '
'stroke-linejoin="miter" {}/>'.format(pts(points), color, fmt(width), extra))
def text(x, y, s, size=17, color=INK, anchor="start", weight="normal", halo=True):
style = "{};font-size:{}px;font-weight:{};fill:{}".format(
FONT, fmt(size * FS), weight, color)
if halo:
style += ";paint-order:stroke;stroke:#ffffff;stroke-width:5px;stroke-linejoin:round"
s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
out.append('<text x="{}" y="{}" text-anchor="{}" style="{}">{}</text>'.format(
fmt(x), fmt(y), anchor, style, s))
def note(x, y, lines):
"""Legende de bas de panneau, derniere ligne sur la ligne de base `y`."""
step = 22 * FS
for k, line in enumerate(lines):
text(x, y - (len(lines) - 1 - k) * step, line, size=16, halo=False)
def arrow_head(tip, direction, color, size=9):
ux, uy = direction
nx, ny = -uy, ux
base = (tip[0] - size * ux, tip[1] - size * uy)
out.append('<polygon points="{}" fill="{}"/>'.format(pts([
tip, (base[0] + 0.45 * size * nx, base[1] + 0.45 * size * ny),
(base[0] - 0.45 * size * nx, base[1] - 0.45 * size * ny)]), color))
def dimension(p, q, offset, label, color=DIM, label_pos=0.5, label_shift=18, size=17):
"""Cote entre p et q, decalee de `offset` perpendiculairement."""
dx, dy = q[0] - p[0], q[1] - p[1]
length = math.hypot(dx, dy)
ux, uy = dx / length, dy / length
nx, ny = -uy, ux
a = (p[0] + offset * nx, p[1] + offset * ny)
b = (q[0] + offset * nx, q[1] + offset * ny)
sign = 1 if offset >= 0 else -1
if offset:
for base, end in ((p, a), (q, b)):
polyline([(base[0] + sign * 4 * nx, base[1] + sign * 4 * ny),
(end[0] + sign * 6 * nx, end[1] + sign * 6 * ny)], color, 1,
'stroke-dasharray="3,3"')
polyline([a, b], color, 1.6)
arrow_head(a, (-ux, -uy), color)
arrow_head(b, (ux, uy), color)
lx = a[0] + label_pos * (b[0] - a[0]) + sign * label_shift * FS * nx
ly = a[1] + label_pos * (b[1] - a[1]) + sign * label_shift * FS * ny + 6 * FS
text(lx, ly, label, size=size, color=color, anchor="middle", weight="bold")
def panel_title(x, y, number, title):
text(x, y, "{} {}".format(number, title), size=22, weight="bold", halo=False)
def fill_rings(rings, fill, stroke="none", width=0, extra=""):
"""Chemin plein pair-impair a partir d'anneaux (liste de points)."""
d = " ".join("M " + " L ".join("{},{}".format(fmt(x), fmt(y)) for x, y in ring) + " Z"
for ring in rings)
out.append('<path d="{}" fill="{}" fill-rule="evenodd" stroke="{}" '
'stroke-width="{}" {}/>'.format(d, fill, stroke, fmt(width), extra))
# --------------------------------------------------------------------------
# Panneaux, numerotes 1 a 4, dessines avec les vraies fonctions de
# board_photo_core. Les reperes sont grossis pour rester lisibles.
# --------------------------------------------------------------------------
AREA = 400.0 # zone de travail du schema (mm)
ORIGIN, SPACING, SIZE = 45.0, 310.0, 40.0
BOARD = [(95.0, 110.0), (310.0, 95.0), (318.0, 300.0), (88.0, 312.0)]
HOLES = [((150.0, 170.0), 16.0), ((240.0, 215.0), 26.0), ((275.0, 140.0), 5.0)]
BOARD_FILL = "#e9d8b8"
BED = "#6c757d"
def work_area(transform, board=False, origin=ORIGIN, spacing=SPACING):
"""Zone de travail : fond, reperes (et planche) passes par `transform` (mm -> px)."""
def draw(rings, fill, stroke="none", width=0):
fill_rings([transform(ring) for ring in rings], fill, stroke, width)
draw([[(0, 0), (AREA, 0), (AREA, AREA), (0, AREA)]], BED, EDGE, 1.5)
centers = core.marker_layout(AREA, origin, origin, spacing, spacing)
for index, (cx, cy) in enumerate(centers):
draw([[(cx - SIZE, cy - SIZE), (cx + SIZE, cy - SIZE),
(cx + SIZE, cy + SIZE), (cx - SIZE, cy + SIZE)]], "#f8f9fa")
draw(core.marker_rings((cx, cy), SIZE, index == core.ORIGIN_MARKER), "#000000")
if board:
draw([BOARD] + [core.circle_ring(c, r) for c, r in HOLES], BOARD_FILL, EDGE, 1)
return centers
def affine(scale, ox, oy):
def transform(ring):
return core.scale_rings([ring], scale, (ox, oy))[0]
return transform
# Panneau 1 : reperes colles autour de la zone de travail (hors de portee de la
# laser), cas le plus courant ; le repere origine a donc des X, Y negatifs.
OUT_ORIGIN = -SIZE # piece (2 x SIZE) touchant l'angle
OUT_SPACING = AREA - 2 * OUT_ORIGIN
FRAME = "#ced4da"
def panel_1():
panel_title(30, 50, 1, T["title1"])
scale, ox, oy = 0.52, 215.0, 118.0
reach = -OUT_ORIGIN + SIZE + 6.0 # bord du cadre autour de la zone
frame = [(-reach, -reach), (AREA + reach, -reach), (AREA + reach, AREA + reach),
(-reach, AREA + reach)]
fill_rings(core.scale_rings([frame], scale, (ox, oy)), FRAME)
centers = work_area(affine(scale, ox, oy), origin=OUT_ORIGIN, spacing=OUT_SPACING)
def at(p):
return (ox + p[0] * scale, oy + p[1] * scale)
size = AREA * scale
tl, tr, br, bl = (at(c) for c in centers)
right, bottom = ox + size, oy + size
outer = reach * scale
text(ox + size / 2, oy - outer + 14, T["frame"], size=13, color=INK,
anchor="middle", halo=False)
dimension((ox, bottom), (right, bottom), outer + 46, T["width"], color=DIM2,
label_shift=10)
dimension((right, oy), (right, bottom), -outer - 16, T["height"], color=DIM2,
label_shift=44)
dimension(tl, tr, 46, T["spacing_x"], label_shift=-20)
dimension(tr, br, 46, T["spacing_y"], label_shift=52)
out.append('<circle cx="{}" cy="{}" r="6" fill="{}"/>'.format(
fmt(ox), fmt(bottom), DIM))
text(ox + 12, bottom - 12, T["origin"], size=16, color=DIM, weight="bold")
note(30, 522, T["note1"])
def panel_2():
x0 = PW
panel_title(x0 + 30, 50, 2, T["title2"])
side = 72.0
for k, (origin, label) in enumerate(((False, T["ordinary"]),
(True, T["origin_marker"]))):
cx, cy = x0 + 190 + k * 320, 260
# Zone claire conseillee : deux fois la taille du repere.
out.append('<rect x="{}" y="{}" width="{}" height="{}" fill="#f1f3f5" '
'stroke="{}" stroke-dasharray="6,4"/>'.format(
fmt(cx - side), fmt(cy - side), fmt(2 * side), fmt(2 * side), DIM2))
fill_rings(core.marker_rings((cx, cy), side, origin), "#000000")
text(cx, cy + side + 36, label, size=18, anchor="middle", weight="bold", halo=False)
text(cx - side + 6, cy + side - 10, T["light"], size=14, color=DIM2, halo=False)
dimension((cx - side / 2, cy - side / 2), (cx + side / 2, cy - side / 2), -24,
T["size"], label_shift=10)
note(x0 + 30, 520, T["note2"])
def panel_3():
y0 = PH
panel_title(30, y0 + 50, 3, T["title3"])
# Photo : zone de travail vue en perspective (homographie du noyau).
corners = [(0, 0), (AREA, 0), (AREA, AREA), (0, AREA)]
quad = [(62, y0 + 118), (290, y0 + 96), (306, y0 + 392), (40, y0 + 360)]
camera = core.homography(corners, quad)
work_area(lambda ring: core.apply_homography(camera, ring).tolist(), board=True)
text(172, y0 + 428, T["photo"], size=16, anchor="middle", halo=False)
polyline([(332, y0 + 250), (380, y0 + 250)], DIM, 3)
arrow_head((392, y0 + 250), (1, 0), DIM, 14)
scale = 0.66
work_area(affine(scale, 410, y0 + 110), board=True)
text(410 + AREA * scale / 2, y0 + 428, T["calibrated"], size=16, anchor="middle",
halo=False)
note(30, y0 + 520, T["note3"])
def panel_4():
x0, y0 = PW, PH
panel_title(x0 + 30, y0 + 50, 4, T["title4"])
scale = 1.5
ox, oy = x0 + 120 - 88 * scale, y0 + 80 - 95 * scale
def at(p):
return (ox + p[0] * scale, oy + p[1] * scale)
transform = affine(scale, ox, oy)
fill_rings([transform(r) for r in [BOARD] + [core.circle_ring(c, r)
for c, r in HOLES[:2]]],
BOARD_FILL, DIM2, 2.5)
# Petit trou sous l'aire minimale : ignore (bouche).
small = at(HOLES[2][0])
out.append('<circle cx="{}" cy="{}" r="{}" fill="#b08968"/>'.format(
fmt(small[0]), fmt(small[1]), fmt(HOLES[2][1] * scale)))
text(small[0], small[1] - 16, T["ignored"], size=14, anchor="middle")
hole = at(HOLES[1][0])
text(hole[0], hole[1] + 6, T["hole"], size=15, color=DIM2, anchor="middle",
halo=False)
note(x0 + 30, y0 + 520, T["note4"])
def export_png(svg_path, png_path, width):
exe = next((path for path in INKSCAPE if os.path.exists(path)), None)
if exe is None:
print("Inkscape introuvable : exporter {} a la main".format(svg_path))
return
os.makedirs(os.path.dirname(png_path), exist_ok=True)
subprocess.run([exe, svg_path, "--export-type=png",
"--export-width={}".format(width),
"--export-filename={}".format(png_path)],
check=True, stderr=subprocess.DEVNULL)
print(png_path)
def build(language):
global FS
version = VERSIONS[language]
out.clear()
T.clear()
T.update(version["text"])
FS = version["font_scale"]
out.append('<rect width="{}" height="{}" fill="#ffffff"/>'.format(W, H))
for x1, y1, x2, y2 in ((PW, 20, PW, H - 20), (20, PH, W - 20, PH)):
out.append('<line x1="{}" y1="{}" x2="{}" y2="{}" stroke="#dee2e6" '
'stroke-width="1.5"/>'.format(x1, y1, x2, y2))
panel_1()
panel_2()
panel_3()
panel_4()
svg = ('<?xml version="1.0" encoding="UTF-8"?>\n'
'<svg xmlns="http://www.w3.org/2000/svg" width="{0}" height="{1}" '
'viewBox="0 0 {0} {1}">\n{2}\n</svg>\n').format(W, H, "\n".join(out))
with open(version["svg"], "w", encoding="utf-8", newline="\n") as handle:
handle.write(svg)
print(version["svg"])
export_png(version["svg"], version["png"], version["png_width"])
def main(argv):
languages = argv or sorted(VERSIONS)
for language in languages:
build(language)
if __name__ == "__main__":
main(sys.argv[1:])
+308
View File
@@ -0,0 +1,308 @@
#!/usr/bin/env python3
# coding=utf-8
"""
Chaine de traduction de l'extension, sans dependance a gettext.
python i18n.py # extract + update + compile
python i18n.py extract # po/<domaine>.pot depuis le .inx et les .py
python i18n.py update # reporte le modele dans po/<langue>.po
python i18n.py compile # po/<langue>.po -> locale/<langue>/LC_MESSAGES/*.mo
Le domaine est lu dans l'attribut translationdomain des .inx (le meme pour
tous) ; les sources sont les .inx et tous les .py du dossier (hors i18n.py
et tests).
Les textes source (.inx et appels _() des .py) sont en anglais : c'est ce
qu'Inkscape affiche pour une langue sans catalogue. Le catalogue anglais est
rempli automatiquement avec les textes source ; seul fr.po se traduit a la main.
Les chaines retenues dans le .inx suivent les regles d'Inkscape (inx.its) :
<name>, attributs gui-text et gui-description, contenu de <option>, <item> et
<label>, sauf translatable="no". Les espaces sont normalises, sauf sous
xml:space="preserve".
"""
import ast
import os
import re
import struct
import sys
import xml.etree.ElementTree as ET
HERE = os.path.dirname(os.path.abspath(__file__))
LANGUAGES = ["en", "fr"]
SOURCE_LANGUAGE = "en"
PO_DIR = os.path.join(HERE, "po")
LOCALE_DIR = os.path.join(HERE, "locale")
XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space"
INX_NS = "{http://www.inkscape.org/namespace/inkscape/extension}"
def _find_inx():
found = sorted(name for name in os.listdir(HERE) if name.endswith(".inx"))
if not found:
sys.exit("Aucun fichier .inx dans {}".format(HERE))
return found
# Plusieurs entrees de menu partagent un seul catalogue : tous les .inx
# doivent declarer le meme translationdomain.
INX_FILES = _find_inx()
_DOMAINS = {ET.parse(os.path.join(HERE, name)).getroot().get("translationdomain")
for name in INX_FILES}
if len(_DOMAINS) != 1 or None in _DOMAINS:
sys.exit("Les .inx doivent tous declarer le meme translationdomain (trouve : {})"
.format(sorted(str(d) for d in _DOMAINS)))
DOMAIN = _DOMAINS.pop()
EXTENSION_NAME = "Board photo"
SOURCES = INX_FILES + sorted(
name for name in os.listdir(HERE)
if name.endswith(".py") and name != "i18n.py" and not name.startswith("test"))
# --------------------------------------------------------------------------
# Extraction
# --------------------------------------------------------------------------
def _local(tag):
return tag.rsplit("}", 1)[-1]
def _normalize(text, preserve):
return text if preserve else " ".join(text.split())
def extract_inx(path):
"""Chaines traduisibles d'un fichier .inx, dans l'ordre du document."""
messages = []
def walk(elem, preserve):
preserve = elem.get(XML_SPACE, "preserve" if preserve else "default") == "preserve"
if elem.get("translatable") != "no":
for attr in ("gui-text", "gui-description"):
if elem.get(attr):
messages.append(_normalize(elem.get(attr), preserve))
if _local(elem.tag) in ("name", "option", "item", "label") and elem.text:
messages.append(_normalize(elem.text, preserve))
for child in elem:
walk(child, preserve)
walk(ET.parse(path).getroot(), False)
return [m for m in messages if m]
def extract_py(path):
"""Arguments litteraux des appels _("...") d'un script Python."""
with open(path, encoding="utf-8") as handle:
tree = ast.parse(handle.read(), path)
calls = [node for node in ast.walk(tree)
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
and node.func.id == "_" and len(node.args) == 1
and isinstance(node.args[0], ast.Constant)
and isinstance(node.args[0].value, str)]
calls.sort(key=lambda node: (node.lineno, node.col_offset))
return [node.args[0].value for node in calls]
def extract():
"""Liste ordonnee et sans doublon de (msgid, [fichiers sources])."""
found = {}
for name in SOURCES:
path = os.path.join(HERE, name)
strings = extract_inx(path) if name.endswith(".inx") else extract_py(path)
for msgid in strings:
found.setdefault(msgid, [])
if name not in found[msgid]:
found[msgid].append(name)
return list(found.items())
# --------------------------------------------------------------------------
# Lecture / ecriture des fichiers .po
# --------------------------------------------------------------------------
_ESCAPES = {"n": "\n", "t": "\t", '"': '"', "\\": "\\"}
def _unquote(line):
body = line.strip()[1:-1]
return re.sub(r'\\(.)', lambda m: _ESCAPES.get(m.group(1), m.group(1)), body)
def _quote(text):
text = text.replace("\\", "\\\\").replace('"', '\\"').replace("\t", "\\t")
lines = text.split("\n")
parts = [line + "\\n" for line in lines[:-1]]
if lines[-1]:
parts.append(lines[-1])
if len(parts) <= 1:
return '"{}"'.format(parts[0] if parts else "")
return '""\n' + "\n".join('"{}"'.format(part) for part in parts)
def read_po(path):
"""Dictionnaire msgid -> (msgstr, fuzzy). L'en-tete a pour cle ""."""
entries = {}
if not os.path.exists(path):
return entries
msgid = msgstr = None
field = None
fuzzy = False
def flush():
if msgid is not None:
entries[msgid] = (msgstr or "", fuzzy)
with open(path, encoding="utf-8") as handle:
for raw in handle:
line = raw.strip()
if line.startswith("#,") and "fuzzy" in line:
flush()
msgid = msgstr = field = None
fuzzy = True
elif line.startswith("msgid "):
if field == "msgstr":
flush()
fuzzy = False
msgid, msgstr, field = _unquote(line[6:]), None, "msgid"
elif line.startswith("msgstr "):
msgstr, field = _unquote(line[7:]), "msgstr"
elif line.startswith('"') and field == "msgid":
msgid += _unquote(line)
elif line.startswith('"') and field == "msgstr":
msgstr += _unquote(line)
elif not line and field == "msgstr":
flush()
msgid = msgstr = field = None
fuzzy = False
flush()
return entries
def _header(language):
fields = [
("Project-Id-Version", DOMAIN),
("Language", language or ""),
("MIME-Version", "1.0"),
("Content-Type", "text/plain; charset=UTF-8"),
("Content-Transfer-Encoding", "8bit"),
("Plural-Forms", {"fr": "nplurals=2; plural=(n > 1);",
"en": "nplurals=2; plural=(n != 1);"}.get(language, "")),
]
return "".join("{}: {}\n".format(key, value) for key, value in fields if value)
def write_po(path, language, messages, translations):
title = ("Modele de traduction" if language is None
else "Traduction ({})".format(language))
out = ["# {} de l'extension Inkscape « {} ».".format(title, EXTENSION_NAME),
"# Genere par i18n.py ; ne modifier que les msgstr.",
"msgid \"\"",
"msgstr " + _quote(_header(language)),
""]
for msgid, refs in messages:
msgstr, fuzzy = translations.get(msgid, ("", False))
out.append("#: " + " ".join(refs))
if fuzzy:
out.append("#, fuzzy")
out.append("msgid " + _quote(msgid))
out.append("msgstr " + _quote(msgstr))
out.append("")
with open(path, "w", encoding="utf-8", newline="\n") as handle:
handle.write("\n".join(out))
# --------------------------------------------------------------------------
# Compilation .mo (format GNU gettext)
# --------------------------------------------------------------------------
def write_mo(path, catalog):
"""Ecrit un catalogue {msgid: msgstr} au format .mo, cles triees."""
keys = sorted(catalog)
ids = [key.encode("utf-8") for key in keys]
strs = [catalog[key].encode("utf-8") for key in keys]
count = len(keys)
ids_start = 7 * 4 + 16 * count
strs_start = ids_start + sum(len(b) + 1 for b in ids)
table_ids, table_strs = [], []
offset = ids_start
for data in ids:
table_ids += [len(data), offset]
offset += len(data) + 1
offset = strs_start
for data in strs:
table_strs += [len(data), offset]
offset += len(data) + 1
output = struct.pack("<7I", 0x950412DE, 0, count, 7 * 4, 7 * 4 + 8 * count, 0, 0)
output += struct.pack("<{}I".format(2 * count), *table_ids)
output += struct.pack("<{}I".format(2 * count), *table_strs)
output += b"".join(data + b"\0" for data in ids)
output += b"".join(data + b"\0" for data in strs)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as handle:
handle.write(output)
# --------------------------------------------------------------------------
# Commandes
# --------------------------------------------------------------------------
def po_path(language):
return os.path.join(PO_DIR, "{}.po".format(language))
def mo_path(language):
return os.path.join(LOCALE_DIR, language, "LC_MESSAGES", DOMAIN + ".mo")
def cmd_extract():
os.makedirs(PO_DIR, exist_ok=True)
messages = extract()
write_po(os.path.join(PO_DIR, DOMAIN + ".pot"), None, messages, {})
print("{} chaines -> po/{}.pot".format(len(messages), DOMAIN))
def cmd_update():
messages = extract()
for language in LANGUAGES:
translations = read_po(po_path(language))
if language == SOURCE_LANGUAGE:
translations = {msgid: (msgid, False) for msgid, _refs in messages}
write_po(po_path(language), language, messages, translations)
missing = [m for m, _r in messages if not translations.get(m, ("", False))[0]]
print("po/{}.po : {} a traduire".format(language, len(missing)))
for msgid in missing:
print(" " + msgid.splitlines()[0])
def cmd_compile():
for language in LANGUAGES:
entries = read_po(po_path(language))
catalog = {msgid: msgstr for msgid, (msgstr, fuzzy) in entries.items()
if msgid and msgstr and not fuzzy}
catalog[""] = _header(language)
write_mo(mo_path(language), catalog)
print("{} -> {} ({} chaines)".format(
os.path.relpath(po_path(language), HERE),
os.path.relpath(mo_path(language), HERE), len(catalog) - 1))
def main(argv):
commands = {"extract": [cmd_extract], "update": [cmd_update],
"compile": [cmd_compile],
"all": [cmd_extract, cmd_update, cmd_compile]}
name = argv[0] if argv else "all"
if name not in commands:
print(__doc__)
return 1
for command in commands[name]:
command()
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.
Binary file not shown.
+575
View File
@@ -0,0 +1,575 @@
# Modele de traduction de l'extension Inkscape « Board photo ».
# Genere par i18n.py ; ne modifier que les msgstr.
msgid ""
msgstr ""
"Project-Id-Version: board_photo\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: board_photo_import.inx
msgid "Board photo: import and calibrate"
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Work area"
msgstr ""
#: board_photo_import.inx
msgid "Honeycomb = laser work area (mm)"
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Width (mm):"
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Height (mm):"
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Set the page to the work area size"
msgstr ""
#: board_photo_import.inx board_photo_markers.py
msgid "Calibration markers"
msgstr ""
#: board_photo_import.inx
msgid "Marker position:"
msgstr ""
#: board_photo_import.inx
msgid "Around the honeycomb: the inner corner of each paper piece touches a corner of the honeycomb"
msgstr ""
#: board_photo_import.inx
msgid "Custom: centre of the origin marker and spacing below"
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Marker size (mm):"
msgstr ""
#: board_photo_import.inx
msgid "Side of the black square; the paper piece is twice as large"
msgstr ""
#: board_photo_import.inx
msgid "Around the honeycomb, everything is deduced: the bottom left corner of the honeycomb is the laser origin (bottom left of the page), and the spacing is the honeycomb size plus twice the marker size. The values below are only used for a custom position."
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Origin marker centre X (mm):"
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Distance from the laser origin to the centre of the two-dot marker, along X; negative when the markers are around the work area (left of the origin)"
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Origin marker centre Y (mm):"
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Distance from the laser origin to the centre of the two-dot marker, along Y (upwards); negative when the markers are around the work area (below the origin)"
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Spacing between markers X (mm):"
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Spacing between markers Y (mm):"
msgstr ""
#: board_photo_import.inx
msgid "Photo"
msgstr ""
#: board_photo_import.inx
msgid "Photo source:"
msgstr ""
#: board_photo_import.inx
msgid "Photo file"
msgstr ""
#: board_photo_import.inx
msgid "Remote camera (capture server)"
msgstr ""
#: board_photo_import.inx
msgid "Photo of the board:"
msgstr ""
#: board_photo_import.inx
msgid "Photo taken from above, showing the 4 markers"
msgstr ""
#: board_photo_import.inx
msgid "Remote camera"
msgstr ""
#: board_photo_import.inx
msgid "Address of the remote machine (IP or IP:port):"
msgstr ""
#: board_photo_import.inx
msgid "Machine running the capture server, for example 192.168.1.20"
msgstr ""
#: board_photo_import.inx
msgid "Port:"
msgstr ""
#: board_photo_import.inx
msgid "Picture:"
msgstr ""
#: board_photo_import.inx
msgid "Take a new photo (/capture)"
msgstr ""
#: board_photo_import.inx
msgid "Use the last photo taken (/old)"
msgstr ""
#: board_photo_import.inx
msgid "Timeout (s):"
msgstr ""
#: board_photo_import.inx
msgid "Resolution of the calibrated photo (px/mm):"
msgstr ""
#: board_photo_import.inx
msgid "4 px/mm = 0.25 mm per pixel; higher values make a heavier document"
msgstr ""
#: board_photo_import.inx
msgid "JPEG quality:"
msgstr ""
#: board_photo_import.inx
msgid "Board detection"
msgstr ""
#: board_photo_import.inx
msgid "Vectorize the board outline and holes"
msgstr ""
#: board_photo_import.inx
msgid "Board tone:"
msgstr ""
#: board_photo_import.inx
msgid "Lighter than the bed (light wood on honeycomb)"
msgstr ""
#: board_photo_import.inx
msgid "Darker than the bed (dark board on light surface)"
msgstr ""
#: board_photo_import.inx
msgid "Threshold (0 = automatic):"
msgstr ""
#: board_photo_import.inx
msgid "Grey level between board and bed; 0 computes it automatically (Otsu)"
msgstr ""
#: board_photo_import.inx
msgid "Smoothing (mm):"
msgstr ""
#: board_photo_import.inx
msgid "Removes specks and fills small notches smaller than about twice this value"
msgstr ""
#: board_photo_import.inx
msgid "Minimum hole area (mm²):"
msgstr ""
#: board_photo_import.inx
msgid "Smaller holes are ignored (filled)"
msgstr ""
#: board_photo_import.inx
msgid "Outline tolerance (mm):"
msgstr ""
#: board_photo_import.inx
msgid "Maximum deviation allowed when simplifying the outline"
msgstr ""
#: board_photo_import.inx
msgid "Outline colour:"
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Diagram"
msgstr ""
#: board_photo_import.inx board_photo_markers.inx
msgid "Help"
msgstr ""
#: board_photo_import.inx
msgid ""
"1. Print the 4 markers (Board photo: print\n"
" calibration markers, A4 sheet) and stick\n"
" them at the corners of the honeycomb.\n"
"2. Lay the board on the bed and take a photo\n"
" from above showing the 4 markers.\n"
"3. With nothing selected, choose the photo\n"
" file, or the address of the remote camera\n"
" (capture server), and apply: the photo is\n"
" straightened and\n"
" placed at the exact scale of the work area,\n"
" with the board outline and holes.\n"
"4. Draw or place the shapes in the \"Cuts\"\n"
" layer, on the board, then export them with\n"
" \"Export to LaserGRBL\".\n"
"\n"
"If the markers are not found, the raw photo\n"
"is placed with 4 red targets: move them onto\n"
"the marker centres, select the layer content\n"
"(Ctrl+A) and apply again.\n"
"\n"
"Markers around the honeycomb (default): stick\n"
"the 4 printed pieces so that the inner corner\n"
"of each piece touches a corner of the\n"
"honeycomb, the two-dot marker at the bottom\n"
"left. The bottom left corner of the honeycomb\n"
"is then the laser origin, i.e. the bottom left\n"
"of the page, as expected by the export to\n"
"LaserGRBL.\n"
"\n"
"Coordinates are in mm from the laser origin\n"
"(bottom left of the work area)."
msgstr ""
#: board_photo_markers.inx
msgid "Board photo: print calibration markers"
msgstr ""
#: board_photo_markers.inx
msgid "Output:"
msgstr ""
#: board_photo_markers.inx
msgid "Markers to engrave on the bed"
msgstr ""
#: board_photo_markers.inx
msgid "A4 sheet to print (markers to cut out)"
msgstr ""
#: board_photo_markers.inx
msgid "Placement guides to engrave on the bed (for printed markers)"
msgstr ""
#: board_photo_markers.inx
msgid "Laser work area (mm)"
msgstr ""
#: board_photo_markers.inx
msgid "Calibration markers, inside or around the work area (laser origin at the bottom left)"
msgstr ""
#: board_photo_markers.inx
msgid "Printed sheet"
msgstr ""
#: board_photo_markers.inx
msgid ""
"Print the sheet at actual size (100 %,\n"
"no \"fit to page\"), preferably from a PDF\n"
"(File > Save a Copy > PDF). Then measure\n"
"both 100 mm bars.\n"
"\n"
"Only if the printer still shrinks the sheet,\n"
"enter the measured lengths below: the sheet\n"
"is enlarged to compensate. Print it again\n"
"and check that the bars now measure 100 mm."
msgstr ""
#: board_photo_markers.inx
msgid "Measured length of the horizontal bar (mm):"
msgstr ""
#: board_photo_markers.inx
msgid "Measured length of the vertical bar (mm):"
msgstr ""
#: board_photo_markers.inx
msgid ""
"Engraved markers: engrave them once, filled,\n"
"on light plates fixed to the bed, keeping a\n"
"light area of twice the marker size around\n"
"each one.\n"
"\n"
"Printed markers:\n"
"1. \"A4 sheet\": print at 100 % (no fit to\n"
" page), check the 100 mm bar, cut out the\n"
" 4 pieces along the dashed lines.\n"
"2. \"Placement guides\": engrave them lightly\n"
" on the bed (thin red lines).\n"
"3. Stick each piece inside its guide, the\n"
" ticks of the piece on the cross.\n"
"\n"
"The markers must stay in place: every photo\n"
"is scaled from them. The marker with two dots\n"
"is the origin marker, at the bottom left\n"
"(laser origin). Use the same settings in\n"
"\"Board photo: import and calibrate\"."
msgstr ""
#: board_photo_import.py board_photo_markers.py
msgid "Work area, marker spacing and marker size must be strictly positive."
msgstr ""
#: board_photo_import.py
msgid "Choose the photo of the board in the \"Photo\" tab (or select a photo and 4 markers for a manual calibration)."
msgstr ""
#: board_photo_import.py
msgid "Photo not found: {}"
msgstr ""
#: board_photo_import.py
msgid "This file cannot be read as an image: {}"
msgstr ""
#: board_photo_import.py
msgid "Enter the address of the remote machine in the \"Photo\" tab (for example 192.168.1.20)."
msgstr ""
#: board_photo_import.py
msgid "Invalid remote address: {}"
msgstr ""
#: board_photo_import.py
msgid "The remote machine cannot be reached ({}): check its address, that the capture server is running and that the port is open."
msgstr ""
#: board_photo_import.py
msgid "The remote machine did not answer in time ({}): increase the timeout or check the network."
msgstr ""
#: board_photo_import.py
msgid "The transfer of the photo was interrupted ({}), even after a second attempt: check the network and try again."
msgstr ""
#: board_photo_import.py
msgid "The capture server returned an error: {}"
msgstr ""
#: board_photo_import.py
msgid "The capture server did not return an image: {}"
msgstr ""
#: board_photo_import.py
msgid "The image returned by the capture server is too large ({})."
msgstr ""
#: board_photo_import.py
msgid "Remote capture failed: {}"
msgstr ""
#: board_photo_import.py
msgid "The capture server did not return a readable image ({})."
msgstr ""
#: board_photo_import.py
msgid "Photo received from {} ({} x {} px)."
msgstr ""
#: board_photo_import.py
msgid "Manual calibration: select the photo and exactly 4 small shapes centred on the markers (for example Ctrl+A in the \"Manual calibration\" layer). Deselect everything to import a new photo."
msgstr ""
#: board_photo_import.py
msgid "The selected image cannot be read (embed it, or check that the linked file still exists)."
msgstr ""
#: board_photo_import.py
msgid "The selected image has no size."
msgstr ""
#: board_photo_import.py
msgid "Manual calibration"
msgstr ""
#: board_photo_import.py
msgid "Marker target"
msgstr ""
#: board_photo_import.py
msgid "no dark shape found"
msgstr ""
#: board_photo_import.py
msgid "{} marker(s) found out of 4"
msgstr ""
#: board_photo_import.py
msgid "the markers found do not form a rectangle"
msgstr ""
#: board_photo_import.py
msgid "Automatic marker detection failed ({})."
msgstr ""
#: board_photo_import.py
msgid "The raw photo was placed in the \"Manual calibration\" layer with 4 red targets: move each target onto the centre of a marker (zoom in), select the layer content (Ctrl+A) and run this extension again."
msgstr ""
#: board_photo_import.py
msgid "The 4 marker positions do not form a convex quadrilateral: check them and try again."
msgstr ""
#: board_photo_import.py
msgid "The 4 marker positions are aligned: check them and try again."
msgstr ""
#: board_photo_import.py
msgid "The origin marker (two dots) was not recognised: the photo is assumed upright (origin at the bottom left of the photo)."
msgstr ""
#: board_photo_import.py
msgid "A marker measures {:.1f} mm instead of {:.1f} mm: check the marker positions and size in the \"Work area\" tab."
msgstr ""
#: board_photo_import.py
msgid "No board found on the photo: try the other \"Board tone\" or set the threshold by hand."
msgstr ""
#: board_photo_import.py
msgid "The page is not the size of the work area: the export to LaserGRBL takes the bottom left of the page as the laser origin, so tick \"Set the page to the work area size\" before cutting."
msgstr ""
#: board_photo_import.py
msgid "Board photo calibrated: {:.2f} mm per photo pixel."
msgstr ""
#: board_photo_import.py
msgid "{} hole(s) found."
msgstr ""
#: board_photo_import.py
msgid "Board photo"
msgstr ""
#: board_photo_import.py
msgid "Calibrated photo"
msgstr ""
#: board_photo_import.py
msgid "Board outline"
msgstr ""
#: board_photo_import.py
msgid "Board outline ({} holes)"
msgstr ""
#: board_photo_import.py
msgid "Cuts"
msgstr ""
#: board_photo_markers.py
msgid "The placement guides do not fit in the work area: keep every marker centre at least {:g} mm from the edges (1.5 x the marker size)."
msgstr ""
#: board_photo_markers.py
msgid "The markers do not fit in the work area, so the laser cannot engrave them: reduce the spacing or move the origin marker. Markers placed around the work area (negative origin, larger spacing) are printed instead (\"Output\": A4 sheet) and stuck in place by hand."
msgstr ""
#: board_photo_markers.py
msgid "The markers are too close to each other: the spacing must be at least twice the marker size."
msgstr ""
#: board_photo_markers.py
msgid "Origin marker"
msgstr ""
#: board_photo_markers.py
msgid "Marker"
msgstr ""
#: board_photo_markers.py
msgid "Marker placement guides"
msgstr ""
#: board_photo_markers.py
msgid "These markers are too large for an A4 sheet: reduce the marker size, or engrave them directly on the bed."
msgstr ""
#: board_photo_markers.py
msgid "The measured bar lengths must be between 80 and 120 mm."
msgstr ""
#: board_photo_markers.py
msgid "Calibration markers (print)"
msgstr ""
#: board_photo_markers.py
msgid "Calibration markers - print at 100 %"
msgstr ""
#: board_photo_markers.py
msgid "Print at actual size (no \"fit to page\"), then check that both bars measure 100 mm."
msgstr ""
#: board_photo_markers.py
msgid "Cut along the dashed lines and stick each piece outside a corner of the honeycomb, its inner corner on that corner."
msgstr ""
#: board_photo_markers.py
msgid "Marker size: {:g} mm"
msgstr ""
#: board_photo_markers.py
msgid "printer correction: X {:.1f} %, Y {:.1f} %"
msgstr ""
#: board_photo_markers.py
msgid "Top left"
msgstr ""
#: board_photo_markers.py
msgid "Top right"
msgstr ""
#: board_photo_markers.py
msgid "Bottom right"
msgstr ""
#: board_photo_markers.py
msgid "Origin - bottom left"
msgstr ""
#: board_photo_markers.py
msgid "Cutting line"
msgstr ""
#: board_photo_markers.py
msgid "Alignment ticks"
msgstr ""
#: board_photo_markers.py
msgid "Scale bar X"
msgstr ""
#: board_photo_markers.py
msgid "100 mm (X)"
msgstr ""
#: board_photo_markers.py
msgid "Scale bar Y"
msgstr ""
#: board_photo_markers.py
msgid "100 mm (Y)"
msgstr ""
+636
View File
@@ -0,0 +1,636 @@
# Traduction (en) de l'extension Inkscape « Board photo ».
# Genere par i18n.py ; ne modifier que les msgstr.
msgid ""
msgstr ""
"Project-Id-Version: board_photo\n"
"Language: en\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: board_photo_import.inx
msgid "Board photo: import and calibrate"
msgstr "Board photo: import and calibrate"
#: board_photo_import.inx board_photo_markers.inx
msgid "Work area"
msgstr "Work area"
#: board_photo_import.inx
msgid "Honeycomb = laser work area (mm)"
msgstr "Honeycomb = laser work area (mm)"
#: board_photo_import.inx board_photo_markers.inx
msgid "Width (mm):"
msgstr "Width (mm):"
#: board_photo_import.inx board_photo_markers.inx
msgid "Height (mm):"
msgstr "Height (mm):"
#: board_photo_import.inx board_photo_markers.inx
msgid "Set the page to the work area size"
msgstr "Set the page to the work area size"
#: board_photo_import.inx board_photo_markers.py
msgid "Calibration markers"
msgstr "Calibration markers"
#: board_photo_import.inx
msgid "Marker position:"
msgstr "Marker position:"
#: board_photo_import.inx
msgid "Around the honeycomb: the inner corner of each paper piece touches a corner of the honeycomb"
msgstr "Around the honeycomb: the inner corner of each paper piece touches a corner of the honeycomb"
#: board_photo_import.inx
msgid "Custom: centre of the origin marker and spacing below"
msgstr "Custom: centre of the origin marker and spacing below"
#: board_photo_import.inx board_photo_markers.inx
msgid "Marker size (mm):"
msgstr "Marker size (mm):"
#: board_photo_import.inx
msgid "Side of the black square; the paper piece is twice as large"
msgstr "Side of the black square; the paper piece is twice as large"
#: board_photo_import.inx
msgid "Around the honeycomb, everything is deduced: the bottom left corner of the honeycomb is the laser origin (bottom left of the page), and the spacing is the honeycomb size plus twice the marker size. The values below are only used for a custom position."
msgstr "Around the honeycomb, everything is deduced: the bottom left corner of the honeycomb is the laser origin (bottom left of the page), and the spacing is the honeycomb size plus twice the marker size. The values below are only used for a custom position."
#: board_photo_import.inx board_photo_markers.inx
msgid "Origin marker centre X (mm):"
msgstr "Origin marker centre X (mm):"
#: board_photo_import.inx board_photo_markers.inx
msgid "Distance from the laser origin to the centre of the two-dot marker, along X; negative when the markers are around the work area (left of the origin)"
msgstr "Distance from the laser origin to the centre of the two-dot marker, along X; negative when the markers are around the work area (left of the origin)"
#: board_photo_import.inx board_photo_markers.inx
msgid "Origin marker centre Y (mm):"
msgstr "Origin marker centre Y (mm):"
#: board_photo_import.inx board_photo_markers.inx
msgid "Distance from the laser origin to the centre of the two-dot marker, along Y (upwards); negative when the markers are around the work area (below the origin)"
msgstr "Distance from the laser origin to the centre of the two-dot marker, along Y (upwards); negative when the markers are around the work area (below the origin)"
#: board_photo_import.inx board_photo_markers.inx
msgid "Spacing between markers X (mm):"
msgstr "Spacing between markers X (mm):"
#: board_photo_import.inx board_photo_markers.inx
msgid "Spacing between markers Y (mm):"
msgstr "Spacing between markers Y (mm):"
#: board_photo_import.inx
msgid "Photo"
msgstr "Photo"
#: board_photo_import.inx
msgid "Photo source:"
msgstr "Photo source:"
#: board_photo_import.inx
msgid "Photo file"
msgstr "Photo file"
#: board_photo_import.inx
msgid "Remote camera (capture server)"
msgstr "Remote camera (capture server)"
#: board_photo_import.inx
msgid "Photo of the board:"
msgstr "Photo of the board:"
#: board_photo_import.inx
msgid "Photo taken from above, showing the 4 markers"
msgstr "Photo taken from above, showing the 4 markers"
#: board_photo_import.inx
msgid "Remote camera"
msgstr "Remote camera"
#: board_photo_import.inx
msgid "Address of the remote machine (IP or IP:port):"
msgstr "Address of the remote machine (IP or IP:port):"
#: board_photo_import.inx
msgid "Machine running the capture server, for example 192.168.1.20"
msgstr "Machine running the capture server, for example 192.168.1.20"
#: board_photo_import.inx
msgid "Port:"
msgstr "Port:"
#: board_photo_import.inx
msgid "Picture:"
msgstr "Picture:"
#: board_photo_import.inx
msgid "Take a new photo (/capture)"
msgstr "Take a new photo (/capture)"
#: board_photo_import.inx
msgid "Use the last photo taken (/old)"
msgstr "Use the last photo taken (/old)"
#: board_photo_import.inx
msgid "Timeout (s):"
msgstr "Timeout (s):"
#: board_photo_import.inx
msgid "Resolution of the calibrated photo (px/mm):"
msgstr "Resolution of the calibrated photo (px/mm):"
#: board_photo_import.inx
msgid "4 px/mm = 0.25 mm per pixel; higher values make a heavier document"
msgstr "4 px/mm = 0.25 mm per pixel; higher values make a heavier document"
#: board_photo_import.inx
msgid "JPEG quality:"
msgstr "JPEG quality:"
#: board_photo_import.inx
msgid "Board detection"
msgstr "Board detection"
#: board_photo_import.inx
msgid "Vectorize the board outline and holes"
msgstr "Vectorize the board outline and holes"
#: board_photo_import.inx
msgid "Board tone:"
msgstr "Board tone:"
#: board_photo_import.inx
msgid "Lighter than the bed (light wood on honeycomb)"
msgstr "Lighter than the bed (light wood on honeycomb)"
#: board_photo_import.inx
msgid "Darker than the bed (dark board on light surface)"
msgstr "Darker than the bed (dark board on light surface)"
#: board_photo_import.inx
msgid "Threshold (0 = automatic):"
msgstr "Threshold (0 = automatic):"
#: board_photo_import.inx
msgid "Grey level between board and bed; 0 computes it automatically (Otsu)"
msgstr "Grey level between board and bed; 0 computes it automatically (Otsu)"
#: board_photo_import.inx
msgid "Smoothing (mm):"
msgstr "Smoothing (mm):"
#: board_photo_import.inx
msgid "Removes specks and fills small notches smaller than about twice this value"
msgstr "Removes specks and fills small notches smaller than about twice this value"
#: board_photo_import.inx
msgid "Minimum hole area (mm²):"
msgstr "Minimum hole area (mm²):"
#: board_photo_import.inx
msgid "Smaller holes are ignored (filled)"
msgstr "Smaller holes are ignored (filled)"
#: board_photo_import.inx
msgid "Outline tolerance (mm):"
msgstr "Outline tolerance (mm):"
#: board_photo_import.inx
msgid "Maximum deviation allowed when simplifying the outline"
msgstr "Maximum deviation allowed when simplifying the outline"
#: board_photo_import.inx
msgid "Outline colour:"
msgstr "Outline colour:"
#: board_photo_import.inx board_photo_markers.inx
msgid "Diagram"
msgstr "Diagram"
#: board_photo_import.inx board_photo_markers.inx
msgid "Help"
msgstr "Help"
#: board_photo_import.inx
msgid ""
"1. Print the 4 markers (Board photo: print\n"
" calibration markers, A4 sheet) and stick\n"
" them at the corners of the honeycomb.\n"
"2. Lay the board on the bed and take a photo\n"
" from above showing the 4 markers.\n"
"3. With nothing selected, choose the photo\n"
" file, or the address of the remote camera\n"
" (capture server), and apply: the photo is\n"
" straightened and\n"
" placed at the exact scale of the work area,\n"
" with the board outline and holes.\n"
"4. Draw or place the shapes in the \"Cuts\"\n"
" layer, on the board, then export them with\n"
" \"Export to LaserGRBL\".\n"
"\n"
"If the markers are not found, the raw photo\n"
"is placed with 4 red targets: move them onto\n"
"the marker centres, select the layer content\n"
"(Ctrl+A) and apply again.\n"
"\n"
"Markers around the honeycomb (default): stick\n"
"the 4 printed pieces so that the inner corner\n"
"of each piece touches a corner of the\n"
"honeycomb, the two-dot marker at the bottom\n"
"left. The bottom left corner of the honeycomb\n"
"is then the laser origin, i.e. the bottom left\n"
"of the page, as expected by the export to\n"
"LaserGRBL.\n"
"\n"
"Coordinates are in mm from the laser origin\n"
"(bottom left of the work area)."
msgstr ""
"1. Print the 4 markers (Board photo: print\n"
" calibration markers, A4 sheet) and stick\n"
" them at the corners of the honeycomb.\n"
"2. Lay the board on the bed and take a photo\n"
" from above showing the 4 markers.\n"
"3. With nothing selected, choose the photo\n"
" file, or the address of the remote camera\n"
" (capture server), and apply: the photo is\n"
" straightened and\n"
" placed at the exact scale of the work area,\n"
" with the board outline and holes.\n"
"4. Draw or place the shapes in the \"Cuts\"\n"
" layer, on the board, then export them with\n"
" \"Export to LaserGRBL\".\n"
"\n"
"If the markers are not found, the raw photo\n"
"is placed with 4 red targets: move them onto\n"
"the marker centres, select the layer content\n"
"(Ctrl+A) and apply again.\n"
"\n"
"Markers around the honeycomb (default): stick\n"
"the 4 printed pieces so that the inner corner\n"
"of each piece touches a corner of the\n"
"honeycomb, the two-dot marker at the bottom\n"
"left. The bottom left corner of the honeycomb\n"
"is then the laser origin, i.e. the bottom left\n"
"of the page, as expected by the export to\n"
"LaserGRBL.\n"
"\n"
"Coordinates are in mm from the laser origin\n"
"(bottom left of the work area)."
#: board_photo_markers.inx
msgid "Board photo: print calibration markers"
msgstr "Board photo: print calibration markers"
#: board_photo_markers.inx
msgid "Output:"
msgstr "Output:"
#: board_photo_markers.inx
msgid "Markers to engrave on the bed"
msgstr "Markers to engrave on the bed"
#: board_photo_markers.inx
msgid "A4 sheet to print (markers to cut out)"
msgstr "A4 sheet to print (markers to cut out)"
#: board_photo_markers.inx
msgid "Placement guides to engrave on the bed (for printed markers)"
msgstr "Placement guides to engrave on the bed (for printed markers)"
#: board_photo_markers.inx
msgid "Laser work area (mm)"
msgstr "Laser work area (mm)"
#: board_photo_markers.inx
msgid "Calibration markers, inside or around the work area (laser origin at the bottom left)"
msgstr "Calibration markers, inside or around the work area (laser origin at the bottom left)"
#: board_photo_markers.inx
msgid "Printed sheet"
msgstr "Printed sheet"
#: board_photo_markers.inx
msgid ""
"Print the sheet at actual size (100 %,\n"
"no \"fit to page\"), preferably from a PDF\n"
"(File > Save a Copy > PDF). Then measure\n"
"both 100 mm bars.\n"
"\n"
"Only if the printer still shrinks the sheet,\n"
"enter the measured lengths below: the sheet\n"
"is enlarged to compensate. Print it again\n"
"and check that the bars now measure 100 mm."
msgstr ""
"Print the sheet at actual size (100 %,\n"
"no \"fit to page\"), preferably from a PDF\n"
"(File > Save a Copy > PDF). Then measure\n"
"both 100 mm bars.\n"
"\n"
"Only if the printer still shrinks the sheet,\n"
"enter the measured lengths below: the sheet\n"
"is enlarged to compensate. Print it again\n"
"and check that the bars now measure 100 mm."
#: board_photo_markers.inx
msgid "Measured length of the horizontal bar (mm):"
msgstr "Measured length of the horizontal bar (mm):"
#: board_photo_markers.inx
msgid "Measured length of the vertical bar (mm):"
msgstr "Measured length of the vertical bar (mm):"
#: board_photo_markers.inx
msgid ""
"Engraved markers: engrave them once, filled,\n"
"on light plates fixed to the bed, keeping a\n"
"light area of twice the marker size around\n"
"each one.\n"
"\n"
"Printed markers:\n"
"1. \"A4 sheet\": print at 100 % (no fit to\n"
" page), check the 100 mm bar, cut out the\n"
" 4 pieces along the dashed lines.\n"
"2. \"Placement guides\": engrave them lightly\n"
" on the bed (thin red lines).\n"
"3. Stick each piece inside its guide, the\n"
" ticks of the piece on the cross.\n"
"\n"
"The markers must stay in place: every photo\n"
"is scaled from them. The marker with two dots\n"
"is the origin marker, at the bottom left\n"
"(laser origin). Use the same settings in\n"
"\"Board photo: import and calibrate\"."
msgstr ""
"Engraved markers: engrave them once, filled,\n"
"on light plates fixed to the bed, keeping a\n"
"light area of twice the marker size around\n"
"each one.\n"
"\n"
"Printed markers:\n"
"1. \"A4 sheet\": print at 100 % (no fit to\n"
" page), check the 100 mm bar, cut out the\n"
" 4 pieces along the dashed lines.\n"
"2. \"Placement guides\": engrave them lightly\n"
" on the bed (thin red lines).\n"
"3. Stick each piece inside its guide, the\n"
" ticks of the piece on the cross.\n"
"\n"
"The markers must stay in place: every photo\n"
"is scaled from them. The marker with two dots\n"
"is the origin marker, at the bottom left\n"
"(laser origin). Use the same settings in\n"
"\"Board photo: import and calibrate\"."
#: board_photo_import.py board_photo_markers.py
msgid "Work area, marker spacing and marker size must be strictly positive."
msgstr "Work area, marker spacing and marker size must be strictly positive."
#: board_photo_import.py
msgid "Choose the photo of the board in the \"Photo\" tab (or select a photo and 4 markers for a manual calibration)."
msgstr "Choose the photo of the board in the \"Photo\" tab (or select a photo and 4 markers for a manual calibration)."
#: board_photo_import.py
msgid "Photo not found: {}"
msgstr "Photo not found: {}"
#: board_photo_import.py
msgid "This file cannot be read as an image: {}"
msgstr "This file cannot be read as an image: {}"
#: board_photo_import.py
msgid "Enter the address of the remote machine in the \"Photo\" tab (for example 192.168.1.20)."
msgstr "Enter the address of the remote machine in the \"Photo\" tab (for example 192.168.1.20)."
#: board_photo_import.py
msgid "Invalid remote address: {}"
msgstr "Invalid remote address: {}"
#: board_photo_import.py
msgid "The remote machine cannot be reached ({}): check its address, that the capture server is running and that the port is open."
msgstr "The remote machine cannot be reached ({}): check its address, that the capture server is running and that the port is open."
#: board_photo_import.py
msgid "The remote machine did not answer in time ({}): increase the timeout or check the network."
msgstr "The remote machine did not answer in time ({}): increase the timeout or check the network."
#: board_photo_import.py
msgid "The transfer of the photo was interrupted ({}), even after a second attempt: check the network and try again."
msgstr "The transfer of the photo was interrupted ({}), even after a second attempt: check the network and try again."
#: board_photo_import.py
msgid "The capture server returned an error: {}"
msgstr "The capture server returned an error: {}"
#: board_photo_import.py
msgid "The capture server did not return an image: {}"
msgstr "The capture server did not return an image: {}"
#: board_photo_import.py
msgid "The image returned by the capture server is too large ({})."
msgstr "The image returned by the capture server is too large ({})."
#: board_photo_import.py
msgid "Remote capture failed: {}"
msgstr "Remote capture failed: {}"
#: board_photo_import.py
msgid "The capture server did not return a readable image ({})."
msgstr "The capture server did not return a readable image ({})."
#: board_photo_import.py
msgid "Photo received from {} ({} x {} px)."
msgstr "Photo received from {} ({} x {} px)."
#: board_photo_import.py
msgid "Manual calibration: select the photo and exactly 4 small shapes centred on the markers (for example Ctrl+A in the \"Manual calibration\" layer). Deselect everything to import a new photo."
msgstr "Manual calibration: select the photo and exactly 4 small shapes centred on the markers (for example Ctrl+A in the \"Manual calibration\" layer). Deselect everything to import a new photo."
#: board_photo_import.py
msgid "The selected image cannot be read (embed it, or check that the linked file still exists)."
msgstr "The selected image cannot be read (embed it, or check that the linked file still exists)."
#: board_photo_import.py
msgid "The selected image has no size."
msgstr "The selected image has no size."
#: board_photo_import.py
msgid "Manual calibration"
msgstr "Manual calibration"
#: board_photo_import.py
msgid "Marker target"
msgstr "Marker target"
#: board_photo_import.py
msgid "no dark shape found"
msgstr "no dark shape found"
#: board_photo_import.py
msgid "{} marker(s) found out of 4"
msgstr "{} marker(s) found out of 4"
#: board_photo_import.py
msgid "the markers found do not form a rectangle"
msgstr "the markers found do not form a rectangle"
#: board_photo_import.py
msgid "Automatic marker detection failed ({})."
msgstr "Automatic marker detection failed ({})."
#: board_photo_import.py
msgid "The raw photo was placed in the \"Manual calibration\" layer with 4 red targets: move each target onto the centre of a marker (zoom in), select the layer content (Ctrl+A) and run this extension again."
msgstr "The raw photo was placed in the \"Manual calibration\" layer with 4 red targets: move each target onto the centre of a marker (zoom in), select the layer content (Ctrl+A) and run this extension again."
#: board_photo_import.py
msgid "The 4 marker positions do not form a convex quadrilateral: check them and try again."
msgstr "The 4 marker positions do not form a convex quadrilateral: check them and try again."
#: board_photo_import.py
msgid "The 4 marker positions are aligned: check them and try again."
msgstr "The 4 marker positions are aligned: check them and try again."
#: board_photo_import.py
msgid "The origin marker (two dots) was not recognised: the photo is assumed upright (origin at the bottom left of the photo)."
msgstr "The origin marker (two dots) was not recognised: the photo is assumed upright (origin at the bottom left of the photo)."
#: board_photo_import.py
msgid "A marker measures {:.1f} mm instead of {:.1f} mm: check the marker positions and size in the \"Work area\" tab."
msgstr "A marker measures {:.1f} mm instead of {:.1f} mm: check the marker positions and size in the \"Work area\" tab."
#: board_photo_import.py
msgid "No board found on the photo: try the other \"Board tone\" or set the threshold by hand."
msgstr "No board found on the photo: try the other \"Board tone\" or set the threshold by hand."
#: board_photo_import.py
msgid "The page is not the size of the work area: the export to LaserGRBL takes the bottom left of the page as the laser origin, so tick \"Set the page to the work area size\" before cutting."
msgstr "The page is not the size of the work area: the export to LaserGRBL takes the bottom left of the page as the laser origin, so tick \"Set the page to the work area size\" before cutting."
#: board_photo_import.py
msgid "Board photo calibrated: {:.2f} mm per photo pixel."
msgstr "Board photo calibrated: {:.2f} mm per photo pixel."
#: board_photo_import.py
msgid "{} hole(s) found."
msgstr "{} hole(s) found."
#: board_photo_import.py
msgid "Board photo"
msgstr "Board photo"
#: board_photo_import.py
msgid "Calibrated photo"
msgstr "Calibrated photo"
#: board_photo_import.py
msgid "Board outline"
msgstr "Board outline"
#: board_photo_import.py
msgid "Board outline ({} holes)"
msgstr "Board outline ({} holes)"
#: board_photo_import.py
msgid "Cuts"
msgstr "Cuts"
#: board_photo_markers.py
msgid "The placement guides do not fit in the work area: keep every marker centre at least {:g} mm from the edges (1.5 x the marker size)."
msgstr "The placement guides do not fit in the work area: keep every marker centre at least {:g} mm from the edges (1.5 x the marker size)."
#: board_photo_markers.py
msgid "The markers do not fit in the work area, so the laser cannot engrave them: reduce the spacing or move the origin marker. Markers placed around the work area (negative origin, larger spacing) are printed instead (\"Output\": A4 sheet) and stuck in place by hand."
msgstr "The markers do not fit in the work area, so the laser cannot engrave them: reduce the spacing or move the origin marker. Markers placed around the work area (negative origin, larger spacing) are printed instead (\"Output\": A4 sheet) and stuck in place by hand."
#: board_photo_markers.py
msgid "The markers are too close to each other: the spacing must be at least twice the marker size."
msgstr "The markers are too close to each other: the spacing must be at least twice the marker size."
#: board_photo_markers.py
msgid "Origin marker"
msgstr "Origin marker"
#: board_photo_markers.py
msgid "Marker"
msgstr "Marker"
#: board_photo_markers.py
msgid "Marker placement guides"
msgstr "Marker placement guides"
#: board_photo_markers.py
msgid "These markers are too large for an A4 sheet: reduce the marker size, or engrave them directly on the bed."
msgstr "These markers are too large for an A4 sheet: reduce the marker size, or engrave them directly on the bed."
#: board_photo_markers.py
msgid "The measured bar lengths must be between 80 and 120 mm."
msgstr "The measured bar lengths must be between 80 and 120 mm."
#: board_photo_markers.py
msgid "Calibration markers (print)"
msgstr "Calibration markers (print)"
#: board_photo_markers.py
msgid "Calibration markers - print at 100 %"
msgstr "Calibration markers - print at 100 %"
#: board_photo_markers.py
msgid "Print at actual size (no \"fit to page\"), then check that both bars measure 100 mm."
msgstr "Print at actual size (no \"fit to page\"), then check that both bars measure 100 mm."
#: board_photo_markers.py
msgid "Cut along the dashed lines and stick each piece outside a corner of the honeycomb, its inner corner on that corner."
msgstr "Cut along the dashed lines and stick each piece outside a corner of the honeycomb, its inner corner on that corner."
#: board_photo_markers.py
msgid "Marker size: {:g} mm"
msgstr "Marker size: {:g} mm"
#: board_photo_markers.py
msgid "printer correction: X {:.1f} %, Y {:.1f} %"
msgstr "printer correction: X {:.1f} %, Y {:.1f} %"
#: board_photo_markers.py
msgid "Top left"
msgstr "Top left"
#: board_photo_markers.py
msgid "Top right"
msgstr "Top right"
#: board_photo_markers.py
msgid "Bottom right"
msgstr "Bottom right"
#: board_photo_markers.py
msgid "Origin - bottom left"
msgstr "Origin - bottom left"
#: board_photo_markers.py
msgid "Cutting line"
msgstr "Cutting line"
#: board_photo_markers.py
msgid "Alignment ticks"
msgstr "Alignment ticks"
#: board_photo_markers.py
msgid "Scale bar X"
msgstr "Scale bar X"
#: board_photo_markers.py
msgid "100 mm (X)"
msgstr "100 mm (X)"
#: board_photo_markers.py
msgid "Scale bar Y"
msgstr "Scale bar Y"
#: board_photo_markers.py
msgid "100 mm (Y)"
msgstr "100 mm (Y)"
+640
View File
@@ -0,0 +1,640 @@
# Traduction (fr) de l'extension Inkscape « Board photo ».
# Genere par i18n.py ; ne modifier que les msgstr.
msgid ""
msgstr ""
"Project-Id-Version: board_photo\n"
"Language: fr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: board_photo_import.inx
msgid "Board photo: import and calibrate"
msgstr "Photo de planche : importer et calibrer"
#: board_photo_import.inx board_photo_markers.inx
msgid "Work area"
msgstr "Zone de travail"
#: board_photo_import.inx
msgid "Honeycomb = laser work area (mm)"
msgstr "Nid d'abeille = zone de travail de la laser (mm)"
#: board_photo_import.inx board_photo_markers.inx
msgid "Width (mm):"
msgstr "Largeur (mm) :"
#: board_photo_import.inx board_photo_markers.inx
msgid "Height (mm):"
msgstr "Hauteur (mm) :"
#: board_photo_import.inx board_photo_markers.inx
msgid "Set the page to the work area size"
msgstr "Mettre la page à la taille de la zone de travail"
#: board_photo_import.inx board_photo_markers.py
msgid "Calibration markers"
msgstr "Repères de calibration"
#: board_photo_import.inx
msgid "Marker position:"
msgstr "Position des repères :"
#: board_photo_import.inx
msgid "Around the honeycomb: the inner corner of each paper piece touches a corner of the honeycomb"
msgstr "Autour du nid d'abeille : le coin intérieur de chaque pièce de papier touche un angle du nid"
#: board_photo_import.inx
msgid "Custom: centre of the origin marker and spacing below"
msgstr "Personnalisée : centre du repère origine et écart ci-dessous"
#: board_photo_import.inx board_photo_markers.inx
msgid "Marker size (mm):"
msgstr "Taille des repères (mm) :"
#: board_photo_import.inx
msgid "Side of the black square; the paper piece is twice as large"
msgstr "Côté du carré noir ; la pièce de papier est deux fois plus grande"
#: board_photo_import.inx
msgid "Around the honeycomb, everything is deduced: the bottom left corner of the honeycomb is the laser origin (bottom left of the page), and the spacing is the honeycomb size plus twice the marker size. The values below are only used for a custom position."
msgstr "Autour du nid d'abeille, tout est déduit : l'angle bas gauche du nid est l'origine laser (bas gauche de la page) et l'écart vaut la taille du nid plus deux fois la taille des repères. Les valeurs ci-dessous ne servent que pour une position personnalisée."
#: board_photo_import.inx board_photo_markers.inx
msgid "Origin marker centre X (mm):"
msgstr "Centre du repère origine X (mm) :"
#: board_photo_import.inx board_photo_markers.inx
msgid "Distance from the laser origin to the centre of the two-dot marker, along X; negative when the markers are around the work area (left of the origin)"
msgstr "Distance de l'origine laser au centre du repère à deux pastilles, selon X ; négative si les repères sont autour de la zone de travail (à gauche de l'origine)"
#: board_photo_import.inx board_photo_markers.inx
msgid "Origin marker centre Y (mm):"
msgstr "Centre du repère origine Y (mm) :"
#: board_photo_import.inx board_photo_markers.inx
msgid "Distance from the laser origin to the centre of the two-dot marker, along Y (upwards); negative when the markers are around the work area (below the origin)"
msgstr "Distance de l'origine laser au centre du repère à deux pastilles, selon Y (vers le haut) ; négative si les repères sont autour de la zone de travail (sous l'origine)"
#: board_photo_import.inx board_photo_markers.inx
msgid "Spacing between markers X (mm):"
msgstr "Écart entre repères X (mm) :"
#: board_photo_import.inx board_photo_markers.inx
msgid "Spacing between markers Y (mm):"
msgstr "Écart entre repères Y (mm) :"
#: board_photo_import.inx
msgid "Photo"
msgstr "Photo"
#: board_photo_import.inx
msgid "Photo source:"
msgstr "Source de la photo :"
#: board_photo_import.inx
msgid "Photo file"
msgstr "Fichier photo"
#: board_photo_import.inx
msgid "Remote camera (capture server)"
msgstr "Appareil distant (serveur de capture)"
#: board_photo_import.inx
msgid "Photo of the board:"
msgstr "Photo de la planche :"
#: board_photo_import.inx
msgid "Photo taken from above, showing the 4 markers"
msgstr "Photo prise du dessus, où les 4 repères sont visibles"
#: board_photo_import.inx
msgid "Remote camera"
msgstr "Appareil distant"
#: board_photo_import.inx
msgid "Address of the remote machine (IP or IP:port):"
msgstr "Adresse de la machine distante (IP ou IP:port) :"
#: board_photo_import.inx
msgid "Machine running the capture server, for example 192.168.1.20"
msgstr "Machine qui fait tourner le serveur de capture, par exemple 192.168.1.20"
#: board_photo_import.inx
msgid "Port:"
msgstr "Port :"
#: board_photo_import.inx
msgid "Picture:"
msgstr "Image :"
#: board_photo_import.inx
msgid "Take a new photo (/capture)"
msgstr "Prendre une nouvelle photo (/capture)"
#: board_photo_import.inx
msgid "Use the last photo taken (/old)"
msgstr "Reprendre la dernière photo prise (/old)"
#: board_photo_import.inx
msgid "Timeout (s):"
msgstr "Délai d'attente (s) :"
#: board_photo_import.inx
msgid "Resolution of the calibrated photo (px/mm):"
msgstr "Résolution de la photo calibrée (px/mm) :"
#: board_photo_import.inx
msgid "4 px/mm = 0.25 mm per pixel; higher values make a heavier document"
msgstr "4 px/mm = 0,25 mm par pixel ; une valeur plus élevée alourdit le document"
#: board_photo_import.inx
msgid "JPEG quality:"
msgstr "Qualité JPEG :"
#: board_photo_import.inx
msgid "Board detection"
msgstr "Détection de la planche"
#: board_photo_import.inx
msgid "Vectorize the board outline and holes"
msgstr "Vectoriser le contour et les trous de la planche"
#: board_photo_import.inx
msgid "Board tone:"
msgstr "Teinte de la planche :"
#: board_photo_import.inx
msgid "Lighter than the bed (light wood on honeycomb)"
msgstr "Plus claire que le fond (bois clair sur nid d'abeille)"
#: board_photo_import.inx
msgid "Darker than the bed (dark board on light surface)"
msgstr "Plus foncée que le fond (planche sombre sur surface claire)"
#: board_photo_import.inx
msgid "Threshold (0 = automatic):"
msgstr "Seuil (0 = automatique) :"
#: board_photo_import.inx
msgid "Grey level between board and bed; 0 computes it automatically (Otsu)"
msgstr "Niveau de gris séparant planche et fond ; 0 le calcule automatiquement (Otsu)"
#: board_photo_import.inx
msgid "Smoothing (mm):"
msgstr "Lissage (mm) :"
#: board_photo_import.inx
msgid "Removes specks and fills small notches smaller than about twice this value"
msgstr "Supprime les poussières et comble les petites encoches de moins de deux fois cette valeur environ"
#: board_photo_import.inx
msgid "Minimum hole area (mm²):"
msgstr "Aire minimale d'un trou (mm²) :"
#: board_photo_import.inx
msgid "Smaller holes are ignored (filled)"
msgstr "Les trous plus petits sont ignorés (bouchés)"
#: board_photo_import.inx
msgid "Outline tolerance (mm):"
msgstr "Tolérance du contour (mm) :"
#: board_photo_import.inx
msgid "Maximum deviation allowed when simplifying the outline"
msgstr "Écart maximal admis lors de la simplification du contour"
#: board_photo_import.inx
msgid "Outline colour:"
msgstr "Couleur du contour :"
#: board_photo_import.inx board_photo_markers.inx
msgid "Diagram"
msgstr "Schéma"
#: board_photo_import.inx board_photo_markers.inx
msgid "Help"
msgstr "Aide"
#: board_photo_import.inx
msgid ""
"1. Print the 4 markers (Board photo: print\n"
" calibration markers, A4 sheet) and stick\n"
" them at the corners of the honeycomb.\n"
"2. Lay the board on the bed and take a photo\n"
" from above showing the 4 markers.\n"
"3. With nothing selected, choose the photo\n"
" file, or the address of the remote camera\n"
" (capture server), and apply: the photo is\n"
" straightened and\n"
" placed at the exact scale of the work area,\n"
" with the board outline and holes.\n"
"4. Draw or place the shapes in the \"Cuts\"\n"
" layer, on the board, then export them with\n"
" \"Export to LaserGRBL\".\n"
"\n"
"If the markers are not found, the raw photo\n"
"is placed with 4 red targets: move them onto\n"
"the marker centres, select the layer content\n"
"(Ctrl+A) and apply again.\n"
"\n"
"Markers around the honeycomb (default): stick\n"
"the 4 printed pieces so that the inner corner\n"
"of each piece touches a corner of the\n"
"honeycomb, the two-dot marker at the bottom\n"
"left. The bottom left corner of the honeycomb\n"
"is then the laser origin, i.e. the bottom left\n"
"of the page, as expected by the export to\n"
"LaserGRBL.\n"
"\n"
"Coordinates are in mm from the laser origin\n"
"(bottom left of the work area)."
msgstr ""
"1. Imprimer les 4 repères (Photo de planche :\n"
" imprimer les repères de calibration, feuille\n"
" A4) et les coller aux angles du nid d'abeille.\n"
"2. Poser la planche et la photographier du\n"
" dessus, les 4 repères bien visibles.\n"
"3. Sans rien sélectionner, choisir le fichier\n"
" photo, ou l'adresse de l'appareil distant\n"
" (serveur de capture), et appliquer : la photo\n"
" est redressée et placée à l'échelle exacte\n"
" de la zone de travail, avec le contour et les\n"
" trous de la planche.\n"
"4. Dessiner ou placer les formes dans le calque\n"
" « Découpes », sur la planche, puis les\n"
" exporter avec « Export to LaserGRBL ».\n"
"\n"
"Si les repères ne sont pas trouvés, la photo\n"
"brute est placée avec 4 viseurs rouges : les\n"
"amener au centre des repères, sélectionner le\n"
"contenu du calque (Ctrl+A) et appliquer.\n"
"\n"
"Repères autour du nid d'abeille (par défaut) :\n"
"coller les 4 pièces imprimées de sorte que le\n"
"coin intérieur de chacune touche un angle du\n"
"nid, le repère à deux pastilles en bas à\n"
"gauche. L'angle bas gauche du nid est alors\n"
"l'origine laser, c'est-à-dire le bas gauche de\n"
"la page, comme l'attend l'export vers\n"
"LaserGRBL.\n"
"\n"
"Coordonnées en mm depuis l'origine laser\n"
"(en bas à gauche de la zone de travail)."
#: board_photo_markers.inx
msgid "Board photo: print calibration markers"
msgstr "Photo de planche : imprimer les repères de calibration"
#: board_photo_markers.inx
msgid "Output:"
msgstr "Sortie :"
#: board_photo_markers.inx
msgid "Markers to engrave on the bed"
msgstr "Repères à graver sur la surface"
#: board_photo_markers.inx
msgid "A4 sheet to print (markers to cut out)"
msgstr "Feuille A4 à imprimer (repères à découper)"
#: board_photo_markers.inx
msgid "Placement guides to engrave on the bed (for printed markers)"
msgstr "Gabarits de pose à graver sur la surface (pour repères imprimés)"
#: board_photo_markers.inx
msgid "Laser work area (mm)"
msgstr "Zone de travail de la laser (mm)"
#: board_photo_markers.inx
msgid "Calibration markers, inside or around the work area (laser origin at the bottom left)"
msgstr "Repères de calibration, dans la zone de travail ou autour (origine laser en bas à gauche)"
#: board_photo_markers.inx
msgid "Printed sheet"
msgstr "Feuille imprimée"
#: board_photo_markers.inx
msgid ""
"Print the sheet at actual size (100 %,\n"
"no \"fit to page\"), preferably from a PDF\n"
"(File > Save a Copy > PDF). Then measure\n"
"both 100 mm bars.\n"
"\n"
"Only if the printer still shrinks the sheet,\n"
"enter the measured lengths below: the sheet\n"
"is enlarged to compensate. Print it again\n"
"and check that the bars now measure 100 mm."
msgstr ""
"Imprimer la feuille en taille réelle (100 %,\n"
"sans « ajuster à la page »), de préférence\n"
"depuis un PDF (Fichier > Enregistrer une\n"
"copie > PDF). Mesurer ensuite les deux\n"
"barres de 100 mm.\n"
"\n"
"Seulement si l'imprimante réduit encore la\n"
"feuille, saisir ci-dessous les longueurs\n"
"mesurées : la feuille est agrandie pour\n"
"compenser. La réimprimer et vérifier que les\n"
"barres mesurent maintenant 100 mm."
#: board_photo_markers.inx
msgid "Measured length of the horizontal bar (mm):"
msgstr "Longueur mesurée de la barre horizontale (mm) :"
#: board_photo_markers.inx
msgid "Measured length of the vertical bar (mm):"
msgstr "Longueur mesurée de la barre verticale (mm) :"
#: board_photo_markers.inx
msgid ""
"Engraved markers: engrave them once, filled,\n"
"on light plates fixed to the bed, keeping a\n"
"light area of twice the marker size around\n"
"each one.\n"
"\n"
"Printed markers:\n"
"1. \"A4 sheet\": print at 100 % (no fit to\n"
" page), check the 100 mm bar, cut out the\n"
" 4 pieces along the dashed lines.\n"
"2. \"Placement guides\": engrave them lightly\n"
" on the bed (thin red lines).\n"
"3. Stick each piece inside its guide, the\n"
" ticks of the piece on the cross.\n"
"\n"
"The markers must stay in place: every photo\n"
"is scaled from them. The marker with two dots\n"
"is the origin marker, at the bottom left\n"
"(laser origin). Use the same settings in\n"
"\"Board photo: import and calibrate\"."
msgstr ""
"Repères gravés : les graver une fois, en\n"
"remplissage, sur des plaques claires fixées à\n"
"la surface, avec une zone claire de deux fois\n"
"la taille du repère autour de chacun.\n"
"\n"
"Repères imprimés :\n"
"1. « Feuille A4 » : imprimer à 100 % (sans\n"
" ajuster à la page), contrôler la barre de\n"
" 100 mm, découper les 4 pièces le long des\n"
" pointillés.\n"
"2. « Gabarits de pose » : les graver\n"
" légèrement sur la surface (traits rouges).\n"
"3. Coller chaque pièce dans son gabarit, les\n"
" traits de la pièce sur la croix.\n"
"\n"
"Les repères doivent rester en place : ils\n"
"donnent l'échelle de chaque photo. Le repère\n"
"à deux pastilles est le repère origine, en bas\n"
"à gauche (origine laser). Utiliser les mêmes\n"
"réglages dans « Photo de planche : importer\n"
"et calibrer »."
#: board_photo_import.py board_photo_markers.py
msgid "Work area, marker spacing and marker size must be strictly positive."
msgstr "La zone de travail, l'écart et la taille des repères doivent être strictement positifs."
#: board_photo_import.py
msgid "Choose the photo of the board in the \"Photo\" tab (or select a photo and 4 markers for a manual calibration)."
msgstr "Choisissez la photo de la planche dans l'onglet « Photo » (ou sélectionnez une photo et 4 viseurs pour une calibration manuelle)."
#: board_photo_import.py
msgid "Photo not found: {}"
msgstr "Photo introuvable : {}"
#: board_photo_import.py
msgid "This file cannot be read as an image: {}"
msgstr "Ce fichier ne peut pas être lu comme une image : {}"
#: board_photo_import.py
msgid "Enter the address of the remote machine in the \"Photo\" tab (for example 192.168.1.20)."
msgstr "Saisissez l'adresse de la machine distante dans l'onglet « Photo » (par exemple 192.168.1.20)."
#: board_photo_import.py
msgid "Invalid remote address: {}"
msgstr "Adresse distante invalide : {}"
#: board_photo_import.py
msgid "The remote machine cannot be reached ({}): check its address, that the capture server is running and that the port is open."
msgstr "La machine distante est injoignable ({}) : vérifiez son adresse, que le serveur de capture tourne et que le port est ouvert."
#: board_photo_import.py
msgid "The remote machine did not answer in time ({}): increase the timeout or check the network."
msgstr "La machine distante n'a pas répondu à temps ({}) : augmentez le délai d'attente ou vérifiez le réseau."
#: board_photo_import.py
msgid "The transfer of the photo was interrupted ({}), even after a second attempt: check the network and try again."
msgstr "Le transfert de la photo a été interrompu ({}), même après une seconde tentative : vérifiez le réseau et recommencez."
#: board_photo_import.py
msgid "The capture server returned an error: {}"
msgstr "Le serveur de capture a renvoyé une erreur : {}"
#: board_photo_import.py
msgid "The capture server did not return an image: {}"
msgstr "Le serveur de capture n'a pas renvoyé d'image : {}"
#: board_photo_import.py
msgid "The image returned by the capture server is too large ({})."
msgstr "L'image renvoyée par le serveur de capture est trop volumineuse ({})."
#: board_photo_import.py
msgid "Remote capture failed: {}"
msgstr "La capture à distance a échoué : {}"
#: board_photo_import.py
msgid "The capture server did not return a readable image ({})."
msgstr "Le serveur de capture n'a pas renvoyé d'image lisible ({})."
#: board_photo_import.py
msgid "Photo received from {} ({} x {} px)."
msgstr "Photo reçue de {} ({} x {} px)."
#: board_photo_import.py
msgid "Manual calibration: select the photo and exactly 4 small shapes centred on the markers (for example Ctrl+A in the \"Manual calibration\" layer). Deselect everything to import a new photo."
msgstr "Calibration manuelle : sélectionnez la photo et exactement 4 petites formes centrées sur les repères (par exemple Ctrl+A dans le calque « Calibration manuelle »). Désélectionnez tout pour importer une nouvelle photo."
#: board_photo_import.py
msgid "The selected image cannot be read (embed it, or check that the linked file still exists)."
msgstr "L'image sélectionnée est illisible (incorporez-la, ou vérifiez que le fichier lié existe encore)."
#: board_photo_import.py
msgid "The selected image has no size."
msgstr "L'image sélectionnée n'a pas de dimensions."
#: board_photo_import.py
msgid "Manual calibration"
msgstr "Calibration manuelle"
#: board_photo_import.py
msgid "Marker target"
msgstr "Viseur de repère"
#: board_photo_import.py
msgid "no dark shape found"
msgstr "aucune forme sombre trouvée"
#: board_photo_import.py
msgid "{} marker(s) found out of 4"
msgstr "{} repère(s) trouvé(s) sur 4"
#: board_photo_import.py
msgid "the markers found do not form a rectangle"
msgstr "les repères trouvés ne forment pas un rectangle"
#: board_photo_import.py
msgid "Automatic marker detection failed ({})."
msgstr "La détection automatique des repères a échoué ({})."
#: board_photo_import.py
msgid "The raw photo was placed in the \"Manual calibration\" layer with 4 red targets: move each target onto the centre of a marker (zoom in), select the layer content (Ctrl+A) and run this extension again."
msgstr "La photo brute a été placée dans le calque « Calibration manuelle » avec 4 viseurs rouges : amenez chaque viseur au centre d'un repère (en zoomant), sélectionnez le contenu du calque (Ctrl+A) et relancez cette extension."
#: board_photo_import.py
msgid "The 4 marker positions do not form a convex quadrilateral: check them and try again."
msgstr "Les 4 positions de repères ne forment pas un quadrilatère convexe : vérifiez-les et recommencez."
#: board_photo_import.py
msgid "The 4 marker positions are aligned: check them and try again."
msgstr "Les 4 positions de repères sont alignées : vérifiez-les et recommencez."
#: board_photo_import.py
msgid "The origin marker (two dots) was not recognised: the photo is assumed upright (origin at the bottom left of the photo)."
msgstr "Le repère origine (deux pastilles) n'a pas été reconnu : la photo est supposée droite (origine en bas à gauche de la photo)."
#: board_photo_import.py
msgid "A marker measures {:.1f} mm instead of {:.1f} mm: check the marker positions and size in the \"Work area\" tab."
msgstr "Un repère mesure {:.1f} mm au lieu de {:.1f} mm : vérifiez la position et la taille des repères dans l'onglet « Zone de travail »."
#: board_photo_import.py
msgid "No board found on the photo: try the other \"Board tone\" or set the threshold by hand."
msgstr "Aucune planche trouvée sur la photo : essayez l'autre « Teinte de la planche » ou réglez le seuil à la main."
#: board_photo_import.py
msgid "The page is not the size of the work area: the export to LaserGRBL takes the bottom left of the page as the laser origin, so tick \"Set the page to the work area size\" before cutting."
msgstr "La page n'a pas la taille de la zone de travail : l'export vers LaserGRBL prend le bas gauche de la page pour origine laser, cochez donc « Mettre la page à la taille de la zone de travail » avant de découper."
#: board_photo_import.py
msgid "Board photo calibrated: {:.2f} mm per photo pixel."
msgstr "Photo de la planche calibrée : {:.2f} mm par pixel de la photo."
#: board_photo_import.py
msgid "{} hole(s) found."
msgstr "{} trou(s) trouvé(s)."
#: board_photo_import.py
msgid "Board photo"
msgstr "Photo de la planche"
#: board_photo_import.py
msgid "Calibrated photo"
msgstr "Photo calibrée"
#: board_photo_import.py
msgid "Board outline"
msgstr "Contour de la planche"
#: board_photo_import.py
msgid "Board outline ({} holes)"
msgstr "Contour de la planche ({} trous)"
#: board_photo_import.py
msgid "Cuts"
msgstr "Découpes"
#: board_photo_markers.py
msgid "The placement guides do not fit in the work area: keep every marker centre at least {:g} mm from the edges (1.5 x the marker size)."
msgstr "Les gabarits de pose ne tiennent pas dans la zone de travail : gardez le centre de chaque repère à au moins {:g} mm des bords (1,5 fois la taille du repère)."
#: board_photo_markers.py
msgid "The markers do not fit in the work area, so the laser cannot engrave them: reduce the spacing or move the origin marker. Markers placed around the work area (negative origin, larger spacing) are printed instead (\"Output\": A4 sheet) and stuck in place by hand."
msgstr "Les repères ne tiennent pas dans la zone de travail, la laser ne peut donc pas les graver : réduisez l'écart ou déplacez le repère origine. Des repères placés autour de la zone de travail (origine négative, écart plus grand) s'impriment à la place (« Sortie » : feuille A4) et se collent à la main."
#: board_photo_markers.py
msgid "The markers are too close to each other: the spacing must be at least twice the marker size."
msgstr "Les repères sont trop proches : l'écart doit valoir au moins deux fois leur taille."
#: board_photo_markers.py
msgid "Origin marker"
msgstr "Repère origine"
#: board_photo_markers.py
msgid "Marker"
msgstr "Repère"
#: board_photo_markers.py
msgid "Marker placement guides"
msgstr "Gabarits de pose des repères"
#: board_photo_markers.py
msgid "These markers are too large for an A4 sheet: reduce the marker size, or engrave them directly on the bed."
msgstr "Ces repères sont trop grands pour une feuille A4 : réduisez leur taille, ou gravez-les directement sur la surface."
#: board_photo_markers.py
msgid "The measured bar lengths must be between 80 and 120 mm."
msgstr "Les longueurs mesurées des barres doivent être comprises entre 80 et 120 mm."
#: board_photo_markers.py
msgid "Calibration markers (print)"
msgstr "Repères de calibration (impression)"
#: board_photo_markers.py
msgid "Calibration markers - print at 100 %"
msgstr "Repères de calibration - imprimer à 100 %"
#: board_photo_markers.py
msgid "Print at actual size (no \"fit to page\"), then check that both bars measure 100 mm."
msgstr "Imprimer en taille réelle (sans « ajuster à la page »), puis vérifier que les deux barres mesurent 100 mm."
#: board_photo_markers.py
msgid "Cut along the dashed lines and stick each piece outside a corner of the honeycomb, its inner corner on that corner."
msgstr "Découpez le long des pointillés et collez chaque pièce à l'extérieur d'un angle du nid d'abeille, son coin intérieur sur cet angle."
#: board_photo_markers.py
msgid "Marker size: {:g} mm"
msgstr "Taille des repères : {:g} mm"
#: board_photo_markers.py
msgid "printer correction: X {:.1f} %, Y {:.1f} %"
msgstr "correction d'imprimante : X {:.1f} %, Y {:.1f} %"
#: board_photo_markers.py
msgid "Top left"
msgstr "Haut gauche"
#: board_photo_markers.py
msgid "Top right"
msgstr "Haut droite"
#: board_photo_markers.py
msgid "Bottom right"
msgstr "Bas droite"
#: board_photo_markers.py
msgid "Origin - bottom left"
msgstr "Origine - bas gauche"
#: board_photo_markers.py
msgid "Cutting line"
msgstr "Ligne de découpe"
#: board_photo_markers.py
msgid "Alignment ticks"
msgstr "Traits d'alignement"
#: board_photo_markers.py
msgid "Scale bar X"
msgstr "Barre de contrôle X"
#: board_photo_markers.py
msgid "100 mm (X)"
msgstr "100 mm (X)"
#: board_photo_markers.py
msgid "Scale bar Y"
msgstr "Barre de contrôle Y"
#: board_photo_markers.py
msgid "100 mm (Y)"
msgstr "100 mm (Y)"
+999
View File
@@ -0,0 +1,999 @@
# coding=utf-8
"""Tests de l'extension « Board photo » (pytest).
Trois familles : noyau geometrique et traitement d'image (sans inkex), bout
en bout des trois entrees de menu (inkex requis), traductions et coherence
des .inx. Le test d'echelle principal genere une photo synthetique en
perspective et verifie que les trous sont retrouves a 0,5 mm pres.
"""
import base64
import io
import math
import os
import re
import socket
import sys
import xml.etree.ElementTree as ET
import numpy as np
import pytest
from PIL import Image
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tests"))
import board_photo_core as core # noqa: E402
import board_photo_remote as remote # noqa: E402
import board_photo_vision as vision # noqa: E402
import synthetic as syn # noqa: E402
EMPTY_MM = os.path.join(HERE, "tests", "data", "empty_mm.svg")
EMPTY_PX = os.path.join(HERE, "tests", "data", "empty_px.svg")
SMALL_MARKERS = os.path.join(HERE, "tests", "data", "small_markers.jpg")
INX_FILES = ["board_photo_import", "board_photo_markers"]
TOLERANCE_MM = 0.5
def square(x0, y0, x1, y1, closed=True):
ring = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
return ring + [ring[0]] if closed else ring
def hole_measures(rings):
"""(centre, diametre equivalent) de chaque trou, tries par abscisse."""
result = []
for ring in rings:
area = abs(core.ring_area(ring))
result.append((core.ring_centroid(ring), 2 * math.sqrt(area / math.pi)))
return sorted(result)
def assert_holes_match(rings, scale=1.0, offset=(0.0, 0.0)):
found = hole_measures([[((x - offset[0]) / scale, (y - offset[1]) / scale)
for x, y in ring] for ring in rings])
expected = sorted((center, 2 * radius) for center, radius in syn.HOLES)
assert len(found) == len(expected)
for (center, diameter), (true_center, true_diameter) in zip(found, expected):
assert math.hypot(center[0] - true_center[0],
center[1] - true_center[1]) < TOLERANCE_MM
assert abs(diameter - true_diameter) < TOLERANCE_MM
# --------------------------------------------------------------------------
# Noyau : reperes, homographie
# --------------------------------------------------------------------------
def test_parse_color():
assert core.parse_color("426885887") == ("#1971c2", 1.0)
assert core.parse_color("#abc") == ("#aabbcc", 1.0)
assert core.parse_color("pas une couleur") == ("#b3b3b3", 1.0)
def test_polylines_to_d_closed():
d = core.polylines_to_d([[(0, 0), (1, 2), (3, 0)]], precision=1, closed=True)
assert d == "M 0.0,0.0 L 1.0,2.0 L 3.0,0.0 Z"
def test_laser_svg_conversion_is_involutive():
assert core.laser_to_svg((10, 30), 400) == (10.0, 370.0)
assert core.svg_to_laser(core.laser_to_svg((12.5, 7), 300), 300) == (12.5, 7.0)
def test_marker_layout_origin_bottom_left():
points = core.marker_layout(400, 15, 20, 370, 350)
assert points[core.ORIGIN_MARKER] == (15.0, 380.0)
assert points[core.TOP_LEFT] == (15.0, 30.0)
assert points[core.TOP_RIGHT] == (385.0, 30.0)
assert points[core.BOTTOM_RIGHT] == (385.0, 380.0)
def test_layout_problems():
assert core.layout_problems(400, 400, 15, 15, 370, 370, 20) == []
assert "outside" in core.layout_problems(400, 400, 15, 15, 380, 370, 20)
assert "outside" in core.layout_problems(400, 400, 5, 15, 370, 370, 20)
assert "too_close" in core.layout_problems(400, 400, 15, 15, 30, 370, 20)
assert core.layout_problems(0, 400, 15, 15, 370, 370, 20) == ["non_positive"]
# Gabarits de pose : 30 mm d'emprise autour du centre pour des reperes de 20 mm.
assert core.guide_reach(20) == 30
assert "outside" in core.layout_problems(400, 400, 15, 15, 370, 370, 20, 30)
assert core.layout_problems(400, 400, 30, 30, 340, 340, 20, 30) == []
def test_marker_rings():
ordinary = core.marker_rings((50, 50), 20)
origin = core.marker_rings((50, 50), 20, origin=True)
assert len(ordinary) == 2 and len(origin) == 3
assert abs(abs(core.ring_area(ordinary[0])) - 400) < 1e-9
assert core.ring_centroid(ordinary[1]) == pytest.approx((50, 50))
def test_homography_maps_points_exactly():
src = [(120.5, 80.2), (1830.0, 140.7), (1760.3, 1320.9), (90.1, 1250.0)]
dst = [(15, 15), (385, 15), (385, 385), (15, 385)]
matrix = core.homography(src, dst)
assert np.allclose(core.apply_homography(matrix, src), dst, atol=1e-7)
back = core.homography(dst, src)
assert np.allclose(core.apply_homography(back @ matrix, src), src, atol=1e-6)
def test_homography_degenerate():
with pytest.raises(ValueError):
core.homography([(0, 0), (1, 1), (2, 2), (3, 3)], [(0, 0), (1, 0), (1, 1), (0, 1)])
def test_local_scale():
matrix = core.homography([(0, 0), (10, 0), (10, 10), (0, 10)],
[(0, 0), (25, 0), (25, 25), (0, 25)])
assert core.local_scale(matrix, (5, 5)) == pytest.approx(2.5)
def test_order_corners_and_origin():
shuffled = [(90, 95), (10, 12), (8, 88), (95, 5)]
assert core.order_corners(shuffled) == [(10, 12), (95, 5), (90, 95), (8, 88)]
ordered = ["a", "b", "c", "d"]
assert core.rotate_to_origin(ordered, 3) == ordered
assert core.rotate_to_origin(ordered, 1)[core.ORIGIN_MARKER] == "b"
assert core.rotate_to_origin(ordered, 1) == ["c", "d", "a", "b"]
def test_sheet_layout_fits_a4():
centers = core.sheet_layout(20)
side = core.piece_side(20)
assert len(centers) == 4
for cx, cy in centers:
assert side / 2 <= cx <= core.A4[0] - side / 2
assert side / 2 <= cy <= core.A4[1] - side / 2
# Meme disposition que sur la surface : origine en bas a gauche.
tl, tr, br, bl = centers
assert bl[0] == tl[0] < tr[0] == br[0] and tl[1] == tr[1] < bl[1] == br[1]
assert tr[0] - tl[0] >= side and bl[1] - tl[1] >= side # pieces disjointes
assert core.sheet_layout(40) is not None
assert core.sheet_layout(45) is None
assert core.sheet_layout(0) is None
def test_piece_ticks_and_guides():
ticks = core.piece_ticks((50, 50), 20)
assert len(ticks) == 4
assert ticks[0] == [(30, 50), (33, 50)] # du bord vers le centre, 3 mm
guide = core.guide_lines((50, 50), 20)
assert guide[0][0] == guide[0][-1] == (30, 30) # contour ferme de 40 mm
xs = [x for line in guide[1:] for x, _y in line]
assert min(xs) == 20 and max(xs) == 80 # croix : 10 mm de chaque cote
# Les traits de la piece prolongent exactement la croix du gabarit.
assert all(y == 50 for line in guide[1:3] + ticks[:2] for _x, y in line)
def test_scale_bar():
bar = core.scale_bar((10, 100))
assert bar[0] == [(10, 100), (110, 100)]
assert len(bar) == 12
vertical = core.scale_bar((200, 50), vertical=True)
assert vertical[0] == [(200, 50), (200, 150)]
assert all(line[1][0] < 200 for line in vertical[1:]) # graduations vers la gauche
def test_print_correction():
fx, fy = core.print_correction(97, 100)
assert fx == pytest.approx(100 / 97) and fy == 1.0
stretched = core.stretch_rings([[(5, 10), (15, 10)]], fx, fy, (105, 148.5))
# Barre de 10 mm dessinee 10,31 mm : imprimee a 97 %, elle mesure 10 mm.
length = stretched[0][1][0] - stretched[0][0][0]
assert length * 0.97 == pytest.approx(10)
assert stretched[0][0][1] == 10
def test_is_convex_quad():
assert core.is_convex_quad([(0, 0), (1, 0), (1, 1), (0, 1)])
assert not core.is_convex_quad([(0, 0), (1, 1), (1, 0), (0, 1)])
# --------------------------------------------------------------------------
# Noyau : contours
# --------------------------------------------------------------------------
def test_mask_to_rings_square():
mask = np.zeros((6, 6), dtype=bool)
mask[1:4, 2:5] = True
rings = core.mask_to_rings(mask)
assert len(rings) == 1
# Milieux des aretes : carre 3x3 aux coins coupes de 4 x 1/8.
assert abs(core.ring_area(rings[0])) == pytest.approx(9 - 0.5)
assert core.ring_centroid(rings[0]) == pytest.approx((3.5, 2.5))
def test_mask_to_rings_hole_and_diagonal():
mask = np.ones((7, 7), dtype=bool)
mask[2:5, 2:5] = False
assert len(core.mask_to_rings(mask)) == 2
diagonal = np.array([[1, 0], [0, 1]], dtype=bool)
rings = core.mask_to_rings(diagonal)
assert len(rings) == 2 # deux pixels qui ne se touchent que par un coin
def test_simplify_ring_removes_staircase():
mask = np.zeros((60, 60), dtype=bool)
rows, cols = np.mgrid[0:60, 0:60]
mask[(rows - 30) ** 2 + (cols - 30) ** 2 <= 25 ** 2] = True
ring = core.mask_to_rings(mask)[0]
simple = core.simplify_ring(ring, 0.6)
assert len(simple) < len(ring) / 3
assert abs(core.ring_area(simple)) == pytest.approx(math.pi * 625, rel=0.02)
assert core.simplify_ring(ring, 0) == ring
# --------------------------------------------------------------------------
# Traitement d'image
# --------------------------------------------------------------------------
def test_label_components_connectivity():
mask = np.array([[1, 1, 0, 0],
[0, 0, 1, 0],
[1, 0, 0, 0],
[1, 0, 1, 1]], dtype=bool)
_labels, count4, areas4 = vision.label_components(mask, 4)
assert count4 == 4 and sorted(areas4[1:].tolist()) == [1, 2, 2, 2]
labels8, count8, _areas8 = vision.label_components(mask, 8)
assert count8 == 3
assert labels8[0, 0] == labels8[1, 2]
assert vision.label_components(np.zeros((3, 3), bool), 4)[1] == 0
def test_label_components_u_shape():
# Deux branches reliees seulement par le bas : fusion tardive des plages.
mask = np.zeros((5, 7), dtype=bool)
mask[0:4, 1] = mask[0:4, 5] = True
mask[4, 1:6] = True
assert vision.label_components(mask, 4)[1] == 1
def test_fill_holes():
mask = np.ones((9, 9), dtype=bool)
mask[2:4, 2:4] = False
mask[5:8, 5:8] = False
mask[0, 4] = False # encoche au bord : pas un trou
filled, holes = vision.fill_holes(mask, min_area=5)
assert len(holes) == 1 and holes[0].sum() == 9
assert filled[2, 2] and filled[6, 6] and not filled[0, 4]
def test_otsu_threshold():
values = np.concatenate([np.full(500, 40), np.full(500, 200)]).astype(np.uint8)
assert 40 <= vision.otsu_threshold(values) < 200
def test_rectify_keeps_pixel_grid():
"""Homographie identite a 1 px/mm : l'image ressort identique (pas de decalage)."""
rng = np.random.default_rng(1)
data = rng.integers(0, 255, (40, 60), dtype=np.uint8)
image = Image.fromarray(data).convert("RGB")
result, valid = vision.rectify(image, np.eye(3), 60, 40, 1.0)
out = np.asarray(result.convert("L"), dtype=int)
assert result.size == (60, 40) and valid.all()
assert np.abs(out[2:-2, 2:-2] - data[2:-2, 2:-2].astype(int)).max() <= 2
def test_rectify_scale():
"""Un point blanc a (30 mm, 10 mm) ressort au bon pixel a 4 px/mm."""
data = np.zeros((40, 60), dtype=np.uint8)
data[10, 30] = 255
image = Image.fromarray(data).convert("RGB")
result, _valid = vision.rectify(image, np.eye(3), 60, 40, 4.0)
out = np.asarray(result.convert("L"), dtype=float)
rows, cols = np.mgrid[0:out.shape[0], 0:out.shape[1]]
total = out.sum()
x = ((cols + 0.5) * out).sum() / total / 4.0
y = ((rows + 0.5) * out).sum() / total / 4.0
assert (x, y) == pytest.approx((30.5, 10.5), abs=0.05)
@pytest.fixture(scope="module")
def photo():
return syn.render_photo()
@pytest.mark.parametrize("rotate", [0, 1, 2, 3])
def test_detect_markers_any_orientation(rotate):
picture = syn.render_photo(seed=rotate, rotate=rotate)
found = vision.detect_markers(vision.gray_array(picture))
assert found["oriented"]
assert found["dots"] == [1, 1, 1, 2]
truth = syn.marker_pixels(rotate)
for point, true_point in zip(found["points"], truth):
assert math.hypot(point[0] - true_point[0], point[1] - true_point[1]) < 1.5
def test_printed_markers_on_guides():
"""Reperes imprimes colles sur leur gabarit : traits et croix ne gene pas."""
picture = syn.render_photo(seed=7, printed=True)
found = vision.detect_markers(vision.gray_array(picture))
assert found["oriented"] and found["dots"] == [1, 1, 1, 2]
for point, true_point in zip(found["points"], syn.marker_pixels()):
assert math.hypot(point[0] - true_point[0], point[1] - true_point[1]) < 1.5
matrix = core.homography(found["points"], syn.markers())
rectified, valid = vision.rectify(picture, matrix, syn.WIDTH, syn.HEIGHT, 4.0)
exclude = [(x - 20, y - 20, x + 20, y + 20) for x, y in syn.markers()]
board = vision.extract_board(vision.gray_array(rectified), valid, 4.0, exclude=exclude)
assert_holes_match(board["rings"][1:])
def test_detect_markers_small_real_photo():
"""Vraie photo 800 x 600 : reperes d'environ 22 px, dont deux colles aux
rails sombres de la machine (le seuil adaptatif large les fragmentait)."""
found = vision.detect_markers(vision.gray_array(vision.load_photo(SMALL_MARKERS)))
assert found["oriented"] and found["dots"] == [1, 1, 1, 2]
truth = [(146, 53), (658, 34), (685, 550), (158, 568)]
for point, true_point in zip(found["points"], truth):
assert math.hypot(point[0] - true_point[0], point[1] - true_point[1]) < 3
def test_detect_markers_failure():
blank = np.full((600, 800), 128, dtype=np.uint8)
with pytest.raises(vision.MarkerError):
vision.detect_markers(blank)
def test_dots_near_manual_points(photo):
dots = vision.dots_near(vision.gray_array(photo), syn.marker_pixels())
assert dots == [1, 1, 1, 2]
def test_scale_is_respected(photo):
"""Chaine complete sur photo en perspective : trous retrouves a 0,5 mm pres."""
found = vision.detect_markers(vision.gray_array(photo))
matrix = core.homography(found["points"], syn.markers())
rectified, valid = vision.rectify(photo, matrix, syn.WIDTH, syn.HEIGHT, 4.0)
assert rectified.size == (1600, 1600)
exclude = [(x - 20, y - 20, x + 20, y + 20) for x, y in syn.markers()]
board = vision.extract_board(vision.gray_array(rectified), valid, 4.0, exclude=exclude)
assert board["holes"] == 3
assert_holes_match(board["rings"][1:])
corners = board["rings"][0]
for true_corner in syn.BOARD:
assert min(math.hypot(x - true_corner[0], y - true_corner[1])
for x, y in corners) < 1.0
expected_area = abs(core.ring_area(syn.BOARD)) - sum(
math.pi * r * r for _c, r in syn.HOLES)
assert board["area"] == pytest.approx(expected_area, rel=0.01)
def test_extract_board_none_and_min_hole():
gray = np.full((200, 200), 60, dtype=np.uint8)
valid = np.ones_like(gray, dtype=bool)
assert vision.extract_board(gray, valid, 4.0) is None
gray[20:180, 20:180] = 210
gray[50:54, 50:54] = 60 # trou de 1 mm2 : ignore
gray[100:120, 100:120] = 60 # trou de 25 mm2 : garde
board = vision.extract_board(gray, valid, 4.0, smoothing=0, min_hole_area=4.0)
assert board["holes"] == 1
dark = vision.extract_board(255 - gray, valid, 4.0, lighter=False, smoothing=0)
assert dark["holes"] == 1
# --------------------------------------------------------------------------
# Bout en bout (necessite inkex)
# --------------------------------------------------------------------------
def run(tmp_path, cls_name, module, source, *args):
pytest.importorskip("inkex")
if module == "board_photo_import" and not any(
str(a).startswith("--marker_placement") for a in args):
# Scene synthetique : reperes dans la zone de travail (origine 30 mm,
# ecart 340 mm), donc position personnalisee.
args = args + ("--marker_placement=custom",)
extension = getattr(__import__(module), cls_name)
out = tmp_path / "out.svg"
extension().run([*args, "--output={}".format(out), str(source)])
if not out.exists():
return None # document inchange (message d'erreur)
import inkex
return inkex.load_svg(str(out)).getroot()
def layers(svg, key):
return svg.xpath("//*[@data-board-photo='{}']".format(key))
def outline_rings(svg):
import inkex
path = layers(svg, "outline-path")[0]
return [[(p[1][0], p[1][1]) for p in sub]
for sub in inkex.Path(path.get("d")).to_superpath()]
def test_markers_end_to_end(tmp_path):
svg = run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM)
assert svg.get("width") == "400mm" and svg.get("viewBox") == "0 0 400 400"
paths = layers(svg, "markers")[0].findall("{http://www.w3.org/2000/svg}path")
assert len(paths) == 4
origin = paths[core.ORIGIN_MARKER]
assert origin.get("d").count("M") == 3
box = origin.bounding_box()
assert (box.center.x, box.center.y) == pytest.approx((30, 370))
assert box.width == pytest.approx(20)
def test_markers_print_sheet(tmp_path):
svg = run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM,
"--mode=sheet", "--work_width=600")
assert (svg.get("width"), svg.get("height")) == ("210mm", "297mm")
sheet = layers(svg, "sheet")[0]
paths = sheet.findall("{http://www.w3.org/2000/svg}path")
markers = [p for p in paths if "fill:#000000" in str(p.get("style"))]
assert len(markers) == 4
# Taille imprimee exacte : carre de 20 mm, piece de 40 mm.
assert markers[0].bounding_box().width == pytest.approx(20)
cuts = [p for p in paths if "stroke-dasharray" in str(p.get("style"))]
assert len(cuts) == 4 and cuts[0].bounding_box().width == pytest.approx(40)
bar_x = [p for p in paths if p.label == "Scale bar X"][0]
bar_y = [p for p in paths if p.label == "Scale bar Y"][0]
assert bar_x.bounding_box().width == pytest.approx(100)
assert bar_y.bounding_box().height == pytest.approx(100)
texts = "".join(t.text or "" for t in sheet.findall("{http://www.w3.org/2000/svg}text"))
assert "100 %" in texts and "Origin" in texts and "correction" not in texts
# Tout le dessin tient dans la page A4.
for path in paths:
box = path.bounding_box()
assert 0 < box.left and box.right < 210 and 0 < box.top and box.bottom < 297
def test_markers_print_sheet_correction(tmp_path):
"""Imprimante qui reduit a 97 % en X : la feuille est dessinee 100/97 plus large."""
svg = run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM,
"--mode=sheet", "--print_x=97")
sheet = layers(svg, "sheet")[0]
paths = sheet.findall("{http://www.w3.org/2000/svg}path")
bar_x = [p for p in paths if p.label == "Scale bar X"][0]
bar_y = [p for p in paths if p.label == "Scale bar Y"][0]
assert bar_x.bounding_box().width * 0.97 == pytest.approx(100, abs=1e-3)
assert bar_y.bounding_box().height == pytest.approx(100)
marker = [p for p in paths if "fill:#000000" in str(p.get("style"))][0]
box = marker.bounding_box()
assert box.width * 0.97 == pytest.approx(20, abs=1e-3)
assert box.height == pytest.approx(20, abs=1e-3)
texts = "".join(t.text or "" for t in sheet.findall("{http://www.w3.org/2000/svg}text"))
assert "X 103.1 %, Y 100.0 %" in texts
for path in paths:
box = path.bounding_box()
assert 0 < box.left and box.right < 210 and 0 < box.top and box.bottom < 297
def test_markers_print_sheet_bad_correction(tmp_path, capsys):
run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM,
"--mode=sheet", "--print_y=50")
assert "between 80 and 120 mm" in capsys.readouterr().err
def test_markers_print_sheet_too_large(tmp_path, capsys):
run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM,
"--mode=sheet", "--marker_size=60")
assert "too large for an A4 sheet" in capsys.readouterr().err
def test_markers_guides(tmp_path):
svg = run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM,
"--mode=guides")
assert svg.get("width") == "400mm"
paths = layers(svg, "guides")[0].findall("{http://www.w3.org/2000/svg}path")
assert len(paths) == 4 and not layers(svg, "markers")
box = paths[core.ORIGIN_MARKER].bounding_box()
assert (box.center.x, box.center.y) == pytest.approx((30, 370))
assert box.width == pytest.approx(60) # piece de 40 mm + croix de 10 mm
def test_markers_guides_outside(tmp_path, capsys):
run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM,
"--mode=guides", "--origin_x=15")
assert "at least 30 mm from the edges" in capsys.readouterr().err
def test_markers_error(tmp_path, capsys):
run(tmp_path, "BoardPhotoMarkers", "board_photo_markers", EMPTY_MM, "--spacing_x=390")
assert "do not fit" in capsys.readouterr().err
@pytest.fixture(scope="module")
def photo_file(tmp_path_factory, photo):
path = tmp_path_factory.mktemp("photo") / "board.jpg"
photo.save(str(path), quality=92)
return path
def test_import_end_to_end_mm(tmp_path, photo_file, capsys):
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
"--photo={}".format(photo_file))
assert "3 hole(s)" in capsys.readouterr().err
assert (svg.get("width"), svg.get("height")) == ("400mm", "400mm")
image = layers(svg, "photo")[0][0]
assert [float(image.get(k)) for k in ("x", "y", "width", "height")] == [0, 0, 400, 400]
assert image.get("preserveAspectRatio") == "none"
assert layers(svg, "photo")[0].get("sodipodi:insensitive") == "true"
rings = outline_rings(svg)
assert len(rings) == 4
assert_holes_match(rings[1:])
cuts = layers(svg, "cuts")
assert len(cuts) == 1
assert svg.namedview.get("inkscape:current-layer") == cuts[0].get_id()
# Ordre des calques : photo sous le contour, lui-meme sous Cuts.
order = [child.get("data-board-photo") for child in svg if child.get("data-board-photo")]
assert order == ["photo", "outline", "cuts"]
def test_import_keeps_document_scale(tmp_path, photo_file):
"""Document en px : l'echelle existante est gardee, le resultat reste en mm."""
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_PX,
"--photo={}".format(photo_file))
scale = 96 / 25.4
assert svg.get("width") == "400mm"
assert svg.unittouu("1mm") == pytest.approx(scale)
image = layers(svg, "photo")[0][0]
assert float(image.get("width")) == pytest.approx(400 * scale, rel=1e-6)
existing = svg.getElementById("existing")
assert float(existing.get("width")) == 96 # objet existant intact
assert_holes_match(outline_rings(svg)[1:], scale=scale)
def test_import_twice_replaces_layers(tmp_path, photo_file):
first = tmp_path / "first"
first.mkdir()
run(first, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
"--photo={}".format(photo_file))
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", first / "out.svg",
"--photo={}".format(photo_file), "--vectorize=false")
assert len(layers(svg, "photo")) == 1
assert not layers(svg, "outline") and len(layers(svg, "cuts")) == 1
def test_import_errors(tmp_path, capsys):
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM)
assert "Choose the photo" in capsys.readouterr().err
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
"--photo={}".format(tmp_path / "nothing.jpg"))
assert "not found" in capsys.readouterr().err
def test_import_falls_back_to_manual(tmp_path, capsys):
blank = tmp_path / "blank.jpg"
Image.new("RGB", (800, 600), (128, 128, 128)).save(str(blank))
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
"--photo={}".format(blank))
assert "detection failed" in capsys.readouterr().err
manual = layers(svg, "manual")
assert len(manual) == 1 and len(manual[0]) == 5
assert not layers(svg, "photo")
def manual_document(tmp_path, photo, points, scale=0.1):
"""Photo incorporee (0,1 mm par pixel) + 4 cercles poses sur les reperes."""
import io
buffer = io.BytesIO()
photo.save(buffer, "JPEG", quality=92)
href = "data:image/jpeg;base64," + base64.b64encode(buffer.getvalue()).decode()
circles = "".join(
'<circle id="t{}" cx="{}" cy="{}" r="1.5" fill="none" stroke="red"/>'.format(
k, x * scale + 5, y * scale + 7) for k, (x, y) in enumerate(points))
source = tmp_path / "manual.svg"
source.write_text(
'<svg xmlns="http://www.w3.org/2000/svg" '
'xmlns:xlink="http://www.w3.org/1999/xlink" '
'xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" '
'xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" '
'width="400mm" height="400mm" viewBox="0 0 400 400">'
'<sodipodi:namedview id="nv"/>'
'<g id="manual" inkscape:groupmode="layer" data-board-photo="manual">'
'<image id="photo" x="0" y="0" width="{}" height="{}" '
'transform="translate(5,7)" preserveAspectRatio="none" xlink:href="{}"/>'
'{}</g></svg>'.format(photo.width * scale, photo.height * scale, href, circles),
encoding="utf-8")
return source
def test_import_manual_calibration(tmp_path, photo):
# Cercles donnes dans le desordre : l'ordre et l'orientation sont retrouves.
points = syn.marker_pixels()
order = [2, 0, 3, 1]
source = manual_document(tmp_path, photo, [points[k] for k in order])
ids = ["--id=photo"] + ["--id=t{}".format(k) for k in range(4)]
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", source, *ids)
assert not layers(svg, "manual")
assert_holes_match(outline_rings(svg)[1:])
def test_import_manual_bad_selection(tmp_path, photo, capsys):
source = manual_document(tmp_path, photo, syn.marker_pixels()[:3])
run(tmp_path, "BoardPhotoImport", "board_photo_import", source,
"--id=photo", "--id=t0", "--id=t1", "--id=t2")
assert "exactly 4" in capsys.readouterr().err
# --------------------------------------------------------------------------
# Camera distante : faux serveur de capture (memes routes que le serveur Flask)
# --------------------------------------------------------------------------
class Camera:
"""Faux serveur de capture lance dans son propre processus (tests/fake_camera.py)."""
def __init__(self, port, folder):
self.port = port
self.folder = folder
@property
def calls(self):
path = os.path.join(self.folder, "calls.txt")
if not os.path.exists(path):
return []
with open(path) as handle:
return handle.read().split()
def broken(self, value):
flag = os.path.join(self.folder, "broken")
if value:
open(flag, "w").close()
elif os.path.exists(flag):
os.remove(flag)
@pytest.fixture(scope="module")
def camera(tmp_path_factory, photo):
import subprocess
folder = tmp_path_factory.mktemp("camera")
jpeg = folder / "photo.jpg"
photo.save(str(jpeg), "JPEG", quality=92)
process = subprocess.Popen(
[sys.executable, os.path.join(HERE, "tests", "fake_camera.py"), str(jpeg),
str(folder)], stdout=subprocess.PIPE, text=True)
try:
port = int(process.stdout.readline())
yield Camera(port, str(folder))
finally:
process.kill()
process.wait()
def free_port():
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def test_remote_url():
assert remote.remote_url("192.168.1.20") == "http://192.168.1.20:5000/capture"
assert remote.remote_url(" 192.168.1.20:8080 ", 5000, "old") == \
"http://192.168.1.20:8080/old"
assert remote.remote_url("http://camera.local/photo", 5001) == \
"http://camera.local:5001/capture"
assert remote.remote_url("fe80::1", 5000) == "http://[fe80::1]:5000/capture"
for bad, reason in (("", "no_host"), ("192.168.1.20:99999", "bad_host"),
("ftp://camera", "bad_host")):
with pytest.raises(remote.RemoteError) as info:
remote.remote_url(bad)
assert info.value.reason == reason
with pytest.raises(remote.RemoteError):
remote.remote_url("camera", endpoint="photo")
def test_fetch_photo(camera):
data = remote.fetch_photo(remote.remote_url("127.0.0.1", camera.port, "old"), 5)
assert vision.load_photo(data).size == syn.PHOTO_SIZE
assert camera.calls[-1] == "/old"
def test_fetch_photo_errors(camera):
camera.broken(True)
try:
with pytest.raises(remote.RemoteError) as info:
remote.fetch_photo(remote.remote_url("127.0.0.1", camera.port), 5)
assert info.value.reason == "http"
assert "500" in info.value.detail and "Could not access" in info.value.detail
finally:
camera.broken(False)
before = len(camera.calls)
with pytest.raises(remote.RemoteError) as info:
remote.fetch_photo("http://127.0.0.1:{}/cut".format(camera.port), 5)
assert info.value.reason == "interrupted" and "1000" in info.value.detail
assert camera.calls[before:] == ["/cut", "/cut"] # une nouvelle tentative
with pytest.raises(remote.RemoteError) as info:
remote.fetch_photo("http://127.0.0.1:{}/text".format(camera.port), 5)
assert info.value.reason == "not_image" and "Photo save" in info.value.detail
with pytest.raises(remote.RemoteError) as info:
remote.fetch_photo(remote.remote_url("127.0.0.1", free_port()), 5)
assert info.value.reason in ("unreachable", "timeout")
def test_import_remote_camera(tmp_path, camera, capsys):
port = camera.port
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
"--photo_source=remote", "--remote_host=127.0.0.1:{}".format(port))
err = capsys.readouterr().err
assert "Photo received from http://127.0.0.1:{}/capture".format(port) in err
assert "3 hole(s)" in err and camera.calls[-1] == "/capture"
assert_holes_match(outline_rings(svg)[1:])
def test_import_remote_last_photo(tmp_path, camera):
port = camera.port
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
"--photo_source=remote", "--remote_host=127.0.0.1",
"--remote_port={}".format(port), "--remote_endpoint=old")
assert camera.calls[-1] == "/old"
def test_import_remote_errors(tmp_path, camera, capsys):
port = camera.port
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
"--photo_source=remote")
assert "Enter the address" in capsys.readouterr().err
camera.broken(True)
try:
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
"--photo_source=remote", "--remote_host=127.0.0.1:{}".format(port))
finally:
camera.broken(False)
assert "returned an error: 500 Error: Could not access the camera" in \
capsys.readouterr().err
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
"--photo_source=remote", "--remote_host=127.0.0.1:{}".format(free_port()),
"--remote_timeout=3")
err = capsys.readouterr().err
assert "cannot be reached" in err or "did not answer in time" in err
CHECK_SVG = """<svg xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="200mm" height="200mm" viewBox="0 0 200 200">
<sodipodi:namedview id="nv"/>
<g inkscape:groupmode="layer" data-board-photo="outline">
<path data-board-photo="outline-path" fill-rule="evenodd"
d="M 0,0 L 100,0 L 100,100 L 0,100 Z M 60,50 A 10,10 0 1 1 40,50 A 10,10 0 1 1 60,50 Z"/>
</g>
<g id="cuts" inkscape:groupmode="layer" data-board-photo="cuts">
<rect id="good" x="5" y="5" width="20" height="20"/>
<rect id="over_hole" x="45" y="45" width="10" height="10"/>
<rect id="near_edge" x="1" y="60" width="9" height="10"/>
<g transform="translate(100,100)"><circle id="outside" cx="50" cy="50" r="5"/></g>
<circle id="round_good" cx="80" cy="80" r="8"/>
</g>
</svg>"""
# --------------------------------------------------------------------------
# Traductions et coherence des .inx
# --------------------------------------------------------------------------
def test_translations_up_to_date_and_complete():
"""Chaque texte des .inx et des .py a sa traduction dans chaque catalogue."""
import gettext
import i18n
msgids = [msgid for msgid, _refs in i18n.extract()]
for name in ("Board photo: import and calibrate",
"Board photo: print calibration markers"):
assert name in msgids
for language in i18n.LANGUAGES:
entries = i18n.read_po(i18n.po_path(language))
missing = [m for m in msgids if not entries.get(m, ("", False))[0]]
assert not missing, "{}.po incomplet : {}".format(language, missing)
catalog = gettext.translation(i18n.DOMAIN, i18n.LOCALE_DIR, [language])
for msgid in msgids:
assert catalog.gettext(msgid) == entries[msgid][0], \
"{} : .mo a recompiler (python i18n.py)".format(language)
def test_po_roundtrip(tmp_path):
import i18n
messages = [("Simple", ["a"]), ('Quote "x" and \\ back', ["a"]),
("Two\nlines", ["a"]), ("Tab\tend\n", ["a"])]
path = str(tmp_path / "xx.po")
i18n.write_po(path, "fr", messages,
{m: ("<" + m + ">", False) for m, _r in messages})
entries = i18n.read_po(path)
for msgid, _refs in messages:
assert entries[msgid] == ("<" + msgid + ">", False)
def inx_params(name):
"""Valeur par defaut de chaque <param> (premiere option d'un choix sans texte)."""
root = ET.parse(os.path.join(HERE, name + ".inx")).getroot()
params = {}
for elem in root.iter():
if elem.tag.rsplit("}", 1)[-1] != "param":
continue
value = (elem.text or "").strip()
options = [o for o in elem if o.tag.rsplit("}", 1)[-1] == "option"]
if not value and options:
value = options[0].get("value")
params[elem.get("name")] = value
return params
@pytest.mark.parametrize("name", INX_FILES)
def test_inx_matches_arguments(name):
"""Chaque <param> du .inx a son add_argument avec le meme defaut, et inversement."""
with open(os.path.join(HERE, name + ".py"), encoding="utf-8") as handle:
source = handle.read()
arguments = dict(re.findall(r'add_argument\("--(\w+)"(?:, type=[\w.]+)?, '
r'default=("?[^")]*"?)\)', source))
params = inx_params(name)
assert set(params) == set(arguments)
for key, value in params.items():
if key == "tab":
continue
default = arguments[key].strip('"')
if value in ("true", "false"):
assert default == str(value == "true")
elif re.match(r"^-?[\d.]+$", value) and re.match(r"^-?[\d.]+$", default):
assert float(default) == float(value), key
else:
assert default == value, key
def test_work_area_settings_identical():
"""Import et reperes partagent la description de la zone de travail."""
shared = {k: v for k, v in inx_params("board_photo_markers").items()
if k not in ("tab", "mode", "print_x", "print_y")}
imported = inx_params("board_photo_import")
assert {k: imported[k] for k in shared} == shared
@pytest.mark.parametrize("name", INX_FILES)
def test_inx_images_exist(name):
"""Les images de la boite de dialogue sont presentes (chemin relatif au .inx)."""
root = ET.parse(os.path.join(HERE, name + ".inx")).getroot()
for elem in root.iter():
if elem.tag.rsplit("}", 1)[-1] == "image":
assert os.path.isfile(os.path.join(HERE, elem.text.strip())), elem.text
# --------------------------------------------------------------------------
# Export vers LaserGRBL (extension tierce, simulee : selection et coordonnees)
# --------------------------------------------------------------------------
LASER_COLORS = "#000000,#FF0000,#0000ff" # gravure, decoupe int., decoupe ext.
def lasergrbl_export(svg):
"""Elements retenus par « Export to LaserGRBL » v1.21 (tout le document) et
points du G-code de leur trace, en mm depuis le bas gauche de la page."""
import inkex
colors = [inkex.Color(c).to_rgba() for c in LASER_COLORS.split(",")]
to_mm = svg.unit_to_viewport(1, "mm")
vbox = svg.get_viewbox()
exported = {}
for el in svg.descendants():
ident = el.get("id")
if el.TAG == "use":
el = el.unlink()
if el.TAG in ["rect", "circle", "ellipse"]:
el = el.to_path_element()
elif el.TAG != "path":
continue
fill = None if "fill" not in el.style or el.style["fill"] == "none" \
else el.style.get_color("fill")
col = None if "stroke" not in el.style or el.style["stroke"] == "none" \
else el.style.get_color("stroke")
if not any(c in [col, fill] for c in colors):
continue
path = el.path.transform(el.composed_transform()).to_superpath()
exported[ident] = [
(round((pt[1][0] - vbox[0]) * to_mm, 2),
round((vbox[1] + vbox[3] - pt[1][1]) * to_mm, 2))
for sub in path for pt in sub]
return exported
def with_laser_colors(svg, path):
"""Enregistre le document avec les couleurs d'export memorisees (<lasergrbl:info>)."""
path.write_bytes(svg.tostring().replace(
b"</svg>", '<lasergrbl:info xmlns:lasergrbl="https://lasergrbl.com/inkscape" '
'colors="{}"/></svg>'.format(LASER_COLORS).encode()))
return path
def cut_document(tmp_path, photo_file, source):
"""Import, puis deux formes rouges dans « Cuts » (une sur la planche, une hors
planche) ; renvoie le document, avec les couleurs d'export memorisees."""
import inkex
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", source,
"--photo={}".format(photo_file))
scale = svg.unittouu("1mm")
cuts = layers(svg, "cuts")[0]
# Rectangle de 30 x 20 mm, coin bas gauche en (150, 160) mm repere laser.
good = inkex.Rectangle.new(150 * scale, (400 - 180) * scale, 30 * scale, 20 * scale)
good.set("id", "good")
bad = inkex.Rectangle.new(2 * scale, 2 * scale, 10 * scale, 10 * scale)
bad.set("id", "bad")
for shape in (good, bad):
shape.style = inkex.Style({"fill": "none", "stroke": "#ff0000",
"stroke-width": str(0.1 * scale)})
cuts.add(shape)
placed = with_laser_colors(svg, tmp_path / "cuts.svg")
return inkex.load_svg(str(placed)).getroot()
@pytest.mark.parametrize("source", [EMPTY_MM, EMPTY_PX])
def test_lasergrbl_export_origin_and_size(tmp_path, photo_file, source, capsys):
"""Seules les formes de « Cuts » partent a la laser, a la bonne place et taille,
en document mm comme px ; photo et contour ne sont pas exportes."""
pytest.importorskip("inkex")
svg = cut_document(tmp_path, photo_file, source)
assert layers(svg, "outline") and layers(svg, "photo")
exported = lasergrbl_export(svg)
assert set(exported) == {"good", "bad"}
xs, ys = zip(*exported["good"])
assert (min(xs), max(xs), min(ys), max(ys)) == pytest.approx((150, 180, 160, 180),
abs=0.01)
def test_import_warns_when_page_is_not_the_work_area(tmp_path, photo_file, capsys):
run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
"--photo={}".format(photo_file), "--set_page=false")
assert "The page is not the size of the work area" in capsys.readouterr().err
def test_corner_layout():
"""Pieces de 40 mm (reperes de 20) aux angles d'un nid de 400 x 400 mm."""
assert core.corner_layout(400, 400, 20) == pytest.approx((-20, -20, 440, 440))
assert core.corner_layout(400, 300, 17.5) == pytest.approx((-17.5, -17.5, 435, 335))
@pytest.mark.parametrize("name", ["board_photo_import", "board_photo_markers"])
def test_inx_accepts_negative_origin(name):
"""Le dialogue doit accepter un repere origine hors de la zone (X, Y < 0)."""
root = ET.parse(os.path.join(HERE, name + ".inx")).getroot()
for elem in root.iter():
if elem.get("name") in ("origin_x", "origin_y"):
assert float(elem.get("min")) < 0
def test_photo_extent():
"""Reperes dans la zone : la photo couvre la zone seule ; reperes autour :
elle s'agrandit pour les montrer, bornes sur la grille des pixels."""
assert core.photo_extent(400, 400, 30, 30, 340, 340, 20, 4.0) == (0, 0, 400, 400)
x0, y0, x1, y1 = core.photo_extent(400, 400, -21.5, -18, 443, 436, 20, 4.0)
assert (x0, x1) == pytest.approx((-51.5, 451.5))
assert (y0, y1) == pytest.approx((-48, 448))
x0, _y0, _x1, _y1 = core.photo_extent(400, 400, -21.3, -18, 443, 436, 20, 3.0)
assert x0 * 3.0 == pytest.approx(round(x0 * 3.0)) and x0 <= -51.3
def test_rectify_with_offset():
"""Une photo couvrant (-50, -50)-(450, 450) mm place chaque point au bon pixel."""
picture = syn.render_photo()
matrix = core.homography(syn.marker_pixels(), syn.markers())
wide, valid = vision.rectify(picture, matrix, 500, 500, 2.0, offset=(-50, -50))
area, _valid = vision.rectify(picture, matrix, 400, 400, 2.0)
assert wide.size == (1000, 1000)
inner = np.asarray(wide.convert("L"), dtype=float)[100:900, 100:900]
assert np.abs(inner - np.asarray(area.convert("L"), dtype=float)).mean() < 2
def test_import_markers_at_honeycomb_corners(tmp_path, photo_file):
"""Reperes aux angles du nid d'abeille (reglage par defaut) : origine et ecart
deduits, la photo deborde de la page pour les montrer.
Dans la scene synthetique, les pieces (40 mm) touchent les angles du carre
(50, 50)-(350, 350) : c'est le nid d'abeille de 300 x 300 mm vu ici."""
pytest.importorskip("inkex")
svg = run(tmp_path, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
"--photo={}".format(photo_file))
reference = outline_rings(svg)
out = tmp_path / "corners"
out.mkdir()
svg = run(out, "BoardPhotoImport", "board_photo_import", EMPTY_MM,
"--photo={}".format(photo_file), "--work_width=300", "--work_height=300",
"--marker_placement=corners")
image = layers(svg, "photo")[0][0]
box = [float(image.get(k)) for k in ("x", "y", "width", "height")]
assert box == pytest.approx([-50, -50, 400, 400])
assert (svg.get("width"), svg.get("height")) == ("300mm", "300mm")
shifted = outline_rings(svg)
assert len(shifted) == len(reference)
xs = [p[0] for p in shifted[0]]
ref_xs = [p[0] for p in reference[0]]
assert min(xs) == pytest.approx(min(ref_xs) - 50, abs=0.5)
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="210mm" height="297mm" viewBox="0 0 210 297">
<sodipodi:namedview id="namedview1"/>
</svg>

After

Width:  |  Height:  |  Size: 322 B

+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="800" height="600" viewBox="0 0 800 600">
<sodipodi:namedview id="namedview1"/>
<rect id="existing" x="10" y="10" width="96" height="48" fill="#cccccc"/>
</svg>

After

Width:  |  Height:  |  Size: 394 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

+82
View File
@@ -0,0 +1,82 @@
# coding=utf-8
"""
Faux serveur de capture pour les tests (memes routes que le serveur Flask).
python tests/fake_camera.py <photo.jpg> <dossier>
Ecrit son port sur la sortie standard, puis sert :
- /capture et /old : la photo (image/jpeg) ; /capture renvoie une erreur 500
« Error: Could not access the camera » si le fichier <dossier>/broken existe ;
- /text : une reponse texte (comme la route /photo du serveur Flask).
Chaque chemin demande est ajoute a <dossier>/calls.txt.
/cut annonce plus d'octets qu'il n'en envoie puis ferme : transmission
interrompue.
Il tourne dans son propre processus, comme la vraie camera.
"""
import os
import socket
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
def main(photo, folder):
with open(photo, "rb") as handle:
jpeg = handle.read()
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
with open(os.path.join(folder, "calls.txt"), "a") as log:
log.write(self.path + "\n")
broken = os.path.exists(os.path.join(folder, "broken"))
if self.path == "/capture" and broken:
self.reply(500, "text/html", b"Error: Could not access the camera")
elif self.path in ("/capture", "/old"):
self.reply(200, "image/jpeg", jpeg)
elif self.path == "/cut":
self.send_response(200)
self.send_header("Content-Type", "image/jpeg")
self.send_header("Content-Length", str(len(jpeg)))
self.end_headers()
self.wfile.write(jpeg[:1000])
self.close_connection = True
elif self.path == "/text":
self.reply(200, "text/html", b"Photo save")
else:
self.reply(404, "text/html", b"Not found")
def reply(self, code, content_type, body):
self.send_response(code)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
self.wfile.flush()
# Fermeture en douceur. Sur certaines machines Windows (filtre
# reseau, antivirus), fermer la connexion juste apres l'envoi fait
# perdre la fin de la reponse en boucle locale : constate avec curl
# comme avec urllib (environ 1 fois sur 5 sans cette pause, jamais
# avec). On laisse les donnees partir, puis on attend que le client
# ferme a son tour.
try:
time.sleep(0.5)
self.connection.shutdown(socket.SHUT_WR)
self.connection.settimeout(10)
while self.connection.recv(65536):
pass
except OSError:
pass
def log_message(self, *args):
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
print(server.server_address[1], flush=True)
server.serve_forever()
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])
+115
View File
@@ -0,0 +1,115 @@
# coding=utf-8
"""
Photo synthetique d'une planche trouee sur la surface de travail.
Sert aux tests (et au schema) : on connait exactement la position des
reperes, du contour et des trous, puis on simule la prise de vue par une
perspective connue, un leger flou et du bruit. Si la chaine retrouve les
cotes a quelques dixiemes de millimetre, l'echelle est respectee.
"""
import os
import sys
import numpy as np
from PIL import Image, ImageDraw, ImageFilter
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import board_photo_core as core # noqa: E402
WIDTH, HEIGHT = 400.0, 400.0 # zone de travail (mm)
ORIGIN = (30.0, 30.0) # centre du repere origine (repere laser)
SPACING = (340.0, 340.0)
MARKER_SIZE = 20.0
BOARD = [(70.0, 90.0), (330.0, 80.0), (340.0, 300.0), (60.0, 310.0)] # repere SVG
HOLES = [((130.0, 150.0), 6.0), ((230.0, 190.0), 12.5), ((290.0, 260.0), 4.0)]
CAMERA = [(300.0, 150.0), (2150.0, 230.0), (2060.0, 1700.0), (370.0, 1610.0)]
PHOTO_SIZE = (2400, 1800)
def markers():
return core.marker_layout(HEIGHT, ORIGIN[0], ORIGIN[1], SPACING[0], SPACING[1])
def render_scene(res=8.0, bed=70, board=205, printed=False):
"""Vue de dessus parfaite, `res` pixels par mm.
`printed` : reperes imprimes colles sur leur gabarit de pose grave (piece
de papier, traits d'alignement, contour et croix du gabarit autour).
"""
size = (int(WIDTH * res), int(HEIGHT * res))
image = Image.new("L", size, bed)
draw = ImageDraw.Draw(image)
def poly(ring, fill):
draw.polygon([(x * res, y * res) for x, y in ring], fill=fill)
# Nid d'abeille schematise : grille claire sur fond sombre.
for k in range(0, int(WIDTH), 8):
draw.line([(k * res, 0), (k * res, size[1])], fill=bed + 35, width=int(res))
draw.line([(0, k * res), (size[0], k * res)], fill=bed + 35, width=int(res))
def lines(polylines, fill, width_mm):
for line in polylines:
draw.line([(x * res, y * res) for x, y in line], fill=fill,
width=max(1, int(round(width_mm * res))))
for index, center in enumerate(markers()):
if printed:
plate = MARKER_SIZE * 1.8
poly([(center[0] - plate, center[1] - plate), (center[0] + plate, center[1] - plate),
(center[0] + plate, center[1] + plate), (center[0] - plate, center[1] + plate)],
215)
lines(core.guide_lines(center, MARKER_SIZE), 90, 0.3)
poly(core.piece_outline(center, MARKER_SIZE)[:-1], 245)
lines(core.piece_ticks(center, MARKER_SIZE), 20, 0.3)
rings = core.marker_rings(center, MARKER_SIZE, origin=index == core.ORIGIN_MARKER)
poly(rings[0], 25)
for dot in rings[1:]:
poly(dot, 245)
continue
half = MARKER_SIZE * 0.85
poly([(center[0] - half, center[1] - half), (center[0] + half, center[1] - half),
(center[0] + half, center[1] + half), (center[0] - half, center[1] + half)], 235)
rings = core.marker_rings(center, MARKER_SIZE, origin=index == core.ORIGIN_MARKER)
poly(rings[0], 25)
for dot in rings[1:]:
poly(dot, 235)
poly(BOARD, board)
for center, radius in HOLES:
poly(core.circle_ring(center, radius, 180), bed)
return image
def camera_matrix():
"""Homographie mm (repere SVG) -> pixels de la photo simulee."""
corners = [(0.0, 0.0), (WIDTH, 0.0), (WIDTH, HEIGHT), (0.0, HEIGHT)]
return core.homography(corners, CAMERA)
def render_photo(seed=0, rotate=0, res=8.0, printed=False):
"""Photo simulee (PIL RGB) ; `rotate` en quarts de tour (appareil tourne)."""
scene = render_scene(res, printed=printed)
to_scene = np.diag([res, res, 1.0]) @ np.linalg.inv(camera_matrix())
to_scene = to_scene / to_scene[2, 2]
photo = scene.transform(PHOTO_SIZE, Image.PERSPECTIVE, tuple(to_scene.ravel()[:8]),
Image.BICUBIC, fillcolor=40)
photo = photo.filter(ImageFilter.GaussianBlur(1.2))
rng = np.random.default_rng(seed)
noisy = np.asarray(photo, dtype=float) + rng.normal(0, 6, (PHOTO_SIZE[1], PHOTO_SIZE[0]))
photo = Image.fromarray(np.clip(noisy, 0, 255).astype(np.uint8)).convert("RGB")
if rotate:
photo = photo.rotate(90 * rotate, expand=True)
return photo
def marker_pixels(rotate=0):
"""Position exacte des reperes dans la photo (ordre HG, HD, BD, BG du repere SVG)."""
points = core.apply_homography(camera_matrix(), markers())
w, h = PHOTO_SIZE
for _ in range(rotate % 4):
# Rotation de 90 deg dans le sens trigonometrique (PIL, expand=True).
points = np.column_stack([points[:, 1], w - points[:, 0]])
w, h = h, w
return [tuple(p) for p in points]