{"generated":"2026-09-29T07:27:30Z","site":"https://celestiax-plugins.sturzy.ch","repo":"https://github.com/erwansturzenegger/CelestiaX-Plugins","plugins":[{"id":"ai-starless","version":"1.0.0","name":{"fr":"Sans étoiles IA (Dark Star)","en":"AI starless (Dark Star)"},"summary":{"fr":"Suppression des étoiles et masque d'étoiles par le réseau libre Dark Star de Cosmic Clarity (MIT, ONNX) ; calque d'étoiles compatible avec stars_add.","en":"Star removal and star mask with Cosmic Clarity's open Dark Star network (MIT, ONNX); star layer compatible with stars_add."},"category":"ai","tags":["ai","starless","star-mask","stars","onnx"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/ai-starless","min_astrostack":"0.1.0","entry":"celestiax_ai_starless","python_deps":["onnxruntime>=1.17"],"stages":["ai_starless","star_mask"],"frame_ops":[],"ai":true,"models":[{"id":"darkstar-2.1c","name":{"fr":"Dark Star 2.1c (couleur)","en":"Dark Star 2.1c (colour)"},"url":"https://github.com/setiastro/cosmicclarity/releases/download/AppleSilicon/darkstar_v2.1c.onnx","filename":"darkstar_v2.1c.onnx","size_mb":15,"sha256":"d9c3ab0ee808cbbe576aa3ea4c806b1e3117e47d807603bf03c0bb2f849667a6","license":"MIT","notes":{"fr":"Modèle couleur pour les images RGB. Publié par Franklin Marek (Seti Astro) dans les versions GitHub de Cosmic Clarity, dépôt sous licence MIT. Le même fichier est publié pour toutes les plateformes.","en":"Colour model for RGB images. Published by Franklin Marek (Seti Astro) in Cosmic Clarity's GitHub releases, repository under the MIT licence. The same file is published for every platform."}},{"id":"darkstar-2.1","name":{"fr":"Dark Star 2.1 (mono)","en":"Dark Star 2.1 (mono)"},"url":"https://github.com/setiastro/cosmicclarity/releases/download/AppleSilicon/darkstar_v2.1.onnx","filename":"darkstar_v2.1.onnx","size_mb":15,"sha256":"e10a1e4ff2b0a47d35035b947fd0cb392bb047a3356e46b7e1c8807aff664917","license":"MIT","notes":{"fr":"Modèle mono (images de luminance, bandes étroites, ou RGB aux canaux identiques). Même provenance et même licence.","en":"Mono model (luminance, narrowband, or RGB with identical channels). Same origin and licence."}}],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale : ai_starless et star_mask (Dark Star 2.1 / 2.1c).","en":"Initial release: ai_starless and star_mask (Dark Star 2.1 / 2.1c)."}},"download":"https://celestiax-plugins.sturzy.ch/dl/ai-starless-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/ai-starless-1.0.0.zip","size":15503,"sha256":"5fbebf92eafbb17fb153da1301d0ee8b81a1084eedd48991444c9c5b31f56ec9","readme":{"fr":"# Sans étoiles IA — Dark Star\n\nDeux étapes fondées sur le réseau **Dark Star** de [Cosmic Clarity](https://github.com/setiastro/cosmicclarity) (Franklin Marek / Seti Astro), un modèle libre (MIT) de suppression d'étoiles :\n\n| Étape | Rôle |\n|---|---|\n| `ai_starless` | image sans étoiles + calque d'étoiles (pour traiter nébuleuse et étoiles séparément puis les recombiner) |\n| `star_mask` | masque d'étoiles précis (y compris sur fond de nébuleuse), réutilisable par toutes les étapes via `mask:` |\n\n## Quand l'utiliser\n\n- Pour étirer, saturer ou accentuer la nébuleuse sans gonfler les étoiles : `ai_starless`, traitements, puis `stars_add` (plugin *Outils étoiles*) pour remettre les étoiles, exactement (`starless + calque = original`).\n- Pour protéger les étoiles d'un débruitage ou d'une accentuation : `star_mask`, puis `mask: \"file path=star_mask.npy invert=true\"` dans l'étape suivante (ou `apply_mask`, qui reprend le dernier masque calculé).\n- Plus propre que l'étape `starless` classique (détection + remplissage) sur les champs denses et les étoiles posées sur une nébuleuse.\n\n## Ce que fait le modèle\n\nDark Star est un réseau convolutif (dilatations successives) entraîné sur des images étirées : il prend des tuiles RGB de 256×256 px dans [0, 1] et rend la même tuile sans étoiles. Comme Cosmic Clarity, l'étape étire d'abord l'image si elle est linéaire (médiane < 0,125 → MTF non lié, médiane 0,25), traite l'image par tuiles qui se recouvrent (32 px de fondu linéaire, 16 px de contexte ignorés), puis revient à l'échelle d'origine — ici par l'inverse exact de l'étirement. Le modèle **couleur** (2.1c) sert pour les images RGB, le modèle **mono** (2.1) pour la luminance ou les poses en bande étroite (canal répété ×3). Le résultat est limité à l'image d'origine (`starless ≤ image`), de sorte que le calque d'étoiles est positif et que la recombinaison est exacte.\n\n`star_mask` seuille le calque d'étoiles (rampe entre `threshold` et 2 × `threshold` σ), le dilate de `grow` px et adoucit ses bords de `feather` px. S'il suit un `ai_starless`, il réutilise son calque sans relancer le réseau. Le masque est enregistré dans `.work/star_mask.npy`.\n\n## Modèles, provenance et licence\n\n| Modèle | Fichier | Taille | Licence |\n|---|---|---|---|\n| `darkstar-2.1c` (couleur) | [darkstar_v2.1c.onnx](https://github.com/setiastro/cosmicclarity/releases/tag/AppleSilicon) | 15 Mo | MIT |\n| `darkstar-2.1` (mono) | [darkstar_v2.1.onnx](https://github.com/setiastro/cosmicclarity/releases/tag/AppleSilicon) | 15 Mo | MIT |\n\nLes deux fichiers ONNX sont publiés par l'auteur dans les versions GitHub du dépôt Cosmic Clarity (licence **MIT**, © 2024 Franklin Marek) ; le même fichier est proposé pour toutes les plateformes. Téléchargement à la demande, avec vérification SHA-256 :\n\n```\nastrostack plugin models ai-starless --download darkstar-2.1c\nastrostack plugin models ai-starless --download darkstar-2.1\n```\n\n(ou vue Plugins → Sans étoiles IA → Modèles). Sans modèle, l'étape s'arrête avec `ModelMissing`.\n\n**Pourquoi pas StarNet ?** StarNet v1/v2 (N. Mikhailov) est la référence en la matière, mais ses poids ne sont pas publiés sous une licence qui permette de les redistribuer ou de les intégrer librement ; ce plugin ne l'utilise donc pas. Les utilisateurs de StarNet peuvent continuer à l'employer à part (PixInsight, Siril) et charger le résultat comme masque (`mask: \"file path=…\"`).\n\n## Paramètres\n\n### `ai_starless`\n\n| Paramètre | Défaut | Rôle |\n|---|---|---|\n| `model` | `auto` | `auto` (couleur si l'image est RGB), `color` ou `mono` |\n| `keep` | `starless` | image gardée : `starless`, `stars` (calque seul) ou `both` (image inchangée, fichiers enregistrés) |\n| `batch_size` | 4 | tuiles par lot |\n| `device` | `auto` | `auto` (CoreML/GPU puis CPU) ou `cpu` |\n| `mask` | vide | masque optionnel (ne retirer les étoiles que dans une zone) |\n\n### `star_mask`\n\n| Paramètre | Défaut | Rôle |\n|---|---|---|\n| `threshold` | 3 | seuil en σ du calque d'étoiles |\n| `grow` | 1 | dilatation (px) |\n| `feather` | 2 | adoucissement des bords (px) |\n| `invert` | non | 1 hors des étoiles |\n| `show` | non | remplace l'image par le masque (contrôle) |\n| `model`, `device` | | comme `ai_starless`, si le réseau doit être lancé |\n\n## Exemple\n\n```yaml\npipeline:\n  - stack: {}\n  - crop: {}\n  - background: {}\n  - stretch: {method: auto}\n  - ai_starless: {keep: starless}\n  - saturation: {amount: 1.4}\n  - stars_add: {mode: screen, amount: 0.9}   # plugin stars-tools\n  - star_mask: {grow: 2}\n  - sharpen: {amount: 0.5, mask: \"file path=star_mask.npy invert=true\"}\n  - export: {}\n```\n\n## Contrôle\n\n`ai_starless` écrit `.work/ai_starless_diff.npy` (le calque d'étoiles retiré), `stars_layer.npy` et `starless.npy` ; `star_mask` écrit `star_mask.npy` et `ai_star_mask_diff.npy`. Un morceau de nébuleuse visible dans le calque d'étoiles signale une zone où le réseau s'est trompé.\n\n## Temps de calcul (Mac M4 Max)\n\n| Cas | CoreML | CPU |\n|---|---|---|\n| 640×480 | 0,6 s | 15 s |\n| 1400×1050 (aperçu réduit) | 1,5 s | ≈ 70 s (extrapolé) |\n\nLes deux étapes sont rejouées dans l'aperçu en direct (le modèle est gardé en mémoire entre deux aperçus). Sans CoreML ni GPU, désactivez-les le temps de régler les autres étapes.\n\n## Limites\n\n- De faibles anneaux résiduels peuvent subsister autour des étoiles très brillantes ou saturées (visibles après un étirement fort) ; `stars_add` avec `amount` < 1 les masque en général.\n- Les petites structures compactes (nébuleuses planétaires, noyaux de galaxies, amas globulaires) peuvent être prises pour des étoiles.\n- Réseau entraîné sur des images étirées : sur une image linéaire très sombre, le résultat dépend de l'étirement interne.\n- Calcul en précision réduite sur CoreML ; `device: cpu` pour un résultat reproductible au bit près.\n","en":"# AI starless — Dark Star\n\nTwo steps built on the **Dark Star** network from [Cosmic Clarity](https://github.com/setiastro/cosmicclarity) (Franklin Marek / Seti Astro), an open (MIT) star-removal model:\n\n| Step | Purpose |\n|---|---|\n| `ai_starless` | starless image + star layer (process nebula and stars separately, then recombine) |\n| `star_mask` | accurate star mask (including over nebulosity), reusable by every step through `mask:` |\n\n## When to use it\n\n- To stretch, saturate or sharpen the nebula without bloating stars: `ai_starless`, processing, then `stars_add` (*Star tools* plugin) to put the stars back, exactly (`starless + layer = original`).\n- To protect stars from denoising or sharpening: `star_mask`, then `mask: \"file path=star_mask.npy invert=true\"` in the next step (or `apply_mask`, which reuses the last computed mask).\n- Cleaner than the classic `starless` step (detection + inpainting) on dense fields and stars sitting on nebulosity.\n\n## What the model does\n\nDark Star is a convolutional network (successive dilations) trained on stretched images: it takes 256×256 RGB tiles in [0, 1] and returns the same tile without stars. Like Cosmic Clarity, the step first stretches the image if it is linear (median < 0.125 → unlinked MTF, median 0.25), processes overlapping tiles (32 px linear blending, 16 px of ignored context), then returns to the original scale — here with the exact inverse of the stretch. The **colour** model (2.1c) is used for RGB images, the **mono** model (2.1) for luminance or narrowband frames (channel repeated ×3). The result is capped to the original image (`starless ≤ image`), so the star layer is positive and recombination is exact.\n\n`star_mask` thresholds the star layer (ramp between `threshold` and 2 × `threshold` σ), dilates it by `grow` px and feathers its edges by `feather` px. After an `ai_starless`, it reuses its layer without running the network again. The mask is saved to `.work/star_mask.npy`.\n\n## Models, origin and licence\n\n| Model | File | Size | Licence |\n|---|---|---|---|\n| `darkstar-2.1c` (colour) | [darkstar_v2.1c.onnx](https://github.com/setiastro/cosmicclarity/releases/tag/AppleSilicon) | 15 MB | MIT |\n| `darkstar-2.1` (mono) | [darkstar_v2.1.onnx](https://github.com/setiastro/cosmicclarity/releases/tag/AppleSilicon) | 15 MB | MIT |\n\nBoth ONNX files are published by the author in the GitHub releases of the Cosmic Clarity repository (**MIT** licence, © 2024 Franklin Marek); the same file is offered for every platform. Downloaded on demand, with SHA-256 check:\n\n```\nastrostack plugin models ai-starless --download darkstar-2.1c\nastrostack plugin models ai-starless --download darkstar-2.1\n```\n\n(or Plugins view → AI starless → Models). Without a model, the step stops with `ModelMissing`.\n\n**Why not StarNet?** StarNet v1/v2 (N. Mikhailov) is the reference tool, but its weights are not released under a licence that allows free redistribution or integration, so this plugin does not use it. StarNet users can keep running it separately (PixInsight, Siril) and load the result as a mask (`mask: \"file path=…\"`).\n\n## Parameters\n\n### `ai_starless`\n\n| Parameter | Default | Purpose |\n|---|---|---|\n| `model` | `auto` | `auto` (colour if the image is RGB), `color` or `mono` |\n| `keep` | `starless` | image kept: `starless`, `stars` (layer only) or `both` (image unchanged, files saved) |\n| `batch_size` | 4 | tiles per batch |\n| `device` | `auto` | `auto` (CoreML/GPU then CPU) or `cpu` |\n| `mask` | empty | optional mask (remove stars in one area only) |\n\n### `star_mask`\n\n| Parameter | Default | Purpose |\n|---|---|---|\n| `threshold` | 3 | threshold in σ of the star layer |\n| `grow` | 1 | dilation (px) |\n| `feather` | 2 | edge feathering (px) |\n| `invert` | no | 1 outside stars |\n| `show` | no | replaces the image by the mask (check) |\n| `model`, `device` | | as in `ai_starless`, if the network has to run |\n\n## Example\n\n```yaml\npipeline:\n  - stack: {}\n  - crop: {}\n  - background: {}\n  - stretch: {method: auto}\n  - ai_starless: {keep: starless}\n  - saturation: {amount: 1.4}\n  - stars_add: {mode: screen, amount: 0.9}   # stars-tools plugin\n  - star_mask: {grow: 2}\n  - sharpen: {amount: 0.5, mask: \"file path=star_mask.npy invert=true\"}\n  - export: {}\n```\n\n## Checking the result\n\n`ai_starless` writes `.work/ai_starless_diff.npy` (the removed star layer), `stars_layer.npy` and `starless.npy`; `star_mask` writes `star_mask.npy` and `ai_star_mask_diff.npy`. A piece of nebula visible in the star layer marks an area where the network got it wrong.\n\n## Processing time (Mac M4 Max)\n\n| Case | CoreML | CPU |\n|---|---|---|\n| 640×480 | 0.6 s | 15 s |\n| 1400×1050 (reduced preview) | 1.5 s | ≈ 70 s (extrapolated) |\n\nBoth steps are replayed in the live preview (the model stays in memory between previews). Without CoreML or a GPU, disable them while tuning the other steps.\n\n## Limitations\n\n- Faint residual rings may remain around very bright or saturated stars (visible after a strong stretch); `stars_add` with `amount` < 1 usually hides them.\n- Small compact structures (planetary nebulae, galaxy cores, globular clusters) may be taken for stars.\n- Network trained on stretched images: on a very dark linear image, the result depends on the internal stretch.\n- Reduced-precision computation on CoreML; `device: cpu` for bit-exact reproducibility.\n"}},{"id":"analysis","version":"1.0.0","name":{"fr":"Analyses de l'image","en":"Image analysis"},"summary":{"fr":"Carte de qualité PSF (FWHM, excentricité, tilt, coma), SNR par zone et magnitude limite, détection de transitoires par différence.","en":"PSF quality map (FWHM, eccentricity, tilt, coma), per-zone SNR and limiting magnitude, transient detection by image differencing."},"category":"analysis","tags":["psf","fwhm","snr","limiting-magnitude","transients"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/analysis","min_astrostack":"0.1.0","entry":"celestiax_analysis","python_deps":[],"stages":["psf_map","snr_analysis","transients"],"frame_ops":[],"ai":false,"models":[],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale (extraite du cœur d'astrostack)","en":"Initial release (extracted from the astrostack core)"}},"download":"https://celestiax-plugins.sturzy.ch/dl/analysis-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/analysis-1.0.0.zip","size":24677,"sha256":"3d5b15bd5ee95f7ed7dbd502e7c8ce874c386fbdfe7c49bd7eec1df7d8576d71","readme":{"fr":"# Analyses de l'image\n\nTrois diagnostics chiffrés de l'image empilée (ou d'une pose brute) : carte de qualité PSF avec détection du tilt et de la courbure de champ, SNR par zone et magnitude limite, détection de transitoires par différence avec un stack de référence.\n\n## Fonction\n\nLe plugin fournit trois étapes globales d'analyse. Elles ne modifient pas l'image : elles écrivent des rapports (PNG + JSON) et un résumé dans l'état du projet, repris par l'étape `report` et par l'interface.\n\nToutes trois travaillent sur la **luminance** (moyenne des canaux ; une pose CFA est réduite en super-pixels 2 × 2, les coordonnées étant ensuite remises à l'échelle de la pose). Sur l'image empilée, elles utilisent de préférence la **version linéaire** conservée par le cœur, même si elles sont placées après `stretch`.\n\n### `psf_map` — carte de qualité PSF\n\n1. Détection des étoiles (SEP, seuil `threshold` σ) et mesure de chacune : FWHM (à partir des demi-axes a et b de l'ellipse), excentricité 1 − b/a, orientation. Les objets trop petits (FWHM < 1,2 px, pixels chauds) et aberrants (FWHM > médiane + 8 MAD) sont écartés.\n2. Agrégation sur une grille `grid` × `grid` : FWHM médiane, excentricité médiane et **élongation moyenne orientée** (moyenne vectorielle des orientations, qui ne s'annule pas si toutes les étoiles d'une zone sont étirées dans la même direction). Une zone avec moins de `min_stars` étoiles est laissée vide.\n3. Découpage en 9 zones (coins, bords, centre) et **diagnostic** :\n   - **tilt** suspecté si l'écart de FWHM entre les quatre coins dépasse `tilt_threshold` (le coin le plus flou est désigné) ;\n   - **courbure de champ / backfocus** si les coins sont uniformément plus flous que le centre (rapport > 1 + `tilt_threshold`) sans tilt ;\n   - asymétries gauche/droite et haut/bas ;\n   - étoiles allongées dans les coins (coma ou astigmatisme hors axe) si l'excentricité des coins dépasse nettement celle du centre.\n4. Image de synthèse : carte de FWHM colorée, carte d'excentricité avec traits d'élongation, et **inspecteur d'aberrations** (vignettes agrandies des 9 zones, de `tile` px de côté).\n\n### `snr_analysis` — SNR, magnitude limite, gain d'empilement\n\n1. **SNR par zone** sur une grille `grid` × `grid` : fond estimé par SEP, étoiles masquées (segmentation à 3 σ, dilatée) ; signal = médiane locale − fond global (moyenne sigma-clippée), bruit = MAD des pixels de fond hors étoiles.\n2. **Magnitude limite** à SNR = 5 : photométrie d'ouverture (rayon 1,5 × FWHM) des étoiles non saturées, ajustement linéaire de log(SNR) en fonction de la magnitude, extrapolé à SNR = 5. Si l'étape `spcc` (plugin « astrometry ») a fourni un **point zéro**, la magnitude est calibrée ; sinon elle est **relative** (0 = étoile la plus brillante du champ).\n3. **Gain de SNR de l'empilement** : à partir des poids et du bruit de chaque pose (étape `quality`), nombre d'images équivalentes (Σw)²/Σw², gain théorique √N_eq, courbe de gain théorique en fonction du nombre d'images, et contribution de chaque pose (la « moins utile » est signalée).\n4. Option `curve` : **mesure réelle** du gain en empilant progressivement une zone centrale (`box` px) des `curve_frames` meilleures poses alignées, le bruit étant estimé par différences entre pixels voisins (insensible aux gradients).\n\n### `transients` — transitoires par différence d'images\n\n1. Chargement d'un **stack de référence** du même champ (FITS, TIFF, PNG… ou `.npy`), passage en luminance.\n2. **Alignement** de la référence sur l'image courante (astroalign, transformation affine, interpolation cubique) si `align` est actif.\n3. **Différence** : soustraction des fonds (SEP), égalisation des PSF (l'image la plus nette est floutée pour atteindre la FWHM de l'autre), mise à l'échelle photométrique (rapport médian des flux d'étoiles communes), puis courant − échelle × référence.\n4. **Détection** des sources positives (apparues ou plus brillantes) et négatives (disparues ou plus faibles) au-dessus de `sigma` σ, bords exclus. Les résidus d'étoiles dont la variation reste sous `star_tolerance` × leur flux sont ignorés. Chaque détection est classée « nouvelle source », « source disparue » ou « variable » (si une étoile de la référence est à moins de 2 FWHM), et reçoit ses coordonnées RA/Dec si un WCS est disponible.\n\n## Utilité / quand l'utiliser\n\n- **`psf_map`** : réglage du train optique (tilt de la caméra, backfocus d'un correcteur ou réducteur sur lunette), contrôle de la collimation, vérification d'un télescope intelligent (Vespera, Seestar) après transport. Avec `frame: 0`, on analyse une **pose brute** : c'est la meilleure manière de juger l'optique, sans le lissage de l'alignement et de l'empilement. Sur l'empilement, la carte montre aussi les effets du suivi et de la rotation de champ alt-az.\n- **`snr_analysis`** : comparer des nuits, des sites (ciel pollué ou non), des filtres (dual-band vs. sans filtre sur capteur couleur) ou des réglages ; savoir combien de poses supplémentaires valent la peine (la courbe de gain s'aplatit quand les poses ajoutées sont de mauvaise qualité) ; repérer une pose qui n'apporte presque rien.\n- **`transients`** : rechercher une supernova dans une galaxie, suivre une étoile variable ou une nova, repérer un astéroïde (qui apparaît comme une paire de sources + et −) en comparant avec un stack d'une autre nuit.\n\nÀ ne **pas** utiliser :\n\n- sur la Lune, les planètes ou le Soleil (pas d'étoiles ponctuelles : PSF et magnitude limite n'ont pas de sens) ;\n- `psf_map` sur un champ très pauvre en étoiles (moins d'une dizaine) : la carte est vide ou peu fiable ;\n- `transients` avec une référence prise avec un instrument très différent (échantillonnage, filtre) : la différence laisse beaucoup de résidus ; une référence traitée de façon non linéaire (étirée) donne aussi de faux transitoires.\n\n## Installation\n\n```bash\nastrostack plugin install analysis\n```\n\nOu depuis l'application : vue **Plugins**, fiche « Analyses de l'image », bouton **Installer**.\n\nAucune dépendance Python supplémentaire : le plugin utilise NumPy, SciPy, Astropy, OpenCV, SEP et astroalign, déjà requis par le cœur astrostack.\n\n## Paramètres\n\n### `psf_map`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `grid` | entier (2 à 20) | `5` | Nombre de zones par côté de la carte. |\n| `frame` | entier (facultatif) | aucun | Analyser une pose brute calibrée (index) au lieu de l'image empilée. |\n| `threshold` | réel (2 à 50) | `5.0` | Seuil de détection des étoiles (σ). |\n| `min_stars` | entier (1 à 50) | `3` | Nombre minimum d'étoiles par zone. |\n| `tile` | entier (16 à 512) | `64` | Taille des vignettes de l'inspecteur d'aberrations (px). |\n| `tilt_threshold` | réel (0,02 à 1) | `0.15` | Écart relatif de FWHM signalé comme tilt ou courbure (0,15 = 15 %). |\n\n### `snr_analysis`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `grid` | entier (2 à 32) | `8` | Nombre de zones par côté pour la carte de SNR. |\n| `frame` | entier (facultatif) | aucun | Analyser une pose brute calibrée (index) au lieu de l'image empilée. |\n| `curve` | booléen | `false` | Mesure réelle du gain de SNR par empilement progressif (coûteux : relit les poses). |\n| `curve_frames` | entier (2 à 200) | `16` | Nombre maximal d'images pour la courbe mesurée. |\n| `box` | entier (64 à 2048) | `384` | Taille de la zone centrale utilisée pour la courbe mesurée (px). |\n\n### `transients`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `reference` | texte (chemin) | `\"\"` (obligatoire) | Stack de référence du même champ (FITS/TIFF/PNG/npy, linéaire de préférence). |\n| `sigma` | réel (2 à 30) | `5.0` | Seuil de détection dans l'image de différence (σ). |\n| `minarea` | entier (1 à 100) | `5` | Surface minimale d'une détection (px). |\n| `align` | booléen | `true` | Aligner la référence (astroalign) ; désactiver si elle est déjà recalée au pixel près. |\n| `star_tolerance` | réel (0 à 2) | `0.3` | Résidu d'étoile ignoré s'il reste sous cette fraction de son flux. |\n| `max_results` | entier (1 à 10000) | `200` | Nombre maximal de transitoires listés. |\n\nAucune de ces étapes n'a de paramètre `mask` : ce sont des analyses, elles ne modifient pas l'image.\n\n## Exemples YAML\n\nPlacement conseillé : **après `crop`** (les bords peu couverts faussent les mesures), et pour `snr_analysis` après `spcc` si l'on veut une magnitude limite calibrée. Elles peuvent aussi être placées en fin de chaîne (avant `report`) : elles relisent la version linéaire.\n\nDiagnostic complet d'une séance :\n\n```yaml\npipeline:\n  - stack: {method: sigma_clip}\n  - crop: {min_coverage: 0.9}\n  - platesolve: {}               # plugin « astrometry », pour spcc\n  - spcc: {reference: G2V}       # point zéro pour la magnitude limite\n  - psf_map: {grid: 6}\n  - snr_analysis: {curve: true, curve_frames: 30}\n  - stretch: {method: auto}\n  - export: {formats: [fits, png]}\n  - report: {}                   # reprend les cartes et les chiffres\n```\n\nContrôle du tilt ou du backfocus sur une pose brute (Vespera, lunette + correcteur) :\n\n```yaml\npipeline:\n  - masters: {}\n  - psf_map: {frame: 0, grid: 7, tilt_threshold: 0.1}\n```\n\nRecherche de supernova par rapport à un stack d'une nuit précédente :\n\n```yaml\npipeline:\n  - stack: {}\n  - crop: {}\n  - platesolve: {}               # facultatif : ajoute RA/Dec aux détections\n  - transients:\n      reference: ~/Astro/M101/2026-04-12/out/M101_linear.fits\n      sigma: 6\n      max_results: 50\n```\n\n## Sorties\n\nFichiers écrits dans le dossier de sortie (`output.dir`), `<nom>` étant le nom du projet (ou du groupe) :\n\n| Étape | Fichiers | Clé de `ctx.state` |\n|---|---|---|\n| `psf_map` | `<nom>_psf_map.png` (cartes + inspecteur), `<nom>_psf_map.json` (grilles FWHM/excentricité/élongation/angle/nombre d'étoiles, 9 zones, diagnostic) | `psf_map` : `json`, `png`, `n_stars`, `fwhm_median`, `center_fwhm`, `corner_fwhm`, `tilt`, `curvature`, `messages` |\n| `snr_analysis` | `<nom>_snr_map.png` (carte de SNR superposée à l'image), `<nom>_snr.json` (grilles signal/bruit/SNR, magnitude limite, étoiles mesurées, poids, gains théorique et mesuré, contribution de chaque pose) | `snr` : `median_snr`, `limiting_mag`, `mag_system`, `n_equivalent`, `snr_gain`, `json`, `png` |\n| `transients` | `<nom>_transients.png` (détections cerclées et numérotées : vert = apparue, rouge = disparue), `<nom>_transients.json` (liste : x, y, RA/Dec, signe, flux, SNR, type) | `transients` : `n`, `json`, `png` |\n\nLes trois étapes sont exclues de l'aperçu interactif de l'Atelier (`preview = False`) et ne créent pas de checkpoint (l'image n'est pas modifiée). Un résumé est affiché dans le journal.\n\n## Limites\n\n- **FWHM en pixels**, mesurée par les moments de SEP : c'est une estimation robuste pour comparer des zones, pas une photométrie PSF ajustée. Sur l'empilement, l'alignement (interpolation, rotation de champ) élargit légèrement les étoiles ; utiliser `frame:` pour juger l'optique.\n- Le diagnostic tilt/courbure repose sur des seuils simples ; un champ avec une nébuleuse dense ou très peu d'étoiles dans un coin peut produire une fausse alerte.\n- **Magnitude limite** : sans point zéro `spcc`, elle est relative à l'étoile la plus brillante et ne se compare pas d'un champ à l'autre ; avec `spcc`, la précision dépend de celle du point zéro (bande Gaia, filtres et courbe de réponse du capteur non modélisés) ; c'est une estimation par extrapolation, pas une mesure de complétude.\n- Le gain de SNR théorique suppose des bruits indépendants ; la courbe mesurée (`curve`) ne porte que sur la zone centrale et relit les poses (temps proportionnel à `curve_frames`) ; elle nécessite `register`.\n- **`transients`** : le résultat dépend de la qualité de la référence (même champ, même filtre, même échantillonnage si possible, image linéaire). Les étoiles saturées, les zones à fort gradient et les poses de seeing très différent laissent des résidus. Pas de correction de distorsion : alignement affine uniquement. Les coordonnées RA/Dec nécessitent un WCS (`platesolve`).\n\n## Licences\n\n- Plugin : licence MIT, © Erwan Sturzenegger.\n- Dépendances (fournies par le cœur astrostack) : NumPy (BSD-3-Clause), SciPy (BSD-3-Clause), Astropy (BSD-3-Clause), OpenCV (`opencv-python-headless`, Apache 2.0), SEP (LGPL-3.0, avec des parties sous licences BSD et MIT), astroalign (MIT).\n","en":"# Image analysis\n\nThree quantitative diagnostics of the stacked image (or of a raw frame): PSF quality map with tilt and field-curvature detection, per-zone SNR and limiting magnitude, and transient detection by differencing against a reference stack.\n\n## What it does\n\nThe plugin provides three global analysis stages. They do not modify the image: they write reports (PNG + JSON) and a summary in the project state, which the `report` stage and the interface pick up.\n\nAll three work on the **luminance** (mean of the channels; a CFA frame is reduced to 2 × 2 superpixels, coordinates being scaled back to the frame afterwards). On the stacked image they preferably use the **linear version** kept by the core, even when placed after `stretch`.\n\n### `psf_map` — PSF quality map\n\n1. Star detection (SEP, `threshold` σ) and measurement of each star: FWHM (from the a and b semi-axes of the ellipse), eccentricity 1 − b/a, orientation. Objects that are too small (FWHM < 1.2 px, hot pixels) or outliers (FWHM > median + 8 MAD) are discarded.\n2. Aggregation on a `grid` × `grid` grid: median FWHM, median eccentricity and **mean oriented elongation** (vector mean of the orientations, which does not cancel out when all the stars in a zone are stretched in the same direction). A zone with fewer than `min_stars` stars is left empty.\n3. Split into 9 zones (corners, edges, centre) and **diagnosis**:\n   - **tilt** suspected if the FWHM spread between the four corners exceeds `tilt_threshold` (the blurriest corner is named);\n   - **field curvature / backfocus** if the corners are uniformly blurrier than the centre (ratio > 1 + `tilt_threshold`) without tilt;\n   - left/right and top/bottom asymmetries;\n   - elongated stars in the corners (coma or off-axis astigmatism) if corner eccentricity clearly exceeds that of the centre.\n4. Summary image: colour FWHM map, eccentricity map with elongation strokes, and an **aberration inspector** (enlarged crops of the 9 zones, `tile` px wide).\n\n### `snr_analysis` — SNR, limiting magnitude, stacking gain\n\n1. **Per-zone SNR** on a `grid` × `grid` grid: background estimated by SEP, stars masked (3 σ segmentation, dilated); signal = local median − global background (sigma-clipped mean), noise = MAD of the background pixels outside stars.\n2. **Limiting magnitude** at SNR = 5: aperture photometry (radius 1.5 × FWHM) of unsaturated stars, linear fit of log(SNR) versus magnitude, extrapolated to SNR = 5. If the `spcc` stage (plugin \"astrometry\") has provided a **zero point**, the magnitude is calibrated; otherwise it is **relative** (0 = brightest star in the field).\n3. **Stacking SNR gain**: from the weight and noise of each frame (`quality` stage), equivalent number of frames (Σw)²/Σw², theoretical gain √N_eq, theoretical gain curve versus number of frames, and contribution of each frame (the \"least useful\" one is reported).\n4. `curve` option: **actual measurement** of the gain by progressively stacking a central area (`box` px) of the `curve_frames` best aligned frames, the noise being estimated from differences between neighbouring pixels (insensitive to gradients).\n\n### `transients` — transients by image differencing\n\n1. Loads a **reference stack** of the same field (FITS, TIFF, PNG… or `.npy`) and converts it to luminance.\n2. **Aligns** the reference on the current image (astroalign, affine transform, cubic interpolation) if `align` is enabled.\n3. **Difference**: background subtraction (SEP), PSF matching (the sharper image is blurred to the FWHM of the other), photometric scaling (median flux ratio of common stars), then current − scale × reference.\n4. **Detection** of positive sources (appeared or brighter) and negative ones (disappeared or fainter) above `sigma` σ, edges excluded. Star residuals whose variation stays below `star_tolerance` × their flux are ignored. Each detection is labelled \"new source\", \"vanished source\" or \"variable\" (if a reference star lies within 2 FWHM), and gets RA/Dec coordinates when a WCS is available.\n\n## When to use it\n\n- **`psf_map`**: tuning the optical train (camera tilt, backfocus of a flattener or reducer on a refractor), checking collimation, checking a smart telescope (Vespera, Seestar) after transport. With `frame: 0`, a **raw frame** is analysed: this is the best way to judge the optics, without the smoothing introduced by registration and stacking. On the stack, the map also shows the effects of tracking and alt-az field rotation.\n- **`snr_analysis`**: comparing nights, sites (light-polluted or not), filters (dual-band vs. no filter on a colour sensor) or settings; knowing how many more frames are worth taking (the gain curve flattens when the added frames are of poor quality); spotting a frame that brings almost nothing.\n- **`transients`**: looking for a supernova in a galaxy, following a variable star or a nova, spotting an asteroid (which shows up as a + / − source pair) by comparing with a stack from another night.\n\nDo **not** use it:\n\n- on the Moon, planets or the Sun (no point-like stars: PSF and limiting magnitude are meaningless);\n- `psf_map` on a field with very few stars (fewer than about ten): the map is empty or unreliable;\n- `transients` with a reference taken with a very different instrument (sampling, filter): the difference leaves many residuals; a non-linearly processed (stretched) reference also produces false transients.\n\n## Installation\n\n```bash\nastrostack plugin install analysis\n```\n\nOr from the application: **Plugins** view, \"Image analysis\" page, **Install** button.\n\nNo additional Python dependency: the plugin uses NumPy, SciPy, Astropy, OpenCV, SEP and astroalign, already required by the astrostack core.\n\n## Parameters\n\n### `psf_map`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `grid` | integer (2 to 20) | `5` | Number of zones per side of the map. |\n| `frame` | integer (optional) | none | Analyse a calibrated raw frame (index) instead of the stacked image. |\n| `threshold` | float (2 to 50) | `5.0` | Star detection threshold (σ). |\n| `min_stars` | integer (1 to 50) | `3` | Minimum number of stars per zone. |\n| `tile` | integer (16 to 512) | `64` | Size of the aberration-inspector crops (px). |\n| `tilt_threshold` | float (0.02 to 1) | `0.15` | Relative FWHM difference reported as tilt or curvature (0.15 = 15 %). |\n\n### `snr_analysis`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `grid` | integer (2 to 32) | `8` | Number of zones per side for the SNR map. |\n| `frame` | integer (optional) | none | Analyse a calibrated raw frame (index) instead of the stacked image. |\n| `curve` | boolean | `false` | Actual measurement of the SNR gain by progressive stacking (costly: re-reads the frames). |\n| `curve_frames` | integer (2 to 200) | `16` | Maximum number of frames for the measured curve. |\n| `box` | integer (64 to 2048) | `384` | Size of the central area used for the measured curve (px). |\n\n### `transients`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `reference` | text (path) | `\"\"` (required) | Reference stack of the same field (FITS/TIFF/PNG/npy, preferably linear). |\n| `sigma` | float (2 to 30) | `5.0` | Detection threshold in the difference image (σ). |\n| `minarea` | integer (1 to 100) | `5` | Minimum area of a detection (px). |\n| `align` | boolean | `true` | Align the reference (astroalign); disable if it is already registered to the pixel. |\n| `star_tolerance` | float (0 to 2) | `0.3` | A star residual is ignored if it stays below this fraction of its flux. |\n| `max_results` | integer (1 to 10000) | `200` | Maximum number of transients listed. |\n\nNone of these stages has a `mask` parameter: they are analyses and do not modify the image.\n\n## YAML examples\n\nRecommended position: **after `crop`** (poorly covered edges skew the measurements), and for `snr_analysis` after `spcc` if you want a calibrated limiting magnitude. They can also be placed at the end of the chain (before `report`): they re-read the linear version.\n\nFull diagnosis of a session:\n\n```yaml\npipeline:\n  - stack: {method: sigma_clip}\n  - crop: {min_coverage: 0.9}\n  - platesolve: {}               # plugin \"astrometry\", for spcc\n  - spcc: {reference: G2V}       # zero point for the limiting magnitude\n  - psf_map: {grid: 6}\n  - snr_analysis: {curve: true, curve_frames: 30}\n  - stretch: {method: auto}\n  - export: {formats: [fits, png]}\n  - report: {}                   # includes the maps and figures\n```\n\nChecking tilt or backfocus on a raw frame (Vespera, refractor + flattener):\n\n```yaml\npipeline:\n  - masters: {}\n  - psf_map: {frame: 0, grid: 7, tilt_threshold: 0.1}\n```\n\nSupernova search against a stack from a previous night:\n\n```yaml\npipeline:\n  - stack: {}\n  - crop: {}\n  - platesolve: {}               # optional: adds RA/Dec to detections\n  - transients:\n      reference: ~/Astro/M101/2026-04-12/out/M101_linear.fits\n      sigma: 6\n      max_results: 50\n```\n\n## Outputs\n\nFiles written to the output folder (`output.dir`), `<name>` being the project (or group) name:\n\n| Stage | Files | `ctx.state` key |\n|---|---|---|\n| `psf_map` | `<name>_psf_map.png` (maps + inspector), `<name>_psf_map.json` (FWHM/eccentricity/elongation/angle/star-count grids, 9 zones, diagnosis) | `psf_map`: `json`, `png`, `n_stars`, `fwhm_median`, `center_fwhm`, `corner_fwhm`, `tilt`, `curvature`, `messages` |\n| `snr_analysis` | `<name>_snr_map.png` (SNR map overlaid on the image), `<name>_snr.json` (signal/noise/SNR grids, limiting magnitude, measured stars, weights, theoretical and measured gains, contribution of each frame) | `snr`: `median_snr`, `limiting_mag`, `mag_system`, `n_equivalent`, `snr_gain`, `json`, `png` |\n| `transients` | `<name>_transients.png` (circled, numbered detections: green = appeared, red = vanished), `<name>_transients.json` (list: x, y, RA/Dec, sign, flux, SNR, type) | `transients`: `n`, `json`, `png` |\n\nThe three stages are excluded from the Workshop's interactive preview (`preview = False`) and create no checkpoint (the image is not modified). A summary is printed in the log. Messages and labels written by the stages are in French.\n\n## Limitations\n\n- **FWHM in pixels**, measured from SEP moments: a robust estimate for comparing zones, not fitted PSF photometry. On the stack, registration (interpolation, field rotation) slightly broadens the stars; use `frame:` to judge the optics.\n- The tilt/curvature diagnosis relies on simple thresholds; a field with a dense nebula or very few stars in one corner can trigger a false alarm.\n- **Limiting magnitude**: without an `spcc` zero point it is relative to the brightest star and cannot be compared across fields; with `spcc`, its accuracy depends on that of the zero point (Gaia band, filters and sensor response curve are not modelled); it is an extrapolated estimate, not a completeness measurement.\n- The theoretical SNR gain assumes independent noise; the measured curve (`curve`) only covers the central area and re-reads the frames (time proportional to `curve_frames`); it requires `register`.\n- **`transients`**: the result depends on the quality of the reference (same field, same filter, ideally the same sampling, linear image). Saturated stars, strong-gradient areas and frames with very different seeing leave residuals. No distortion correction: affine alignment only. RA/Dec coordinates require a WCS (`platesolve`).\n\n## Licences\n\n- Plugin: MIT licence, © Erwan Sturzenegger.\n- Dependencies (provided by the astrostack core): NumPy (BSD-3-Clause), SciPy (BSD-3-Clause), Astropy (BSD-3-Clause), OpenCV (`opencv-python-headless`, Apache 2.0), SEP (LGPL-3.0, with parts under BSD and MIT licences), astroalign (MIT).\n"}},{"id":"astrometry","version":"1.0.0","name":{"fr":"Astrométrie & catalogues","en":"Astrometry & catalogues"},"summary":{"fr":"Plate solving (astrometry.net local ou ASTAP), annotation NGC/IC/Messier, calibration photométrique SPCC sur Gaia DR3, astéroïdes attendus (MPC/SkyBoT).","en":"Plate solving (local astrometry.net or ASTAP), NGC/IC/Messier annotation, SPCC photometric colour calibration against Gaia DR3, expected asteroids (MPC/SkyBoT)."},"category":"astrometry","tags":["wcs","plate-solving","gaia","annotation","spcc","asteroids"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/astrometry","min_astrostack":"0.1.0","entry":"celestiax_astrometry","python_deps":["astroquery>=0.4","astrometry>=4.1"],"stages":["platesolve","annotate","spcc","asteroids"],"frame_ops":[],"ai":false,"models":[],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale (extraite du cœur d'astrostack)","en":"Initial release (extracted from the astrostack core)"}},"download":"https://celestiax-plugins.sturzy.ch/dl/astrometry-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/astrometry-1.0.0.zip","size":56271,"sha256":"d27881e78f334e1d80e657b2ed13c446a372dce5c1d5144430c1fe75589a636e","readme":{"fr":"# Astrométrie & catalogues\n\nPlate solving local (astrometry.net ou ASTAP), annotation NGC/IC/Messier avec grille RA/Dec, calibration photométrique des couleurs (SPCC) sur les étoiles Gaia DR3 et recherche des astéroïdes attendus dans le champ (MPC / SkyBoT).\n\n## Fonction\n\nLe plugin fournit quatre étapes globales. `platesolve` calcule la solution astrométrique (WCS) de l'image ; les trois autres s'en servent.\n\n### `platesolve` — plate solving\n\nDétermine, pour chaque pixel de l'image courante, ses coordonnées célestes (WCS : centre, échelle, rotation, parité, et distorsion SIP).\n\n1. **Indices tirés de l'en-tête** de l'image de référence : échelle du pixel (`SCALE`/`PIXSCALE`, sinon 206,265 × `XPIXSZ` / `FOCALLEN`, corrigée du binning, du dématriçage `superpixel` et du `drizzle`), et position approximative (`CRVAL1/2`, `RA/DEC`, `OBJCTRA/OBJCTDEC`, ou, à défaut, le nom de l'objet `OBJECT` recherché dans le catalogue embarqué : « M 42 », « NGC 7000 »…). Les paramètres `scale_arcsec`, `ra`, `dec` remplacent ces valeurs.\n2. **Moteur** : `auto` choisit astrometry.net si le paquet Python `astrometry` est installé, sinon ASTAP s'il est trouvé.\n   - **astrometry.net** (local, hors ligne une fois les index téléchargés) : la luminance est réduite vers ~2000 px, les `max_stars` étoiles les plus brillantes sont détectées (SEP) et envoyées au solveur, qui cherche des « quadrilatères » d'étoiles correspondant aux index. Les échelles d'index sont choisies selon le champ (quadrilatères entre 30 et 70 % du petit côté) : série **4100** (Tycho-2, champs > ~1°) et/ou **5200** (Gaia, petits champs). Les fichiers manquants sont téléchargés une seule fois dans `~/.cache/astrostack/astrometry`.\n   - **ASTAP** (exécutable externe, avec sa base d'étoiles D20/D50…) : l'image est écrite dans un FITS temporaire 16 bits et résolue par `astap_cli`, avec l'indice de champ et de position.\n3. **Recherche à l'aveugle** : si `blind` est actif et que la résolution avec l'indice de position échoue, une seconde tentative est faite sans indice (peut être très longue).\n4. **Résolution des poses brutes** (`frames: true`) : chaque pose est résolue à partir des étoiles déjà mesurées par `quality`, en partant de la solution de l'empilement comme indice. Ces WCS servent notamment à l'alignement `register: {method: wcs}`.\n\n### `annotate` — carte annotée\n\nDessine sur l'image les objets du ciel profond (NGC, IC, Messier) **à leur taille et orientation réelles** (ellipse projetée à partir du grand axe, du petit axe et de l'angle de position), les étoiles brillantes nommées et une grille RA/Dec à pas « rond » adapté au champ (les pôles sont gérés). Les couleurs distinguent galaxies, nébuleuses, amas, nébuleuses planétaires et étoiles. Catalogue : OpenNGC complet téléchargé à la demande dans `~/.cache/astrostack/catalogs`, ou, hors ligne, un extrait embarqué (les 110 objets de Messier et environ 210 NGC/IC brillants ou étendus, plus environ 190 étoiles brillantes nommées). Une image linéaire est étirée automatiquement pour l'affichage ; une image déjà étirée est reprise telle quelle.\n\n### `spcc` — calibration photométrique des couleurs (Gaia DR3)\n\nBalance des blancs fondée sur la photométrie réelle des étoiles du champ, et non sur l'hypothèse « l'étoile moyenne est blanche » de l'étape `color` du cœur :\n\n1. Interrogation de **Gaia DR3** (archive ESA, via `astroquery`) dans le cône couvrant le champ, jusqu'à la magnitude `gmax` ; la réponse est **mise en cache** (`~/.cache/astrostack/gaia`) pour pouvoir rejouer hors ligne.\n2. Détection des étoiles de l'image, projection des étoiles Gaia avec le WCS et appariement au plus proche voisin (unique dans les deux sens).\n3. Photométrie d'ouverture (SEP, rayon 1,5 × FWHM, fond local soustrait dans un anneau) dans chaque canal R, G, B.\n4. **Régression robuste** (rejet itératif à 3 σ) de ln(R/G) et ln(B/G) en fonction de l'indice de couleur Gaia **BP−RP**, sur la plage `bp_rp_range`.\n5. Facteurs R et B qui rendent **blanche** (R = G = B) une étoile de référence : G2V (type solaire, BP−RP = 0,82), galaxie spirale moyenne (0,90) ou indice `bp_rp` personnalisé.\n6. Application des facteurs, avec **neutralisation du fond** (fonds des trois canaux ramenés au même niveau) si demandé.\n7. Calcul d'un **point zéro photométrique** en bande G (médiane de G + 2,5 log₁₀ flux), utilisé ensuite par `snr_analysis` (plugin « analysis ») pour une magnitude limite calibrée. Sur une image monochrome, seul le point zéro est calculé.\n\n### `asteroids` — astéroïdes attendus dans le champ\n\nCalcule l'instant médian de la session (milieu des poses retenues, d'après `DATE-OBS` et le temps de pose, ou le paramètre `date`), puis interroge **MPChecker** du Minor Planet Center (formulaire web) ou, en repli automatique, le service **SkyBoT** de l'IMCCE (via `astroquery`) pour le cône couvrant l'image. Les objets situés dans l'image jusqu'à `limit_mag` sont positionnés avec le WCS, listés (nom, magnitude V, mouvement propre en ″/h) et entourés sur une image de contrôle. Les réponses sont mises en cache sur disque.\n\n## Utilité / quand l'utiliser\n\n- **`platesolve`** : prérequis de toutes les autres étapes du plugin ; donne aussi un FITS final avec en-tête WCS, exploitable par d'autres logiciels (Aladin, Siril, PixInsight, Stellarium…). Utile sur toutes les configurations : Vespera/Seestar (échelle et coordonnées souvent présentes dans l'en-tête), lunette ou télescope avec caméra dédiée (FOCALLEN/XPIXSZ renseignés par le logiciel d'acquisition), appareil photo sur monture (indiquer `scale_arcsec` et `ra`/`dec` ou un nom d'objet si l'en-tête est pauvre).\n- **`annotate`** : identifier les galaxies faibles d'un champ, préparer une image commentée à partager, vérifier le cadrage. Le fichier JSON alimente la superposition d'annotations de l'interface.\n- **`spcc`** : couleurs fidèles sur un **capteur couleur** (OSC, télescopes intelligents) ou une série RGB, en particulier sous un **ciel pollué** où la neutralisation classique est faussée par la dominante du fond, ou dans les champs dominés par une nébuleuse (où « l'étoile moyenne blanche » est biaisée). Remplace l'étape `color`.\n- **`asteroids`** : savoir si le point qui bouge est un astéroïde connu, préparer une observation, compléter l'analyse `transients` (plugin « analysis »).\n\nÀ ne **pas** utiliser :\n\n- sur la Lune, les planètes ou le Soleil (pas de champ d'étoiles à résoudre) ;\n- `spcc` avec un filtre **bande étroite** ou **dual-band** (Hα/OIII) : le modèle en BP−RP suppose un continuum large bande ; utiliser plutôt `color` ou les étapes `dualband`/`narrowband` (plugin « color-tools ») ;\n- `spcc` sur une image déjà étirée : la calibration doit se faire sur des données **linéaires** ;\n- `asteroids` sans connexion réseau et sans cache préalable pour ce champ.\n\n## Installation\n\n```bash\nastrostack plugin install astrometry --deps\n```\n\nOu depuis l'application : vue **Plugins**, fiche « Astrométrie & catalogues », bouton **Installer**, puis installation des dépendances proposée par la fiche.\n\nDépendances Python (`python_deps`), jamais installées automatiquement sans `--deps` ou confirmation :\n\n- `astrometry>=4.1` : solveur astrometry.net embarqué (paquet PyPI `astrometry`), requis pour le moteur astrometry.net ;\n- `astroquery>=0.4` : requêtes Gaia DR3 (`spcc`) et SkyBoT (`asteroids`).\n\nAutres prérequis facultatifs :\n\n- **ASTAP** (<https://www.hnsky.org/astap.htm>) et une base d'étoiles (D20, D50…), si l'on préfère ce moteur ou si le paquet `astrometry` n'est pas installé. L'exécutable est cherché dans le `PATH`, dans `/Applications/ASTAP.app` et dans `/usr/local/bin`, `/opt/astap` ; sinon `astap_path`.\n- **Index astrometry.net** : téléchargés automatiquement au premier usage (quelques centaines de Mo selon les échelles) ; prévoir une connexion la première fois.\n- **Réseau** pour `spcc` (première requête d'un champ), `asteroids` et le premier téléchargement d'OpenNGC.\n\n## Paramètres\n\n### `platesolve`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `engine` | choix : `auto`, `astrometry`, `astap` | `auto` | Moteur : `auto` = astrometry.net si installé, sinon ASTAP. |\n| `scale_arcsec` | réel (0,05 à 200, facultatif) | aucun | Échelle (″/px) de l'image courante ; vide = calculée depuis FOCALLEN/XPIXSZ de l'en-tête. |\n| `scale_tolerance` | réel (0,05 à 0,9) | `0.3` | Tolérance relative sur l'échelle. |\n| `ra` | réel (0 à 360, facultatif) | aucun | Indice : RA du centre (degrés) ; vide = en-tête (RA, OBJCTRA, OBJECT). |\n| `dec` | réel (−90 à 90, facultatif) | aucun | Indice : Dec du centre (degrés). |\n| `radius` | réel (0,5 à 180) | `10.0` | Rayon de recherche autour de l'indice de position (degrés). |\n| `blind` | booléen | `false` | En cas d'échec avec l'indice de position, relancer à l'aveugle (peut être long). |\n| `downsample` | entier (0 à 8) | `0` | Réduction avant détection (0 = auto : ~2000 px). |\n| `max_stars` | entier (20 à 1000) | `150` | Nombre d'étoiles envoyées au solveur. |\n| `threshold` | réel (2 à 50) | `5.0` | Seuil de détection des étoiles (σ). |\n| `series` | choix : `auto`, `4100`, `5200` | `auto` | Série d'index : 4100 (Tycho-2, champs > 1°), 5200 (Gaia, petits champs). |\n| `scales` | texte (facultatif) | `\"\"` | Échelles d'index imposées (ex. « 8,9,10 ») ; vide = selon le champ. |\n| `sip_order` | entier (0 à 5) | `2` | Ordre de la distorsion SIP (0 = aucune). |\n| `frames` | booléen | `false` | Résoudre aussi chaque pose brute (étoiles de l'étape `quality`). |\n| `astap_path` | texte (facultatif) | `\"\"` | Chemin de l'exécutable ASTAP (vide = recherche automatique). |\n| `timeout` | réel (5 à 3600) | `120.0` | Délai maximal d'ASTAP (s). |\n| `cache_dir` | texte (facultatif) | `\"\"` | Dossier des index (défaut `~/.cache/astrostack/astrometry`). |\n\n### `annotate`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `catalog` | choix : `auto`, `openngc`, `embedded` | `auto` | Catalogue : `auto` = OpenNGC téléchargé, sinon extrait embarqué. |\n| `max_mag` | réel (4 à 20) | `14.0` | Magnitude limite des objets du ciel profond. |\n| `stars` | booléen | `true` | Afficher les étoiles nommées. |\n| `star_mag` | réel (−1 à 7) | `6.0` | Magnitude limite des étoiles nommées. |\n| `grid` | booléen | `true` | Grille RA/Dec. |\n| `common_names` | booléen | `true` | Afficher les noms communs (« Andromeda Galaxy »). |\n| `max_size` | entier (512 à 12000) | `2400` | Taille maximale de l'image annotée (px). |\n| `font_scale` | réel (0,2 à 5, facultatif) | aucun | Taille du texte (vide = automatique). |\n| `formats` | liste : `png`, `jpg` | `[png, jpg]` | Fichiers produits. |\n\n### `spcc`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `reference` | choix : `G2V`, `average_spiral_galaxy` | `G2V` | Blanc de référence : étoile G2V ou galaxie spirale moyenne. |\n| `bp_rp` | réel (−0,5 à 4, facultatif) | aucun | Référence personnalisée : indice BP−RP rendu blanc (prioritaire sur `reference`). |\n| `gmax` | réel (8 à 20) | `15.0` | Magnitude G limite des étoiles Gaia. |\n| `threshold` | réel (3 à 50) | `8.0` | Seuil de détection des étoiles (σ). |\n| `max_stars` | entier (50 à 20000) | `3000` | Nombre maximal d'étoiles détectées. |\n| `match_radius` | réel (0,5 à 20, facultatif) | aucun | Rayon d'appariement (px) ; vide = max(2, FWHM). |\n| `min_stars` | entier (5 à 1000) | `20` | Nombre minimum d'étoiles appariées. |\n| `bp_rp_range` | 2 nombres | `[-0.2, 3.0]` | Plage de BP−RP utilisée pour l'ajustement. |\n| `neutralize_background` | booléen | `true` | Neutraliser le fond (gris). |\n| `offline` | booléen | `false` | N'utiliser que le cache Gaia (aucune requête réseau). |\n| `cache_dir` | texte (facultatif) | `\"\"` | Cache Gaia (défaut `~/.cache/astrostack/gaia`). |\n\n### `asteroids`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `limit_mag` | réel (8 à 24) | `19.0` | Magnitude V limite. |\n| `service` | choix : `mpc`, `skybot` | `mpc` | Service d'éphémérides interrogé en premier (repli automatique sur l'autre). |\n| `observatory` | texte | `500` | Code d'observatoire MPC (500 = géocentrique). |\n| `date` | texte (facultatif) | `\"\"` | Date/heure UTC ISO (défaut : milieu de la session, d'après DATE-OBS). |\n| `cache_dir` | texte | `~/.cache/astrostack/mpc` | Cache disque des réponses. |\n| `timeout` | réel (5 à 300) | `60.0` | Délai maximal de la requête (s). |\n\nAucune de ces étapes n'a de paramètre `mask`.\n\n## Exemples YAML\n\nPlacement conseillé : `platesolve` **après `crop`** (et après `drizzle` s'il est actif), car le WCS décrit la géométrie de l'image au moment de l'étape ; toute étape qui recadre ou rééchantillonne ensuite l'image l'invalide. `spcc` **à la place de `color`**, sur l'image encore linéaire, après `background`/`gradient` ; `annotate` et `asteroids` en fin de chaîne, avant `export`.\n\nChaîne type pour un télescope intelligent (Vespera, Seestar) ou une lunette avec capteur couleur :\n\n```yaml\npipeline:\n  - stack: {method: sigma_clip}\n  - crop: {min_coverage: 0.9}\n  - platesolve: {engine: auto}\n  - channel_align: {}\n  - background: {}\n  - spcc: {reference: G2V}          # remplace color\n  - scnr: {amount: 0.8}\n  - stretch: {method: auto}\n  - annotate: {max_mag: 14}\n  - export: {formats: [fits, tiff16, png]}\n```\n\nEn-tête pauvre (appareil photo sur monture) : indices donnés à la main, galaxie comme référence de blanc :\n\n```yaml\npipeline:\n  - crop: {}\n  - platesolve:\n      scale_arcsec: 3.2\n      ra: 83.82\n      dec: -5.39\n      radius: 5\n      blind: true\n  - background: {}\n  - spcc: {reference: average_spiral_galaxy, gmax: 14}\n  - stretch: {}\n```\n\nAstéroïdes et résolution de chaque pose (alignement par WCS), avec code d'observatoire :\n\n```yaml\npipeline:\n  - quality: {}\n  - stack: {}\n  - crop: {}\n  - platesolve: {frames: true, engine: astrometry, series: 5200}\n  - asteroids: {limit_mag: 18, observatory: \"500\"}   # remplacer 500 par le code MPC de votre site\n  - annotate: {formats: [jpg], star_mag: 4}\n  - export: {}\n```\n\n## Sorties\n\n| Étape | Fichiers (dans `output.dir`) | Clés de `ctx.state` |\n|---|---|---|\n| `platesolve` | `<nom>.wcs` (en-tête FITS de la solution) ; le WCS est aussi écrit par le cœur dans l'en-tête du FITS exporté | `wcs` (mots-clés FITS du WCS, avec `IMAGEW`/`IMAGEH`), `wcs_info` (centre, échelle, rotation, champ, retournement), `wcs_frames` (WCS par pose, avec `frames: true`) |\n| `annotate` | `<nom>_annotated.png`, `<nom>_annotated.jpg`, `<nom>_annotations.json` (objets, contours en pixels, grille, WCS, pour la GUI) | `annotations` : `json`, `images`, `count` |\n| `spcc` | `<nom>_spcc.csv` (étoiles utilisées : position, G, BP−RP, flux R/G/B, rapports) ; cache Gaia dans `~/.cache/astrostack/gaia` | `spcc` : `n_stars`, `gaia_stars`, `matched`, `reference`, `bp_rp_ref`, `fit` (pente, ordonnée, dispersion par canal), `factors`, `background`, `zeropoint`, `zeropoint_std`, `aperture_px` |\n| `asteroids` | `<nom>_asteroids.json`, `<nom>_asteroids.png` ; cache dans `~/.cache/astrostack/mpc` | `asteroids` : `n`, `json`, `png`, `service`, `date` (ou `error` si le service est injoignable) |\n\n`spcc` modifie l'image courante (facteurs de couleur et fond) ; les autres étapes la laissent intacte. Aucune n'enregistre de checkpoint. `asteroids` est exclue de l'aperçu interactif (`preview = False`).\n\n## Limites\n\n- **Plate solving** : il faut une estimation correcte de l'échelle (± `scale_tolerance`) et, sauf `blind`, de la position (± `radius`). La recherche à l'aveugle peut être très longue ; elle est désactivée par défaut. Les index astrometry.net pèsent 165 Mo et plus : premier lancement lent et nécessitant le réseau. Le moteur ASTAP n'a été testé qu'avec un exécutable simulé.\n- Le WCS est **invalidé** par tout recadrage ou rééchantillonnage ultérieur : `annotate` et `spcc` s'arrêtent avec un avertissement si la taille de l'image ne correspond plus.\n- **`annotate`** : sans réseau lors du premier usage, seul l'extrait embarqué est disponible (objets brillants ou étendus uniquement). Les tailles d'OpenNGC sont des dimensions catalogue, pas le contour visible sur l'image.\n- **`spcc`** : modèle linéaire en BP−RP, sans courbes de transmission des filtres ni de réponse du capteur ; nécessite au moins `min_stars` étoiles appariées non saturées ; les étoiles de champs très denses peuvent être mal appariées. Première requête Gaia en ligne (archive ESA), qui peut être lente ou indisponible ; ensuite le cache suffit.\n- **`asteroids`** : nécessite un WCS, une date d'observation et le réseau (ou un cache). MPChecker est interrogé via son formulaire web : un changement du format de la page peut rompre l'analyse (le repli SkyBoT prend alors le relais). Positions calculées à un instant unique (milieu de la session) : un astéroïde rapide se déplace pendant la séance. Code `500` = géocentrique, la parallaxe des objets proches n'est alors pas corrigée : indiquer le code de votre observatoire si vous en avez un.\n\n## Licences\n\n- Plugin : licence MIT, © Erwan Sturzenegger.\n- Paquet Python **`astrometry`** (neuromorphicsystems, PyPI) : **GPL-3.0**. Il embarque le code d'**astrometry.net** (D. Lang, D. W. Hogg et al. ; majoritairement BSD-3-Clause, certains composants sous GPL). Le paquet n'est pas redistribué avec le plugin : il est installé séparément par l'utilisateur.\n- **Index astrometry.net** 4100 (construits sur Tycho-2) et 5200 (construits sur Tycho-2 et Gaia) : distribués par astrometry.net ; en cas de publication, citer Lang et al. 2010 (AJ 139, 1782) et les catalogues sources.\n- **ASTAP** (Han Kleijn) et ses bases d'étoiles : logiciel externe, distribué séparément sous sa propre licence.\n- **astroquery** : BSD-3-Clause.\n- **OpenNGC** (Mattia Verga) : **CC-BY-SA 4.0** ; l'extrait embarqué dans le plugin en est dérivé et reste sous cette licence (attribution : OpenNGC, <https://github.com/mattiaverga/OpenNGC>).\n- Étoiles brillantes nommées : positions et magnitudes issues de **SIMBAD** (CDS, Strasbourg) ; citer SIMBAD en cas de publication.\n- **Gaia DR3** : données de la mission Gaia de l'ESA, traitées par le Gaia DPAC ; mention obligatoire « This work has made use of data from the European Space Agency (ESA) mission Gaia, processed by the Gaia Data Processing and Analysis Consortium (DPAC) » et citation de Gaia Collaboration 2016 et 2023 (DR3) en cas de publication.\n- **MPChecker** (Minor Planet Center, IAU) et **SkyBoT** (IMCCE, Observatoire de Paris) : services publics interrogés en ligne ; respecter leurs conditions d'utilisation et citer SkyBoT (Berthier et al. 2006) en cas de publication.\n- Dépendances du cœur utilisées : NumPy, SciPy, Astropy (BSD-3-Clause), OpenCV (Apache 2.0), SEP (LGPL-3.0, parties BSD/MIT).\n","en":"# Astrometry & catalogues\n\nLocal plate solving (astrometry.net or ASTAP), NGC/IC/Messier annotation with an RA/Dec grid, spectrophotometric colour calibration (SPCC) against Gaia DR3 stars, and a search for the asteroids expected in the field (MPC / SkyBoT).\n\n## What it does\n\nThe plugin provides four global stages. `platesolve` computes the astrometric solution (WCS) of the image; the other three rely on it.\n\n### `platesolve` — plate solving\n\nDetermines the sky coordinates of every pixel of the current image (WCS: centre, scale, rotation, parity, and SIP distortion).\n\n1. **Hints taken from the header** of the reference frame: pixel scale (`SCALE`/`PIXSCALE`, otherwise 206.265 × `XPIXSZ` / `FOCALLEN`, corrected for binning, `superpixel` debayering and `drizzle`), and approximate position (`CRVAL1/2`, `RA/DEC`, `OBJCTRA/OBJCTDEC`, or failing that the object name `OBJECT` looked up in the embedded catalogue: \"M 42\", \"NGC 7000\"…). The `scale_arcsec`, `ra` and `dec` parameters override these values.\n2. **Engine**: `auto` picks astrometry.net if the `astrometry` Python package is installed, otherwise ASTAP if it is found.\n   - **astrometry.net** (local, offline once the index files are downloaded): the luminance is downsampled to ~2000 px, the `max_stars` brightest stars are detected (SEP) and passed to the solver, which looks for star \"quads\" matching the index files. Index scales are chosen from the field of view (quads between 30 and 70 % of the short side): series **4100** (Tycho-2, fields > ~1°) and/or **5200** (Gaia, small fields). Missing files are downloaded once into `~/.cache/astrostack/astrometry`.\n   - **ASTAP** (external executable, with its star database D20/D50…): the image is written to a temporary 16-bit FITS and solved by `astap_cli`, with the field-of-view and position hints.\n3. **Blind search**: if `blind` is enabled and solving with the position hint fails, a second attempt is made without the hint (can be very slow).\n4. **Solving the raw frames** (`frames: true`): each frame is solved from the stars already measured by `quality`, using the stack's solution as a hint. These WCS are used in particular by `register: {method: wcs}`.\n\n### `annotate` — annotated chart\n\nDraws on the image the deep-sky objects (NGC, IC, Messier) **at their true size and orientation** (ellipse projected from the major axis, minor axis and position angle), bright named stars, and an RA/Dec grid with a \"round\" spacing suited to the field (poles are handled). Colours distinguish galaxies, nebulae, clusters, planetary nebulae and stars. Catalogue: the full OpenNGC downloaded on demand into `~/.cache/astrostack/catalogs` or, offline, an embedded extract (the 110 Messier objects and about 210 bright or extended NGC/IC objects, plus about 190 bright named stars). A linear image is automatically stretched for display; an already stretched image is used as is.\n\n### `spcc` — spectrophotometric colour calibration (Gaia DR3)\n\nWhite balance based on the actual photometry of the stars in the field, rather than on the \"average star is white\" assumption of the core `color` stage:\n\n1. Queries **Gaia DR3** (ESA archive, via `astroquery`) in the cone covering the field, down to magnitude `gmax`; the response is **cached** (`~/.cache/astrostack/gaia`) so the stage can be replayed offline.\n2. Detects the stars in the image, projects the Gaia stars with the WCS and matches them by nearest neighbour (unique in both directions).\n3. Aperture photometry (SEP, radius 1.5 × FWHM, local background subtracted in an annulus) in each R, G, B channel.\n4. **Robust regression** (iterative 3 σ rejection) of ln(R/G) and ln(B/G) against the Gaia **BP−RP** colour index, over the `bp_rp_range` interval.\n5. R and B factors that make a reference star **white** (R = G = B): G2V (solar type, BP−RP = 0.82), average spiral galaxy (0.90), or a custom `bp_rp` index.\n6. Applies the factors, with **background neutralisation** (the three channel backgrounds brought to the same level) if requested.\n7. Computes a **photometric zero point** in the G band (median of G + 2.5 log₁₀ flux), later used by `snr_analysis` (plugin \"analysis\") for a calibrated limiting magnitude. On a monochrome image, only the zero point is computed.\n\n### `asteroids` — asteroids expected in the field\n\nComputes the median time of the session (middle of the accepted frames, from `DATE-OBS` and exposure time, or the `date` parameter), then queries the Minor Planet Center's **MPChecker** (web form) or, as an automatic fallback, IMCCE's **SkyBoT** service (via `astroquery`) for the cone covering the image. Objects inside the image down to `limit_mag` are placed with the WCS, listed (name, V magnitude, proper motion in ″/h) and circled on a check image. Responses are cached on disk.\n\n## When to use it\n\n- **`platesolve`**: prerequisite for all the other stages of the plugin; also gives a final FITS with a WCS header usable in other software (Aladin, Siril, PixInsight, Stellarium…). Useful with every setup: Vespera/Seestar (scale and coordinates are often in the header), refractor or telescope with a dedicated camera (FOCALLEN/XPIXSZ filled in by the capture software), camera on a mount (give `scale_arcsec` and `ra`/`dec` or an object name if the header is sparse).\n- **`annotate`**: identifying faint galaxies in a field, preparing a labelled image to share, checking the framing. The JSON file feeds the annotation overlay of the interface.\n- **`spcc`**: faithful colours with a **colour sensor** (OSC, smart telescopes) or an RGB series, especially under **light-polluted skies** where classic neutralisation is skewed by the background cast, or in nebula-dominated fields (where the \"average white star\" is biased). Replaces the `color` stage.\n- **`asteroids`**: finding out whether a moving dot is a known asteroid, preparing an observation, complementing the `transients` analysis (plugin \"analysis\").\n\nDo **not** use it:\n\n- on the Moon, planets or the Sun (no star field to solve);\n- `spcc` with a **narrowband** or **dual-band** (Hα/OIII) filter: the BP−RP model assumes a broadband continuum; use `color` or the `dualband`/`narrowband` stages (plugin \"color-tools\") instead;\n- `spcc` on an already stretched image: calibration must be done on **linear** data;\n- `asteroids` without a network connection and without a prior cache for that field.\n\n## Installation\n\n```bash\nastrostack plugin install astrometry --deps\n```\n\nOr from the application: **Plugins** view, \"Astrometry & catalogues\" page, **Install** button, then install the dependencies offered on the page.\n\nPython dependencies (`python_deps`), never installed automatically without `--deps` or confirmation:\n\n- `astrometry>=4.1`: embedded astrometry.net solver (PyPI package `astrometry`), required for the astrometry.net engine;\n- `astroquery>=0.4`: Gaia DR3 queries (`spcc`) and SkyBoT queries (`asteroids`).\n\nOther optional prerequisites:\n\n- **ASTAP** (<https://www.hnsky.org/astap.htm>) and a star database (D20, D50…), if you prefer this engine or if the `astrometry` package is not installed. The executable is looked up in the `PATH`, in `/Applications/ASTAP.app` and in `/usr/local/bin`, `/opt/astap`; otherwise set `astap_path`.\n- **astrometry.net index files**: downloaded automatically on first use (a few hundred MB depending on the scales); a connection is needed the first time.\n- **Network** for `spcc` (first query of a field), `asteroids` and the first OpenNGC download.\n\n## Parameters\n\n### `platesolve`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `engine` | choice: `auto`, `astrometry`, `astap` | `auto` | Engine: `auto` = astrometry.net if installed, otherwise ASTAP. |\n| `scale_arcsec` | float (0.05 to 200, optional) | none | Scale (″/px) of the current image; empty = computed from FOCALLEN/XPIXSZ in the header. |\n| `scale_tolerance` | float (0.05 to 0.9) | `0.3` | Relative tolerance on the scale. |\n| `ra` | float (0 to 360, optional) | none | Hint: RA of the centre (degrees); empty = header (RA, OBJCTRA, OBJECT). |\n| `dec` | float (−90 to 90, optional) | none | Hint: Dec of the centre (degrees). |\n| `radius` | float (0.5 to 180) | `10.0` | Search radius around the position hint (degrees). |\n| `blind` | boolean | `false` | If solving with the position hint fails, retry blind (can be slow). |\n| `downsample` | integer (0 to 8) | `0` | Downsampling before detection (0 = auto: ~2000 px). |\n| `max_stars` | integer (20 to 1000) | `150` | Number of stars sent to the solver. |\n| `threshold` | float (2 to 50) | `5.0` | Star detection threshold (σ). |\n| `series` | choice: `auto`, `4100`, `5200` | `auto` | Index series: 4100 (Tycho-2, fields > 1°), 5200 (Gaia, small fields). |\n| `scales` | text (optional) | `\"\"` | Forced index scales (e.g. \"8,9,10\"); empty = based on the field. |\n| `sip_order` | integer (0 to 5) | `2` | SIP distortion order (0 = none). |\n| `frames` | boolean | `false` | Also solve each raw frame (stars from the `quality` stage). |\n| `astap_path` | text (optional) | `\"\"` | Path of the ASTAP executable (empty = automatic search). |\n| `timeout` | float (5 to 3600) | `120.0` | Maximum ASTAP run time (s). |\n| `cache_dir` | text (optional) | `\"\"` | Index folder (default `~/.cache/astrostack/astrometry`). |\n\n### `annotate`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `catalog` | choice: `auto`, `openngc`, `embedded` | `auto` | Catalogue: `auto` = downloaded OpenNGC, otherwise the embedded extract. |\n| `max_mag` | float (4 to 20) | `14.0` | Limiting magnitude of deep-sky objects. |\n| `stars` | boolean | `true` | Show named stars. |\n| `star_mag` | float (−1 to 7) | `6.0` | Limiting magnitude of named stars. |\n| `grid` | boolean | `true` | RA/Dec grid. |\n| `common_names` | boolean | `true` | Show common names (\"Andromeda Galaxy\"). |\n| `max_size` | integer (512 to 12000) | `2400` | Maximum size of the annotated image (px). |\n| `font_scale` | float (0.2 to 5, optional) | none | Text size (empty = automatic). |\n| `formats` | list: `png`, `jpg` | `[png, jpg]` | Files produced. |\n\n### `spcc`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `reference` | choice: `G2V`, `average_spiral_galaxy` | `G2V` | White reference: G2V star or average spiral galaxy. |\n| `bp_rp` | float (−0.5 to 4, optional) | none | Custom reference: BP−RP index rendered white (takes precedence over `reference`). |\n| `gmax` | float (8 to 20) | `15.0` | Limiting G magnitude of the Gaia stars. |\n| `threshold` | float (3 to 50) | `8.0` | Star detection threshold (σ). |\n| `max_stars` | integer (50 to 20000) | `3000` | Maximum number of detected stars. |\n| `match_radius` | float (0.5 to 20, optional) | none | Matching radius (px); empty = max(2, FWHM). |\n| `min_stars` | integer (5 to 1000) | `20` | Minimum number of matched stars. |\n| `bp_rp_range` | 2 numbers | `[-0.2, 3.0]` | BP−RP range used for the fit. |\n| `neutralize_background` | boolean | `true` | Neutralise the background (grey). |\n| `offline` | boolean | `false` | Only use the Gaia cache (no network query). |\n| `cache_dir` | text (optional) | `\"\"` | Gaia cache (default `~/.cache/astrostack/gaia`). |\n\n### `asteroids`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `limit_mag` | float (8 to 24) | `19.0` | Limiting V magnitude. |\n| `service` | choice: `mpc`, `skybot` | `mpc` | Ephemeris service queried first (automatic fallback to the other). |\n| `observatory` | text | `500` | MPC observatory code (500 = geocentric). |\n| `date` | text (optional) | `\"\"` | UTC date/time in ISO format (default: middle of the session, from DATE-OBS). |\n| `cache_dir` | text | `~/.cache/astrostack/mpc` | Disk cache for the responses. |\n| `timeout` | float (5 to 300) | `60.0` | Maximum query time (s). |\n\nNone of these stages has a `mask` parameter.\n\n## YAML examples\n\nRecommended position: `platesolve` **after `crop`** (and after `drizzle` if enabled), because the WCS describes the geometry of the image at that point; any later stage that crops or resamples the image invalidates it. `spcc` **instead of `color`**, on the still-linear image, after `background`/`gradient`; `annotate` and `asteroids` at the end of the chain, before `export`.\n\nTypical chain for a smart telescope (Vespera, Seestar) or a refractor with a colour sensor:\n\n```yaml\npipeline:\n  - stack: {method: sigma_clip}\n  - crop: {min_coverage: 0.9}\n  - platesolve: {engine: auto}\n  - channel_align: {}\n  - background: {}\n  - spcc: {reference: G2V}          # replaces color\n  - scnr: {amount: 0.8}\n  - stretch: {method: auto}\n  - annotate: {max_mag: 14}\n  - export: {formats: [fits, tiff16, png]}\n```\n\nSparse header (camera on a mount): hints given by hand, galaxy as white reference:\n\n```yaml\npipeline:\n  - crop: {}\n  - platesolve:\n      scale_arcsec: 3.2\n      ra: 83.82\n      dec: -5.39\n      radius: 5\n      blind: true\n  - background: {}\n  - spcc: {reference: average_spiral_galaxy, gmax: 14}\n  - stretch: {}\n```\n\nAsteroids and per-frame solving (WCS-based registration), with an observatory code:\n\n```yaml\npipeline:\n  - quality: {}\n  - stack: {}\n  - crop: {}\n  - platesolve: {frames: true, engine: astrometry, series: 5200}\n  - asteroids: {limit_mag: 18, observatory: \"500\"}   # replace 500 with your site's MPC code\n  - annotate: {formats: [jpg], star_mag: 4}\n  - export: {}\n```\n\n## Outputs\n\n| Stage | Files (in `output.dir`) | `ctx.state` keys |\n|---|---|---|\n| `platesolve` | `<name>.wcs` (FITS header of the solution); the core also writes the WCS into the header of the exported FITS | `wcs` (FITS WCS keywords, with `IMAGEW`/`IMAGEH`), `wcs_info` (centre, scale, rotation, field, flip), `wcs_frames` (per-frame WCS, with `frames: true`) |\n| `annotate` | `<name>_annotated.png`, `<name>_annotated.jpg`, `<name>_annotations.json` (objects, pixel outlines, grid, WCS, for the GUI) | `annotations`: `json`, `images`, `count` |\n| `spcc` | `<name>_spcc.csv` (stars used: position, G, BP−RP, R/G/B fluxes, ratios); Gaia cache in `~/.cache/astrostack/gaia` | `spcc`: `n_stars`, `gaia_stars`, `matched`, `reference`, `bp_rp_ref`, `fit` (slope, intercept, scatter per channel), `factors`, `background`, `zeropoint`, `zeropoint_std`, `aperture_px` |\n| `asteroids` | `<name>_asteroids.json`, `<name>_asteroids.png`; cache in `~/.cache/astrostack/mpc` | `asteroids`: `n`, `json`, `png`, `service`, `date` (or `error` if the service cannot be reached) |\n\n`spcc` modifies the current image (colour factors and background); the other stages leave it untouched. None of them saves a checkpoint. `asteroids` is excluded from the interactive preview (`preview = False`).\n\n## Limitations\n\n- **Plate solving**: a correct estimate of the scale (± `scale_tolerance`) and, unless `blind`, of the position (± `radius`) is required. Blind search can be very slow; it is disabled by default. astrometry.net index files weigh 165 MB and more: the first run is slow and needs the network. The ASTAP engine has only been tested with a simulated executable.\n- The WCS is **invalidated** by any later crop or resampling: `annotate` and `spcc` stop with a warning if the image size no longer matches.\n- **`annotate`**: without network access on first use, only the embedded extract is available (bright or extended objects only). OpenNGC sizes are catalogue dimensions, not the outline visible in the image.\n- **`spcc`**: linear model in BP−RP, without filter transmission or sensor response curves; requires at least `min_stars` matched unsaturated stars; stars in very crowded fields may be mismatched. The first Gaia query is online (ESA archive) and can be slow or unavailable; afterwards the cache is enough.\n- **`asteroids`**: requires a WCS, an observation date and the network (or a cache). MPChecker is queried through its web form: a change in the page format can break parsing (the SkyBoT fallback then takes over). Positions are computed at a single instant (middle of the session): a fast asteroid moves during the session. Code `500` = geocentric, so parallax of nearby objects is not corrected: give your observatory code if you have one.\n\n## Licences\n\n- Plugin: MIT licence, © Erwan Sturzenegger.\n- **`astrometry`** Python package (neuromorphicsystems, PyPI): **GPL-3.0**. It embeds the **astrometry.net** code (D. Lang, D. W. Hogg et al.; mostly BSD-3-Clause, some components under the GPL). The package is not redistributed with the plugin: it is installed separately by the user.\n- **astrometry.net index files** 4100 (built from Tycho-2) and 5200 (built from Tycho-2 and Gaia): distributed by astrometry.net; for publications, cite Lang et al. 2010 (AJ 139, 1782) and the source catalogues.\n- **ASTAP** (Han Kleijn) and its star databases: external software, distributed separately under its own licence.\n- **astroquery**: BSD-3-Clause.\n- **OpenNGC** (Mattia Verga): **CC-BY-SA 4.0**; the extract embedded in the plugin is derived from it and remains under that licence (attribution: OpenNGC, <https://github.com/mattiaverga/OpenNGC>).\n- Bright named stars: positions and magnitudes from **SIMBAD** (CDS, Strasbourg); cite SIMBAD in publications.\n- **Gaia DR3**: data from the ESA Gaia mission, processed by the Gaia DPAC; the acknowledgement \"This work has made use of data from the European Space Agency (ESA) mission Gaia, processed by the Gaia Data Processing and Analysis Consortium (DPAC)\" and citations of Gaia Collaboration 2016 and 2023 (DR3) are required in publications.\n- **MPChecker** (Minor Planet Center, IAU) and **SkyBoT** (IMCCE, Paris Observatory): public online services; follow their terms of use and cite SkyBoT (Berthier et al. 2006) in publications.\n- Core dependencies used: NumPy, SciPy, Astropy (BSD-3-Clause), OpenCV (Apache 2.0), SEP (LGPL-3.0, parts BSD/MIT).\n"}},{"id":"astrosleuth","version":"1.0.0","name":{"fr":"AstroSleuth (agrandissement IA)","en":"AstroSleuth (AI upscaling)"},"summary":{"fr":"Super-résolution esthétique ×2 / ×4 par les réseaux AstroSleuth (ONNX) : image agrandie et plus nette, détails inventés — non scientifique.","en":"Aesthetic ×2 / ×4 super-resolution with the AstroSleuth networks (ONNX): larger, sharper image with invented details — not scientific."},"category":"ai","tags":["ai","upscale","super-resolution","sharpen","onnx"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/astrosleuth","min_astrostack":"0.1.0","entry":"celestiax_astrosleuth","python_deps":["onnxruntime>=1.17"],"stages":["ai_upscale"],"frame_ops":[],"ai":true,"models":[{"id":"astrosleuth-next","name":{"fr":"AstroSleuth NEXT (×4)","en":"AstroSleuth NEXT (×4)"},"url":"https://github.com/Aveygo/AstroSleuth/releases/download/v4/AstroSleuthNEXT.onnx","filename":"AstroSleuthNEXT.onnx","size_mb":18,"sha256":"d78fbadb083cc8a61c8f857a6df71692a9202f805e3d16955859e010d16ff23f","license":"AGPL-3.0","notes":{"fr":"Modèle recommandé (4,5 M paramètres). Publié par Aveygo (auteur d'AstroSleuth) dans les versions GitHub du projet, sous la licence AGPL-3.0 du dépôt.","en":"Recommended model (4.5 M parameters). Published by Aveygo (AstroSleuth's author) in the project's GitHub releases, under the repository's AGPL-3.0 licence."}},{"id":"astrosleuth-fast","name":{"fr":"AstroSleuth FAST (×4)","en":"AstroSleuth FAST (×4)"},"url":"https://github.com/Aveygo/AstroSleuth/releases/download/v3/AstroSleuthFAST.onnx","filename":"AstroSleuthFAST.onnx","size_mb":5,"sha256":"e570af47eae105b177e966af70514f7b28ec13f6052afba3df78a61a89afd15f","license":"AGPL-3.0","notes":{"fr":"Modèle léger (1,2 M paramètres), plus rapide et plus doux. Même provenance et même licence que NEXT.","en":"Light model (1.2 M parameters), faster and softer. Same origin and licence as NEXT."}}],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale : ai_upscale (NEXT ou FAST, ×2 ou ×4, tuiles fondues, étirement réversible).","en":"Initial release: ai_upscale (NEXT or FAST, ×2 or ×4, blended tiles, reversible stretch)."}},"download":"https://celestiax-plugins.sturzy.ch/dl/astrosleuth-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/astrosleuth-1.0.0.zip","size":13683,"sha256":"9402bccb963c822e9da95d7fa08c67b7dc134890d3d8510ba5eb2fbddcb7ead6","readme":{"fr":"# AstroSleuth — agrandissement IA ×2 / ×4\n\nL'étape `ai_upscale` agrandit l'image finale d'un facteur 2 ou 4 avec les réseaux de super-résolution **AstroSleuth** (Aveygo), entraînés sur des images d'astrophotographie : l'image devient plus grande et plus nette, les étoiles plus fines.\n\n> **Résultat esthétique, non scientifique.** Le réseau *invente* des détails plausibles : petites étoiles, textures, aigrettes peuvent apparaître là où il n'y a que du bruit. N'utilisez jamais l'image agrandie pour mesurer (photométrie, astrométrie, FWHM) ni comme document scientifique.\n\n## Quand l'utiliser\n\nÀ la toute fin du traitement, **après l'étirement**, juste avant l'export : pour imprimer en grand, recadrer fortement un petit objet, ou afficher sur un écran haute définition une image de petit capteur. Sur une image encore linéaire, l'étape applique elle-même un étirement MTF réversible (médiane → 0,25), fait passer le réseau, puis revient exactement à l'échelle linéaire.\n\n## Ce que fait le modèle\n\nLes réseaux AstroSleuth (architecture de type Real-ESRGAN) prennent une image RGB dans [0, 1] et rendent une image 4× plus grande, en réduisant aussi le flou, le bruit et les artefacts. Comme dans le projet d'origine, l'image est traitée par tuiles de 256 px avec 16 px de contexte ; ici les tuiles se recouvrent et se **fondent linéairement** (pas de joints), et le ×2 s'obtient en réduisant (INTER_AREA) la sortie ×4 de chaque tuile. Une image mono passe sur 3 canaux identiques. `amount` mélange le résultat du réseau avec un simple agrandissement bicubique.\n\nCe qui suit l'image est remis à l'échelle : carte de couverture, canaux par filtre, version linéaire conservée par `stretch`. Le calque d'étoiles d'un `starless` précédent est oublié, et la solution astrométrique (WCS) aussi : refaites `platesolve` si besoin.\n\n## Modèles, provenance et licence\n\n| Modèle | Fichier | Taille | Licence |\n|---|---|---|---|\n| `astrosleuth-next` (recommandé, 4,5 M paramètres) | [AstroSleuthNEXT.onnx](https://github.com/Aveygo/AstroSleuth/releases/tag/v4) | 18 Mo | AGPL-3.0 |\n| `astrosleuth-fast` (1,2 M paramètres) | [AstroSleuthFAST.onnx](https://github.com/Aveygo/AstroSleuth/releases/tag/v3) | 5 Mo | AGPL-3.0 |\n\nLes modèles sont publiés par leur auteur (Aveygo) dans les versions GitHub du [dépôt AstroSleuth](https://github.com/Aveygo/AstroSleuth), placé sous licence **GNU AGPL-3.0** ; ce plugin ne les redistribue pas, il les télécharge à la demande depuis cette source et vérifie leur empreinte SHA-256 :\n\n```\nastrostack plugin models astrosleuth --download astrosleuth-next\nastrostack plugin models astrosleuth --download astrosleuth-fast\n```\n\n(ou vue Plugins → AstroSleuth → Modèles). Sans modèle, l'étape s'arrête avec `ModelMissing`.\n\n## Paramètres\n\n| Paramètre | Défaut | Rôle |\n|---|---|---|\n| `model` | `next` | `next` (meilleur rendu) ou `fast` (plus doux, plus rapide) |\n| `factor` | 2 | 2 ou 4 (la taille en pixels est multipliée par 4 ou 16) |\n| `amount` | 1,0 | 0 = bicubique seul, 1 = réseau seul |\n| `tile` | 256 | taille des tuiles (128–512) |\n| `device` | `auto` | `auto` (CoreML/GPU puis CPU) ou `cpu` |\n\n## Exemple\n\n```yaml\npipeline:\n  - stack: {}\n  - crop: {}\n  - background: {}\n  - stretch: {method: auto}\n  - ai_upscale: {model: next, factor: 2, amount: 0.8}\n  - export: {formats: [tiff16, png]}\n```\n\n## Contrôle\n\n`.work/ai_upscale_diff.npy` contient ce que le réseau ajoute à un agrandissement bicubique (en unités étirées) : tout ce qui y apparaît est inventé ou reconstruit par le réseau.\n\n## Temps de calcul (Mac M4 Max, image 640×480)\n\n| Cas | CoreML | CPU |\n|---|---|---|\n| NEXT ×2 | 0,9 s (premier appel, compilation comprise) | 5,4 s |\n| NEXT ×4 | 0,6 s | 5,4 s |\n| FAST ×2 / ×4 | 0,2 à 0,6 s | 1,4 s |\n\nLe temps croît avec la surface de l'image d'entrée : NEXT ×2 sur 3000×2000 px prend 9,6 s avec CoreML. L'étape n'est pas rejouée dans l'aperçu en direct (elle change la taille de l'image).\n\n## Limites\n\n- **Non scientifique** : détails inventés, étoiles de bruit, parfois aigrettes ou anneaux artificiels.\n- Entraîné sur des images 8 bits étirées : sur une image linéaire, le résultat dépend de l'étirement interne.\n- Mémoire : ×4 multiplie la taille par 16 (une image 6000×4000 devient 24000×16000, ~4,6 Go en float32) ; préférez ×2 ou recadrez d'abord.\n- Licence AGPL-3.0 des modèles : diffusez-les avec leur licence si vous les redistribuez.\n","en":"# AstroSleuth — AI ×2 / ×4 upscaling\n\nThe `ai_upscale` step enlarges the final image by a factor of 2 or 4 with the **AstroSleuth** super-resolution networks (Aveygo), trained on astrophotographs: the image gets larger and sharper, stars get finer.\n\n> **Aesthetic result, not scientific.** The network *invents* plausible details: small stars, textures, spikes may appear where there is only noise. Never use the upscaled image for measurements (photometry, astrometry, FWHM) or as a scientific record.\n\n## When to use it\n\nAt the very end of processing, **after stretching**, just before export: to print large, crop hard into a small object, or show a small-sensor image on a high-resolution screen. On a still-linear image, the step applies a reversible MTF stretch itself (median → 0.25), runs the network, then returns exactly to the linear scale.\n\n## What the model does\n\nThe AstroSleuth networks (Real-ESRGAN-like architecture) take an RGB image in [0, 1] and return a 4× larger image, also reducing blur, noise and artefacts. As in the original project, the image is processed in 256 px tiles with 16 px of context; here tiles overlap and are **linearly blended** (no seams), and ×2 is obtained by downscaling (INTER_AREA) each tile's ×4 output. Mono images are fed as 3 identical channels. `amount` blends the network output with a plain bicubic enlargement.\n\nWhatever follows the image is rescaled: coverage map, per-filter channels, the linear copy kept by `stretch`. A previous `starless` star layer is dropped, as is the astrometric solution (WCS): run `platesolve` again if needed.\n\n## Models, origin and licence\n\n| Model | File | Size | Licence |\n|---|---|---|---|\n| `astrosleuth-next` (recommended, 4.5 M parameters) | [AstroSleuthNEXT.onnx](https://github.com/Aveygo/AstroSleuth/releases/tag/v4) | 18 MB | AGPL-3.0 |\n| `astrosleuth-fast` (1.2 M parameters) | [AstroSleuthFAST.onnx](https://github.com/Aveygo/AstroSleuth/releases/tag/v3) | 5 MB | AGPL-3.0 |\n\nThe models are published by their author (Aveygo) in the GitHub releases of the [AstroSleuth repository](https://github.com/Aveygo/AstroSleuth), licensed under the **GNU AGPL-3.0**; this plugin does not redistribute them, it downloads them on demand from that source and checks their SHA-256:\n\n```\nastrostack plugin models astrosleuth --download astrosleuth-next\nastrostack plugin models astrosleuth --download astrosleuth-fast\n```\n\n(or Plugins view → AstroSleuth → Models). Without a model, the step stops with `ModelMissing`.\n\n## Parameters\n\n| Parameter | Default | Purpose |\n|---|---|---|\n| `model` | `next` | `next` (best rendering) or `fast` (softer, faster) |\n| `factor` | 2 | 2 or 4 (pixel count multiplied by 4 or 16) |\n| `amount` | 1.0 | 0 = bicubic only, 1 = network only |\n| `tile` | 256 | tile size (128–512) |\n| `device` | `auto` | `auto` (CoreML/GPU then CPU) or `cpu` |\n\n## Example\n\n```yaml\npipeline:\n  - stack: {}\n  - crop: {}\n  - background: {}\n  - stretch: {method: auto}\n  - ai_upscale: {model: next, factor: 2, amount: 0.8}\n  - export: {formats: [tiff16, png]}\n```\n\n## Checking the result\n\n`.work/ai_upscale_diff.npy` holds what the network adds to a bicubic enlargement (in stretched units): everything visible there is invented or reconstructed by the network.\n\n## Processing time (Mac M4 Max, 640×480 image)\n\n| Case | CoreML | CPU |\n|---|---|---|\n| NEXT ×2 | 0.9 s (first call, compilation included) | 5.4 s |\n| NEXT ×4 | 0.6 s | 5.4 s |\n| FAST ×2 / ×4 | 0.2 to 0.6 s | 1.4 s |\n\nTime grows with the input area: NEXT ×2 on 3000×2000 px takes 9.6 s with CoreML. The step is not replayed in the live preview (it changes the image size).\n\n## Limitations\n\n- **Not scientific**: invented details, noise stars, sometimes artificial spikes or rings.\n- Trained on stretched 8-bit images: on a linear image, the result depends on the internal stretch.\n- Memory: ×4 multiplies the pixel count by 16 (a 6000×4000 image becomes 24000×16000, ~4.6 GB in float32); prefer ×2 or crop first.\n- AGPL-3.0 licence of the models: ship them with their licence if you redistribute them.\n"}},{"id":"banding","version":"1.0.0","name":{"fr":"Correction du banding","en":"Banding correction"},"summary":{"fr":"Retire les bandes horizontales et verticales des capteurs CMOS, pose par pose, avant le dématriçage.","en":"Removes horizontal and vertical CMOS banding frame by frame, before debayering."},"category":"calibration","tags":["cmos","banding","calibration"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/banding","min_astrostack":"0.1.0","entry":"celestiax_banding","python_deps":[],"stages":[],"frame_ops":["banding"],"ai":false,"models":[],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale (extraite du cœur d'astrostack)","en":"Initial release (extracted from the astrostack core)"}},"download":"https://celestiax-plugins.sturzy.ch/dl/banding-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/banding-1.0.0.zip","size":8099,"sha256":"53eb2c3acc90278dad4a7a60effc18c31d135589b4b8dbe78df7352d2d2728e7","readme":{"fr":"# Correction du banding\n\nRetire les bandes horizontales et verticales (banding) des capteurs CMOS, pose par pose, avant le dématriçage.\n\n## Fonction\n\nLe plugin fournit une opération par image, **`banding`**, à placer dans la liste `frame_ops:` d'astrostack (application CelestiaX). Les `frame_ops` s'exécutent sur chaque pose, dans les processus de travail, avant l'alignement et l'empilement.\n\nPrincipe : dans une pose, le banding se traduit par un léger décalage de niveau, commun à toute une ligne (ou colonne) du capteur. L'opération estime ce décalage à partir du fond du ciel et le soustrait.\n\n1. **Par couleur CFA** : sur une pose brute couleur (un seul plan avec matrice de Bayer), chacun des quatre sous-plans (R, V1, V2, B) est traité séparément, pour ne pas confondre les couleurs du motif de Bayer. Sur une image mono ou déjà dématricée, chaque canal est traité séparément.\n2. **Masquage des étoiles** : la médiane et le bruit (MAD) du plan sont estimés ; les pixels au-dessus de `fond + star_sigma × σ` (étoiles, galaxies, nébuleuse brillante) sont masqués, masque dilaté de 5 × 5 px. Les pixels non valides (NaN) sont aussi ignorés.\n3. **Profil robuste** : pour chaque ligne (`rows`) ou colonne (`cols`), la médiane des pixels de fond restants donne un profil. Une ligne entièrement masquée reçoit la médiane générale.\n4. **Filtrage d'échelle** : seules les variations plus fines que `scale` lignes/colonnes sont corrigées. Le profil est comparé à sa version lissée par un filtre médian de largeur `scale` ; les variations lentes (gradient de pollution lumineuse, vignetage) sont donc conservées et laissées à l'étape `background` du cœur. Avec `scale: 0`, c'est le profil entier moins sa médiane qui est retiré.\n5. **Correction** : le profil, multiplié par `strength`, est soustrait. Avec `axis: both`, les lignes sont corrigées d'abord, puis les colonnes.\n\n## Utilité / quand l'utiliser\n\n- **Capteurs CMOS à banding visible** : de nombreux capteurs CMOS (caméras astro, APN, télescopes intelligents) montrent de fines bandes horizontales, surtout avec un gain élevé et des poses courtes. Elles ne sont pas aléatoires d'une pose à l'autre et survivent souvent à l'empilement.\n- **Sans darks ni biais** (Vespera, Seestar, poses de télescope intelligent) : le motif de lecture ne peut pas être soustrait par la calibration ; `banding` le retire directement sur chaque pose.\n- **Banding révélé par un étirement fort** : fond de nébuleuse faible, intégrations longues où le bruit aléatoire a baissé et le motif fixe ressort.\n- **Quand ne pas l'utiliser** : si vos darks/biais retirent déjà le motif, ou si aucune bande n'est visible sur l'empilement étiré ; sur un champ où l'objet occupe presque toute l'image (peu de fond pour estimer le profil) ; avec un `scale` trop petit sur des structures fines et rectilignes (bords de nébuleuse alignés sur les lignes).\n- **Position conseillée** : après `calibrate` et `cosmetic`, **avant `debayer`**. Le travail par sous-plan CFA n'a de sens que sur la pose brute.\n\n## Installation\n\n```\nastrostack plugin install banding\n```\n\nOu depuis la vue **Plugins** de l'application CelestiaX. Aucune dépendance Python supplémentaire (`python_deps` vide) : le plugin utilise NumPy, SciPy et OpenCV, déjà requis par le cœur astrostack.\n\n## Paramètres\n\n### `banding` (frame_op)\n\n| Nom | Type | Défaut | Description |\n|---|---|---|---|\n| `axis` | choix (`rows`, `cols`, `both`) | `rows` | Direction du banding : lignes horizontales, colonnes verticales ou les deux |\n| `strength` | réel (0–1) | 1.0 | Fraction de la correction appliquée |\n| `star_sigma` | réel (1–10) | 3.0 | Seuil de masquage des étoiles/objets (σ au-dessus du fond) |\n| `scale` | entier (0–1024) | 64 | Échelle maximale corrigée (lignes/colonnes) ; 0 = pas de filtrage |\n\nConseils : baissez `star_sigma` (2 à 2,5) si la nébuleuse diffuse biaise la correction ; baissez `scale` (16 à 32) pour ne toucher qu'aux bandes très fines ; montez-le (256 ou plus) si les bandes sont larges. Cette opération n'a pas de paramètre `mask` (les masques de post-traitement ne concernent que les étapes `pipeline:`).\n\n## Exemples YAML\n\nPose brute couleur avec banding horizontal (cas le plus courant) :\n\n```yaml\nframe_ops:\n  - calibrate\n  - cosmetic: {auto: true}\n  - banding: {axis: rows}\n  - debayer: {method: bilinear}\n```\n\nTélescope intelligent sans darks, bandes horizontales et verticales, correction un peu adoucie :\n\n```yaml\nframe_ops:\n  - cosmetic: {auto: true}\n  - banding: {axis: both, strength: 0.8, scale: 32}\n  - debayer: {method: rcd}\n```\n\nNébuleuse diffuse qui remplit le champ : masquage plus agressif et correction de toutes les échelles :\n\n```yaml\nframe_ops:\n  - calibrate\n  - banding: {axis: rows, star_sigma: 2.0, scale: 0}\n  - debayer\n```\n\n## Sorties\n\n- Chaque pose est remplacée par sa version corrigée (float32, NaN conservés), avant les opérations suivantes de `frame_ops`.\n- Aucun fichier n'est écrit et aucune clé d'état n'est ajoutée : la correction n'est visible que dans les poses traitées puis dans l'empilement.\n\n## Limites\n\n- Seul un banding **aligné sur les lignes ou colonnes** du capteur est corrigé ; les motifs obliques, ondulés ou les franges d'interférence ne le sont pas.\n- Le profil est estimé sur le fond : une ligne presque entièrement couverte par un objet brillant est mal estimée (elle reçoit la médiane générale).\n- Avec `scale: 0`, les gradients lents le long de l'axe sont aussi retirés, ce qui peut aplatir une nébuleuse étendue.\n- Un banding de faible amplitude par rapport au bruit d'une seule pose est difficile à mesurer : l'effet sera alors limité, l'empilement moyennant déjà une partie du motif s'il varie d'une pose à l'autre.\n\n## Licences\n\n- Plugin : licence MIT, © Erwan Sturzenegger.\n- Dépendances (fournies par le cœur) : NumPy et SciPy (BSD), OpenCV (Apache 2.0), SEP (LGPL / BSD).\n","en":"# Banding correction\n\nRemoves horizontal and vertical CMOS banding frame by frame, before debayering.\n\n## What it does\n\nThe plugin provides one per-frame operation, **`banding`**, to be placed in the `frame_ops:` list of astrostack (the CelestiaX application). `frame_ops` run on every frame, in the worker processes, before registration and stacking.\n\nPrinciple: in a frame, banding shows up as a small level offset shared by a whole sensor row (or column). The operation estimates this offset from the sky background and subtracts it.\n\n1. **Per CFA colour**: on a raw colour frame (a single plane with a Bayer matrix), each of the four sub-planes (R, G1, G2, B) is processed separately, so that the colours of the Bayer pattern are not mixed up. On a mono or already debayered image, each channel is processed separately.\n2. **Star masking**: the median and noise (MAD) of the plane are estimated; pixels above `background + star_sigma × σ` (stars, galaxies, bright nebula) are masked, with the mask dilated by 5 × 5 px. Invalid pixels (NaN) are ignored as well.\n3. **Robust profile**: for each row (`rows`) or column (`cols`), the median of the remaining background pixels gives a profile. A fully masked row receives the overall median.\n4. **Scale filtering**: only variations finer than `scale` rows/columns are corrected. The profile is compared with a version smoothed by a median filter of width `scale`; slow variations (light-pollution gradient, vignetting) are therefore kept and left to the core `background` stage. With `scale: 0`, the whole profile minus its median is removed.\n5. **Correction**: the profile, multiplied by `strength`, is subtracted. With `axis: both`, rows are corrected first, then columns.\n\n## Why / when to use it\n\n- **CMOS sensors with visible banding**: many CMOS sensors (astro cameras, DSLRs/mirrorless, smart telescopes) show thin horizontal bands, especially at high gain and with short exposures. They are not random from frame to frame and often survive stacking.\n- **Without darks or bias** (Vespera, Seestar, smart-telescope frames): the readout pattern cannot be subtracted by calibration; `banding` removes it directly on each frame.\n- **Banding revealed by a strong stretch**: faint nebula backgrounds, long integrations where random noise has dropped and the fixed pattern stands out.\n- **When not to use it**: if your darks/bias already remove the pattern, or if no band is visible on the stretched stack; on a field where the object fills almost the whole image (little background to estimate the profile); with a too small `scale` on thin straight structures (nebula edges aligned with the rows).\n- **Recommended position**: after `calibrate` and `cosmetic`, **before `debayer`**. Working per CFA sub-plane only makes sense on the raw frame.\n\n## Installation\n\n```\nastrostack plugin install banding\n```\n\nOr from the **Plugins** view of the CelestiaX application. No extra Python dependency (`python_deps` is empty): the plugin uses NumPy, SciPy and OpenCV, already required by the astrostack core.\n\n## Parameters\n\n### `banding` (frame_op)\n\n| Name | Type | Default | Description |\n|---|---|---|---|\n| `axis` | choice (`rows`, `cols`, `both`) | `rows` | Banding direction: horizontal rows, vertical columns or both |\n| `strength` | float (0–1) | 1.0 | Fraction of the correction applied |\n| `star_sigma` | float (1–10) | 3.0 | Star/object masking threshold (σ above background) |\n| `scale` | int (0–1024) | 64 | Largest corrected scale (rows/columns); 0 = no filtering |\n\nTips: lower `star_sigma` (2 to 2.5) if diffuse nebulosity biases the correction; lower `scale` (16 to 32) to touch only very thin bands; raise it (256 or more) if the bands are wide. This operation has no `mask` parameter (post-processing masks only apply to `pipeline:` stages).\n\n## YAML examples\n\nRaw colour frame with horizontal banding (the most common case):\n\n```yaml\nframe_ops:\n  - calibrate\n  - cosmetic: {auto: true}\n  - banding: {axis: rows}\n  - debayer: {method: bilinear}\n```\n\nSmart telescope without darks, horizontal and vertical bands, slightly softened correction:\n\n```yaml\nframe_ops:\n  - cosmetic: {auto: true}\n  - banding: {axis: both, strength: 0.8, scale: 32}\n  - debayer: {method: rcd}\n```\n\nDiffuse nebula filling the field: more aggressive masking and correction at all scales:\n\n```yaml\nframe_ops:\n  - calibrate\n  - banding: {axis: rows, star_sigma: 2.0, scale: 0}\n  - debayer\n```\n\n## Outputs\n\n- Each frame is replaced by its corrected version (float32, NaN preserved), before the next `frame_ops` operations.\n- No file is written and no state key is added: the correction is only visible in the processed frames and then in the stack.\n\n## Limitations\n\n- Only banding **aligned with the sensor rows or columns** is corrected; oblique or wavy patterns and interference fringes are not.\n- The profile is estimated on the background: a row almost entirely covered by a bright object is poorly estimated (it receives the overall median).\n- With `scale: 0`, slow gradients along the axis are removed too, which can flatten an extended nebula.\n- Banding that is weak compared with the noise of a single frame is hard to measure: the effect will then be limited, stacking already averaging out part of the pattern if it varies from frame to frame.\n\n## Licences\n\n- Plugin: MIT licence, © Erwan Sturzenegger.\n- Dependencies (provided by the core): NumPy and SciPy (BSD), OpenCV (Apache 2.0), SEP (LGPL / BSD).\n"}},{"id":"color-tools","version":"1.0.0","name":{"fr":"Outils couleur","en":"Colour tools"},"summary":{"fr":"Saturation masquée et décalages de teinte, palettes narrowband (SHO, HOO, HSO, Foraxx), combinaison LRGB, extraction dual-band.","en":"Masked saturation and hue shifts, narrowband palettes (SHO, HOO, HSO, Foraxx), LRGB combination, dual-band extraction."},"category":"post","tags":["saturation","narrowband","sho","hoo","lrgb","dual-band"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/color-tools","min_astrostack":"0.1.0","entry":"celestiax_color_tools","python_deps":[],"stages":["saturation","narrowband","lrgb","dualband"],"frame_ops":[],"ai":false,"models":[],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale (extraite du cœur d'astrostack)","en":"Initial release (extracted from the astrostack core)"}},"download":"https://celestiax-plugins.sturzy.ch/dl/color-tools-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/color-tools-1.0.0.zip","size":14937,"sha256":"418f7e2d684aca5335b960889ad9a50a834c0ee6eb4923fc3c70c9e9a4233f4c","readme":{"fr":"# Outils couleur\n\nSaturation ciblée et retouche des teintes, palettes narrowband (SHO, HOO, HSO, Foraxx), combinaison LRGB et extraction Hα / OIII d'un capteur couleur avec filtre dual-band.\n\n## Fonction\n\nLe plugin fournit quatre étapes de post-traitement (`pipeline:`) pour astrostack (application CelestiaX).\n\n- **`saturation`** : augmente (ou diminue) la saturation à travers un masque de luminance : le poids vaut 1 entre `low` et `high` et retombe doucement à 0 en dessous (fond du ciel) et au-dessus (cœurs brillants), avec des transitions de largeur `soft`. Le gain `1 + amount × poids` multiplie la chrominance a*/b* en CIELab (défaut, préserve la luminosité), ou la saturation en HSV / HSL. Les règles `hue_shift` déplacent ensuite certaines teintes sur la roue HSV (0 rouge, 120 vert, 240 bleu) : poids triangulaire autour de la teinte `from`, sur ± `range` degrés, vers la teinte `to` ; les pixels peu saturés (fond neutre) sont épargnés.\n- **`narrowband`** : compose une image RVB à partir des canaux Hα, OIII et SII empilés séparément. Les fonds sont égalisés (médiane retirée, piédestal commun) et, avec `normalize`, OIII et SII sont ramenés à l'échelle du signal Hα (99,5e percentile au-dessus du fond). Chaque canal est pondéré (`weights`), éventuellement étiré automatiquement (`stretch_inputs`), puis la palette est construite :\n  - `SHO` (palette Hubble) : R = SII, V = Hα, B = OIII ;\n  - `HSO` : R = Hα, V = SII, B = OIII ;\n  - `HOO` : R = Hα, V = B = OIII ;\n  - `Foraxx` : palette dynamique de Paulo Foraxx, qui mélange Hα et OIII (et SII) pixel par pixel selon leur intensité, pour des tons or / bleu plus naturels.\n  Avec `ha_to_red`, l'étape fait autre chose : elle ajoute au rouge d'une image RVB l'excès de Hα (Hα mis à l'échelle du rouge, moins le rouge, borné à 0), dosé par `amount`.\n- **`lrgb`** : remplace la luminance d'une image couleur par un canal L plus profond, en CIELab. L est d'abord ajustée (médiane et hautes lumières) sur la luminance de l'image RVB (`match`), puis mélangée (`l_weight`) ; la chrominance a*/b* peut être amplifiée (`saturation`).\n- **`dualband`** : sépare une image couleur prise avec un filtre dual-band (L-eXtreme, L-eNhance, ALP-T…) en Hα = R et OIII = moyenne pondérée de V et B. Les deux canaux sont écrits dans `ctx.channels` (utilisables ensuite par `narrowband`) et l'image devient une palette HOO, le canal Hα seul, le canal OIII seul, ou reste inchangée.\n\n### Canaux `ctx.channels`\n\n`narrowband` et `lrgb` lisent les canaux empilés **par filtre**. Pour les obtenir, déclarez dans la configuration du cœur `input: {group_by: filter}` : astrostack empile séparément chaque filtre lu dans le mot-clé FITS `FILTER`, sur une référence d'alignement commune, et range le résultat dans `ctx.channels` (`{nom du filtre: image}`). Les noms sont normalisés : `Ha`, `H`, `HALPHA` → `Ha` ; `O3`, `OIII` → `OIII` ; `S2`, `SII` → `SII` ; `L`, `LUM` → `L` ; `R`, `G`, `B`. Un canal de taille différente est redimensionné (Lanczos) avec un avertissement. `dualband` crée lui-même les canaux `Ha` et `OIII` à partir d'une image couleur.\n\n## Utilité / quand l'utiliser\n\n- **Vespera, Seestar, capteur couleur** : `saturation` après l'étirement pour raviver une nébuleuse sans colorer le bruit du fond ni saturer les étoiles ; `hue_shift` pour corriger une dominante (orangé tirant vers le rouge, cyan vers le bleu).\n- **Capteur couleur + filtre dual-band** (Seestar avec filtre LP intégré, Vespera avec filtre dual-band) : `dualband` pour une image HOO, ou pour extraire Hα et OIII puis appliquer `narrowband` en Foraxx.\n- **Données SHO mono** (roue à filtres Hα / OIII / SII) : `narrowband` avec `group_by: filter`. Palette `SHO` classique, `HOO` pour les nébuleuses riches en OIII, `Foraxx` pour un rendu plus doux.\n- **Hα sur une image RVB** (galaxie avec régions HII, nébuleuse faible) : `narrowband` avec `ha_to_red`.\n- **LRGB mono** : `lrgb` combine une luminance longue et des couches couleur plus courtes (éventuellement en binning).\n- **Quand ne pas l'utiliser** : `saturation` sur une image encore linéaire (les couleurs y sont invisibles, le masque de luminance n'a pas de sens) ; `narrowband` / `lrgb` sans `group_by: filter` (pas de canaux : étape ignorée) ; `dualband` sur une image prise sans filtre dual-band (le rouge n'est alors pas du Hα).\n- **Position conseillée** : `dualband`, `narrowband` et `lrgb` après `crop` et `background`, sur l'empilement linéaire (sauf Foraxx, avec `stretch_inputs: true`) et avant `stretch` ; `saturation` sur l'image **étirée**.\n\n## Installation\n\n```\nastrostack plugin install color-tools\n```\n\nOu depuis la vue **Plugins** de l'application CelestiaX. Aucune dépendance Python supplémentaire (`python_deps` vide) : le plugin utilise NumPy, OpenCV et PyYAML, déjà requis par le cœur astrostack.\n\n## Paramètres\n\n### `saturation`\n\n| Nom | Type | Défaut | Description |\n|---|---|---|---|\n| `amount` | réel (−1 à 3) | 0.4 | Gain de saturation (0 = aucun, négatif = désature) |\n| `low` | réel (0–1) | 0.1 | Luminance en dessous de laquelle rien n'est saturé (fond) |\n| `high` | réel (0–1) | 0.9 | Luminance au-dessus de laquelle rien n'est saturé (cœurs) |\n| `soft` | réel (0.001–0.5) | 0.08 | Largeur des transitions du masque de luminance |\n| `space` | choix (`lab`, `hsv`, `hsl`) | `lab` | Espace de travail de la saturation |\n| `hue_shift` | texte (YAML), facultatif | vide | Règles de teinte : `[{from: 0-360, to: 0-360, range: degrés, amount}]` |\n| `mask` | texte, facultatif | vide | Masque de post-traitement (voir ci-dessous) |\n\nDans `hue_shift`, `range` vaut 30 et `amount` 1 par défaut ; une règle seule peut être donnée sans crochets.\n\n### `narrowband`\n\n| Nom | Type | Défaut | Description |\n|---|---|---|---|\n| `palette` | choix (`SHO`, `HOO`, `HSO`, `Foraxx`) | `SHO` | Palette (SHO et HSO nécessitent SII ; Foraxx : dynamique) |\n| `weights` | 3 réels | `[1.0, 1.0, 1.0]` | Poids Hα, OIII, SII |\n| `equalize` | booléen | `true` | Égalise les fonds des canaux |\n| `normalize` | booléen | `true` | Ramène OIII / SII à l'échelle du signal Hα |\n| `stretch_inputs` | booléen | `false` | Étire chaque canal avant combinaison (automatique) |\n| `target_background` | réel (0.02–0.5) | 0.15 | Fond cible de l'étirement des canaux |\n| `ha_to_red` | texte, facultatif | vide | Ajout de Hα au rouge d'une image RVB, ex. `{amount: 0.5}` (ou un simple nombre) |\n\n### `lrgb`\n\n| Nom | Type | Défaut | Description |\n|---|---|---|---|\n| `l_weight` | réel (0–1) | 1.0 | Part de L dans la luminance finale |\n| `saturation` | réel (0–3) | 1.0 | Facteur de chrominance (a*, b*) |\n| `match` | booléen | `true` | Ajuste L sur la luminance RVB avant remplacement |\n\n### `dualband`\n\n| Nom | Type | Défaut | Description |\n|---|---|---|---|\n| `oiii_weights` | 2 réels | `[0.5, 0.5]` | Poids de V et B pour OIII |\n| `output` | choix (`HOO`, `ha`, `oiii`, `keep`) | `HOO` | Image produite |\n| `equalize` | booléen | `true` | Égalise les fonds (HOO) |\n| `normalize` | booléen | `true` | Ramène OIII à l'échelle de Hα (HOO) |\n\n### Le paramètre `mask`\n\n`saturation` accepte les masques du cœur astrostack. Le masque (0 à 1) est calculé sur l'image avant l'étape et le résultat vaut `avant × (1 − m) + après × m`. Forme courte ou dictionnaire YAML : `mask: \"stars invert\"` (ne sature pas les étoiles), `mask: \"object feather=8\"` (seulement la nébuleuse), `mask: \"color hue=[180,260]\"` (seulement les bleus). Types : `luminance`, `color`, `stars`, `object`, `range`, `file`, `combine` ; options communes `invert`, `blur`, `strength`.\n\n## Exemples YAML\n\nNébuleuse au Vespera : saturation hors étoiles et orangés ramenés vers le rouge :\n\n```yaml\npipeline:\n  - stretch: {}\n  - saturation:\n      amount: 0.6\n      mask: \"stars invert\"\n      hue_shift: [{from: 30, to: 0, range: 20, amount: 0.7}]\n```\n\nDonnées SHO mono empilées par filtre, palette Hubble :\n\n```yaml\ninput: {lights: \"lights/*.fits\", group_by: filter}\npipeline:\n  # … masters, quality, register, stack, crop, background …\n  - narrowband: {palette: SHO, weights: [1.0, 1.2, 0.9]}\n  - stretch: {}\n```\n\nCapteur couleur + filtre dual-band, rendu Foraxx :\n\n```yaml\npipeline:\n  - dualband: {output: keep}\n  - narrowband: {palette: Foraxx, stretch_inputs: true, target_background: 0.15}\n```\n\n## Sorties\n\n- `saturation`, `lrgb` : modifient `ctx.image` (les bords NaN sont préservés pour `saturation`).\n- `narrowband` : `ctx.image` devient l'image RVB de la palette (valeurs négatives ramenées à 0). Avec `stretch_inputs`, si l'image n'a pas encore été étirée, `ctx.linear` reçoit la version linéaire de la palette. Avec `ha_to_red`, seul le canal rouge de `ctx.image` est modifié.\n- `dualband` : écrit `ctx.channels[\"Ha\"]` et `ctx.channels[\"OIII\"]`, puis remplace `ctx.image` selon `output`.\n- Aucun fichier n'est écrit ; chaque étape affiche un résumé dans la console. Les étapes sans les données requises (image monochrome pour `saturation`, canaux absents pour `narrowband` / `lrgb`, image non couleur pour `dualband`) sont ignorées avec un avertissement.\n\n## Limites\n\n- `dualband` suppose une séparation idéale : le canal rouge contient aussi du SII et du continuum, et V/B mêlent Hα et OIII selon la réponse du capteur ; ce n'est pas une vraie séparation spectrale.\n- `narrowband` sans SII remplace `SHO` / `HSO` par `HOO`. Hα et OIII sont obligatoires.\n- `hue_shift` travaille en HSV et ignore les pixels peu saturés ; une dominante sur le fond gris se corrige plutôt avec l'étape `color` du cœur.\n- `lrgb` suppose que L et RVB sont alignés (même référence d'alignement, ce que fait `group_by: filter`).\n\n## Licences\n\n- Plugin : licence MIT, © Erwan Sturzenegger.\n- Dépendances (fournies par le cœur) : NumPy et SciPy (BSD), OpenCV (Apache 2.0), SEP (LGPL / BSD).\n","en":"# Colour tools\n\nTargeted saturation and hue adjustments, narrowband palettes (SHO, HOO, HSO, Foraxx), LRGB combination and Hα / OIII extraction from a colour sensor with a dual-band filter.\n\n## What it does\n\nThe plugin provides four post-processing stages (`pipeline:`) for astrostack (the CelestiaX application).\n\n- **`saturation`**: increases (or decreases) saturation through a luminance mask: the weight is 1 between `low` and `high` and smoothly falls to 0 below (sky background) and above (bright cores), with transitions of width `soft`. The gain `1 + amount × weight` multiplies the a*/b* chrominance in CIELab (default, preserves brightness), or the saturation in HSV / HSL. The `hue_shift` rules then move selected hues on the HSV wheel (0 red, 120 green, 240 blue): triangular weight around the `from` hue, over ± `range` degrees, towards the `to` hue; weakly saturated pixels (neutral background) are left alone.\n- **`narrowband`**: builds an RGB image from separately stacked Hα, OIII and SII channels. Backgrounds are equalised (median removed, common pedestal) and, with `normalize`, OIII and SII are brought to the scale of the Hα signal (99.5th percentile above background). Each channel is weighted (`weights`), optionally auto-stretched (`stretch_inputs`), then the palette is built:\n  - `SHO` (Hubble palette): R = SII, G = Hα, B = OIII;\n  - `HSO`: R = Hα, G = SII, B = OIII;\n  - `HOO`: R = Hα, G = B = OIII;\n  - `Foraxx`: Paulo Foraxx's dynamic palette, which blends Hα and OIII (and SII) pixel by pixel according to their intensity, for more natural gold / blue tones.\n  With `ha_to_red`, the stage does something else: it adds the Hα excess (Hα scaled to the red channel, minus the red, floored at 0) to the red channel of an RGB image, weighted by `amount`.\n- **`lrgb`**: replaces the luminance of a colour image with a deeper L channel, in CIELab. L is first matched (median and highlights) to the luminance of the RGB image (`match`), then blended (`l_weight`); the a*/b* chrominance can be boosted (`saturation`).\n- **`dualband`**: splits a colour image taken with a dual-band filter (L-eXtreme, L-eNhance, ALP-T…) into Hα = R and OIII = weighted mean of G and B. Both channels are written to `ctx.channels` (usable afterwards by `narrowband`) and the image becomes an HOO palette, the Hα channel alone, the OIII channel alone, or stays unchanged.\n\n### The `ctx.channels` channels\n\n`narrowband` and `lrgb` read channels stacked **per filter**. To get them, set `input: {group_by: filter}` in the core configuration: astrostack stacks each filter read from the FITS `FILTER` keyword separately, on a common alignment reference, and stores the result in `ctx.channels` (`{filter name: image}`). Names are normalised: `Ha`, `H`, `HALPHA` → `Ha`; `O3`, `OIII` → `OIII`; `S2`, `SII` → `SII`; `L`, `LUM` → `L`; `R`, `G`, `B`. A channel with a different size is resized (Lanczos) with a warning. `dualband` creates the `Ha` and `OIII` channels itself from a colour image.\n\n## Why / when to use it\n\n- **Vespera, Seestar, colour sensor**: `saturation` after stretching to bring a nebula to life without colouring the background noise or saturating the stars; `hue_shift` to fix a colour cast (orange drifting to red, cyan to blue).\n- **Colour sensor + dual-band filter** (Seestar with its built-in LP filter, Vespera with a dual-band filter): `dualband` for an HOO image, or to extract Hα and OIII and then apply `narrowband` in Foraxx.\n- **Mono SHO data** (filter wheel with Hα / OIII / SII): `narrowband` with `group_by: filter`. Classic `SHO` palette, `HOO` for OIII-rich nebulae, `Foraxx` for a softer rendering.\n- **Hα on an RGB image** (galaxy with HII regions, faint nebula): `narrowband` with `ha_to_red`.\n- **Mono LRGB**: `lrgb` combines a long luminance with shorter colour layers (possibly binned).\n- **When not to use it**: `saturation` on a still-linear image (colours are invisible there, the luminance mask makes no sense); `narrowband` / `lrgb` without `group_by: filter` (no channels: the stage is skipped); `dualband` on an image taken without a dual-band filter (the red channel is then not Hα).\n- **Recommended position**: `dualband`, `narrowband` and `lrgb` after `crop` and `background`, on the linear stack (except Foraxx, with `stretch_inputs: true`) and before `stretch`; `saturation` on the **stretched** image.\n\n## Installation\n\n```\nastrostack plugin install color-tools\n```\n\nOr from the **Plugins** view of the CelestiaX application. No extra Python dependency (`python_deps` is empty): the plugin uses NumPy, OpenCV and PyYAML, already required by the astrostack core.\n\n## Parameters\n\n### `saturation`\n\n| Name | Type | Default | Description |\n|---|---|---|---|\n| `amount` | float (−1 to 3) | 0.4 | Saturation gain (0 = none, negative = desaturate) |\n| `low` | float (0–1) | 0.1 | Luminance below which nothing is saturated (background) |\n| `high` | float (0–1) | 0.9 | Luminance above which nothing is saturated (cores) |\n| `soft` | float (0.001–0.5) | 0.08 | Width of the luminance mask transitions |\n| `space` | choice (`lab`, `hsv`, `hsl`) | `lab` | Colour space used for saturation |\n| `hue_shift` | text (YAML), optional | empty | Hue rules: `[{from: 0-360, to: 0-360, range: degrees, amount}]` |\n| `mask` | text, optional | empty | Post-processing mask (see below) |\n\nIn `hue_shift`, `range` defaults to 30 and `amount` to 1; a single rule can be given without brackets.\n\n### `narrowband`\n\n| Name | Type | Default | Description |\n|---|---|---|---|\n| `palette` | choice (`SHO`, `HOO`, `HSO`, `Foraxx`) | `SHO` | Palette (SHO and HSO need SII; Foraxx: dynamic) |\n| `weights` | 3 floats | `[1.0, 1.0, 1.0]` | Hα, OIII, SII weights |\n| `equalize` | bool | `true` | Equalise channel backgrounds |\n| `normalize` | bool | `true` | Bring OIII / SII to the scale of the Hα signal |\n| `stretch_inputs` | bool | `false` | Stretch each channel before combining (automatic) |\n| `target_background` | float (0.02–0.5) | 0.15 | Target background of the channel stretch |\n| `ha_to_red` | text, optional | empty | Add Hα to the red of an RGB image, e.g. `{amount: 0.5}` (or a plain number) |\n\n### `lrgb`\n\n| Name | Type | Default | Description |\n|---|---|---|---|\n| `l_weight` | float (0–1) | 1.0 | Share of L in the final luminance |\n| `saturation` | float (0–3) | 1.0 | Chrominance factor (a*, b*) |\n| `match` | bool | `true` | Match L to the RGB luminance before replacing it |\n\n### `dualband`\n\n| Name | Type | Default | Description |\n|---|---|---|---|\n| `oiii_weights` | 2 floats | `[0.5, 0.5]` | G and B weights for OIII |\n| `output` | choice (`HOO`, `ha`, `oiii`, `keep`) | `HOO` | Output image |\n| `equalize` | bool | `true` | Equalise backgrounds (HOO) |\n| `normalize` | bool | `true` | Bring OIII to the scale of Hα (HOO) |\n\n### The `mask` parameter\n\n`saturation` accepts the astrostack core masks. The mask (0 to 1) is computed on the image before the stage and the result is `before × (1 − m) + after × m`. Short form or YAML dictionary: `mask: \"stars invert\"` (do not saturate the stars), `mask: \"object feather=8\"` (nebula only), `mask: \"color hue=[180,260]\"` (blues only). Types: `luminance`, `color`, `stars`, `object`, `range`, `file`, `combine`; common options `invert`, `blur`, `strength`.\n\n## YAML examples\n\nVespera nebula: saturation outside the stars, oranges pulled towards red:\n\n```yaml\npipeline:\n  - stretch: {}\n  - saturation:\n      amount: 0.6\n      mask: \"stars invert\"\n      hue_shift: [{from: 30, to: 0, range: 20, amount: 0.7}]\n```\n\nMono SHO data stacked per filter, Hubble palette:\n\n```yaml\ninput: {lights: \"lights/*.fits\", group_by: filter}\npipeline:\n  # … masters, quality, register, stack, crop, background …\n  - narrowband: {palette: SHO, weights: [1.0, 1.2, 0.9]}\n  - stretch: {}\n```\n\nColour sensor + dual-band filter, Foraxx rendering:\n\n```yaml\npipeline:\n  - dualband: {output: keep}\n  - narrowband: {palette: Foraxx, stretch_inputs: true, target_background: 0.15}\n```\n\n## Outputs\n\n- `saturation`, `lrgb`: modify `ctx.image` (NaN borders are preserved by `saturation`).\n- `narrowband`: `ctx.image` becomes the RGB palette image (negative values clipped to 0). With `stretch_inputs`, if the image has not been stretched yet, `ctx.linear` receives the linear version of the palette. With `ha_to_red`, only the red channel of `ctx.image` is modified.\n- `dualband`: writes `ctx.channels[\"Ha\"]` and `ctx.channels[\"OIII\"]`, then replaces `ctx.image` according to `output`.\n- No file is written; each stage prints a summary in the console. Stages lacking the required data (monochrome image for `saturation`, missing channels for `narrowband` / `lrgb`, non-colour image for `dualband`) are skipped with a warning.\n\n## Limitations\n\n- `dualband` assumes an ideal split: the red channel also contains SII and continuum, and G/B mix Hα and OIII depending on the sensor response; it is not a true spectral separation.\n- Without SII, `narrowband` replaces `SHO` / `HSO` with `HOO`. Hα and OIII are mandatory.\n- `hue_shift` works in HSV and ignores weakly saturated pixels; a cast on the grey background is better fixed with the core `color` stage.\n- `lrgb` assumes L and RGB are aligned (same alignment reference, which `group_by: filter` provides).\n\n## Licences\n\n- Plugin: MIT licence, © Erwan Sturzenegger.\n- Dependencies (provided by the core): NumPy and SciPy (BSD), OpenCV (Apache 2.0), SEP (LGPL / BSD).\n"}},{"id":"comet","version":"1.0.0","name":{"fr":"Empilement comète","en":"Comet stacking"},"summary":{"fr":"Second empilement aligné sur le noyau de la comète (mouvement interpolé dans le temps), fusionné au stack étoiles.","en":"Second stack aligned on the comet nucleus (motion interpolated in time), blended into the star-aligned stack."},"category":"stacking","tags":["comet","stacking"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/comet","min_astrostack":"0.1.0","entry":"celestiax_comet","python_deps":[],"stages":["comet_stack"],"frame_ops":[],"ai":false,"models":[],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale (extraite du cœur d'astrostack)","en":"Initial release (extracted from the astrostack core)"}},"download":"https://celestiax-plugins.sturzy.ch/dl/comet-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/comet-1.0.0.zip","size":10131,"sha256":"0d04c73408d739664a45f9f653d413c1345466e3077b3914e4430b49176bdfb4","readme":{"fr":"# Empilement comète\n\nSecond empilement des poses aligné sur le noyau de la comète (mouvement interpolé dans le temps), puis fusionné dans l'empilement aligné sur les étoiles pour obtenir une comète nette sur un champ d'étoiles ponctuelles.\n\n## Fonction\n\nLe plugin fournit une étape globale, `comet_stack`.\n\nUne comète se déplace par rapport aux étoiles pendant la séance : un empilement classique, aligné sur les étoiles, étale le noyau et la coma en une traînée floue. `comet_stack` réalise un **second empilement** dans lequel c'est le noyau qui reste fixe :\n\n1. **Position du noyau.** Vous indiquez la position (x, y) du noyau sur la première image acceptée (`start`) et sur la dernière (`end`), en pixels de ces images. Ces deux points sont ramenés dans le repère de l'image de référence grâce aux transformations calculées par `register`.\n2. **Interpolation du mouvement.** La position du noyau sur chaque pose intermédiaire est interpolée linéairement entre ces deux points, soit en fonction de l'heure de prise de vue (`DATE-OBS`, lue dans les mesures de `quality` ou dans l'en-tête FITS), soit, si la date manque ou si `time: index` est demandé, en fonction du rang de la pose.\n3. **Transformations « comète ».** Chaque transformation d'alignement sur les étoiles est composée d'une translation qui ramène le noyau à sa position de la première image. Les poses sont ensuite relues et empilées avec le moteur d'empilement du cœur (streaming, sans image intermédiaire sur disque).\n4. **Rejet des étoiles filées.** Dans ce second stack, ce sont les étoiles qui bougent : en `sigma_clip`, le rejet haut (`kappa_high`, plus sévère que le rejet bas par défaut) les élimine pixel par pixel, ce qui laisse une comète propre sur un fond sans étoiles (ou presque).\n5. **Fusion.** Avec `merge: mask`, la comète est incrustée dans l'empilement étoiles courant à l'aide d'un masque circulaire doux centré sur le noyau : opacité 1 jusqu'à `radius`, puis raccord en cosinus jusqu'à 1,5 × `radius`. Les pixels non définis du stack comète (NaN) sont remplacés par ceux du stack étoiles. Avec `merge: none`, le stack comète est seulement enregistré.\n\n## Utilité / quand l'utiliser\n\n- **Comète brillante photographiée sur une longue série** (Vespera, Seestar, lunette + caméra couleur) : dès que le noyau se déplace de plus d'un ou deux pixels pendant la séance, l'empilement étoiles rend la coma floue. `comet_stack` redonne un noyau net sans sacrifier les étoiles.\n- **Comète rapide près de la Terre** : le déplacement peut atteindre plusieurs dizaines de pixels par heure ; l'interpolation temporelle suit correctement le mouvement même si des poses ont été rejetées ou si la cadence n'était pas régulière.\n- **Export séparé** (`merge: none`) : pour composer vous-même comète et étoiles dans un autre logiciel, ou pour étudier la queue.\n\nÀ ne **pas** utiliser :\n\n- pour un objet du ciel profond fixe (aucun intérêt, le temps d'empilement double) ;\n- quand la comète ne bouge quasiment pas pendant la séance (quelques minutes de pose totale) : l'empilement étoiles suffit ;\n- quand la trajectoire est fortement courbe ou accélérée pendant la séance (le modèle est linéaire) : scinder alors la série.\n\n## Installation\n\n```bash\nastrostack plugin install comet\n```\n\nOu depuis l'application : vue **Plugins**, fiche « Empilement comète », bouton **Installer**.\n\nAucune dépendance Python supplémentaire : le plugin utilise NumPy, Astropy et le moteur d'empilement du cœur astrostack.\n\n## Paramètres\n\n### `comet_stack`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `start` | 2 nombres `[x, y]` | aucun (obligatoire) | Position (x, y) du noyau sur la 1re image acceptée, en pixels. |\n| `end` | 2 nombres `[x, y]` | aucun (obligatoire) | Position (x, y) du noyau sur la dernière image acceptée, en pixels. |\n| `time` | choix : `auto`, `index` | `auto` | Interpolation du mouvement : `auto` utilise `DATE-OBS` (sinon l'index de la pose), `index` force l'interpolation par rang. |\n| `method` | choix : `sigma_clip`, `mean` | `sigma_clip` | Méthode d'empilement du stack comète ; `sigma_clip` rejette les étoiles filées. |\n| `kappa_low` | réel (1 à 6) | `3.0` | Seuil de rejet bas, en σ. |\n| `kappa_high` | réel (1 à 6) | `2.0` | Seuil de rejet haut, en σ : c'est lui qui élimine les étoiles filées. |\n| `iterations` | entier (1 à 5) | `2` | Nombre de passes de rejet sigma (ignoré avec `mean`). |\n| `weighted` | booléen | `true` | Pondère chaque pose par son poids de qualité (étape `quality`). |\n| `merge` | choix : `mask`, `none` | `mask` | `mask` : comète incrustée dans le stack étoiles ; `none` : export du stack comète seul. |\n| `radius` | réel (5 à 2000) | `80.0` | Rayon (px) de la zone comète incrustée (coma et début de queue) ; le raccord s'étend jusqu'à 1,5 × `radius`. |\n\nL'étape n'a pas de paramètre `mask` : la zone d'incrustation est définie par `radius` autour du noyau.\n\nPour trouver `start` et `end`, ouvrez la première et la dernière pose acceptées dans la vue **Images** (ou **Qualité**, clic sur la pose) et relevez les coordonnées du noyau au survol.\n\n## Exemples YAML\n\nPlacement conseillé : **juste après `stack`**, avant `drizzle`, `crop` et tout post-traitement (le stack étoiles et le stack comète doivent avoir la même taille).\n\n```yaml\npipeline:\n  - masters: {}\n  - quality: {min_stars: 15}\n  - register: {}\n  - stack: {method: sigma_clip, kappa_low: 3.0, kappa_high: 2.5}\n  - comet_stack: {start: [1812.4, 1540.0], end: [1768.9, 1602.3]}\n  - crop: {min_coverage: 0.9}\n  - background: {}\n  - stretch: {method: auto}\n```\n\nComète étendue avec une grande coma, rejet plus fort des étoiles filées :\n\n```yaml\npipeline:\n  - stack: {method: sigma_clip}\n  - comet_stack:\n      start: [1204, 988]\n      end: [1310, 1021]\n      kappa_high: 1.8\n      iterations: 3\n      radius: 250\n```\n\nStack comète seul (séries sans horodatage fiable, composition faite ailleurs) :\n\n```yaml\npipeline:\n  - stack: {}\n  - comet_stack: {start: [900, 700], end: [940, 690], time: index, merge: none}\n```\n\n## Sorties\n\n- `.work/comet.npy` : l'empilement aligné sur le noyau (tableau float32 `(C, H, W)`), dans le dossier de travail du projet (ou du groupe).\n- `ctx.state[\"comet_stack\"]` : `{\"path\": …, \"nucleus\": [x, y], \"radius\": …, \"interpolation\": \"temps\" | \"index\"}` — `nucleus` est la position du noyau dans le repère de référence, `interpolation` indique le mode réellement utilisé.\n- Avec `merge: mask`, l'image courante (`ctx.image`) est remplacée par la fusion étoiles + comète, puis sauvegardée comme **checkpoint** (l'étape est marquée `checkpoint = True`), ce qui permet de rejouer le post-traitement avec `--from`.\n- L'étape est exclue de l'aperçu interactif de l'Atelier (`preview = False`) : elle relit les poses brutes.\n\n## Limites\n\n- Le mouvement est supposé **linéaire** entre la première et la dernière pose (vitesse constante en pixels du repère de référence).\n- La précision dépend de la saisie manuelle de `start` et `end` : une erreur de quelques pixels floute le noyau d'autant.\n- Les transformations d'alignement doivent exister (étape `register` exécutée) ; sans elles, l'identité est utilisée.\n- La fusion est ignorée (avec un avertissement) si le stack étoiles est absent ou n'a pas la même taille que le stack comète : placer `comet_stack` juste après `stack`, et pas après `drizzle` ou `crop`.\n- La queue longue et faible n'est incrustée que dans le rayon choisi ; au-delà, elle provient du stack étoiles (légèrement étalée).\n- Le temps de calcul est comparable à celui d'un second empilement.\n\n## Licences\n\n- Plugin : licence MIT, © Erwan Sturzenegger.\n- Dépendances (fournies par le cœur astrostack) : NumPy (BSD-3-Clause), Astropy (BSD-3-Clause).\n","en":"# Comet stacking\n\nA second stack of the frames aligned on the comet nucleus (motion interpolated in time), blended into the star-aligned stack to get a sharp comet over a field of pinpoint stars.\n\n## What it does\n\nThe plugin provides one global stage, `comet_stack`.\n\nA comet moves relative to the stars during the session: a regular star-aligned stack smears the nucleus and coma into a blurred streak. `comet_stack` performs a **second stack** in which the nucleus stays fixed:\n\n1. **Nucleus position.** You give the (x, y) position of the nucleus on the first accepted frame (`start`) and on the last one (`end`), in pixels of those frames. Both points are mapped into the reference frame using the transforms computed by `register`.\n2. **Motion interpolation.** The nucleus position on every intermediate frame is linearly interpolated between these two points, either by capture time (`DATE-OBS`, read from the `quality` measurements or from the FITS header) or, if the date is missing or `time: index` is requested, by frame rank.\n3. **\"Comet\" transforms.** Each star-alignment transform is combined with a translation that brings the nucleus back to its position on the first frame. The frames are then re-read and stacked by the core stacking engine (streaming, no intermediate image on disk).\n4. **Rejection of trailed stars.** In this second stack the stars are the ones moving: with `sigma_clip`, the high rejection (`kappa_high`, stricter than the low rejection by default) removes them pixel by pixel, leaving a clean comet on a (nearly) starless background.\n5. **Blending.** With `merge: mask`, the comet is inserted into the current star stack through a soft circular mask centred on the nucleus: full opacity up to `radius`, then a cosine transition up to 1.5 × `radius`. Undefined pixels of the comet stack (NaN) are taken from the star stack. With `merge: none`, the comet stack is only saved.\n\n## When to use it\n\n- **A bright comet shot over a long series** (Vespera, Seestar, refractor + colour camera): as soon as the nucleus moves by more than a pixel or two during the session, the star stack blurs the coma. `comet_stack` restores a sharp nucleus without sacrificing the stars.\n- **A fast comet close to Earth**: the motion can reach tens of pixels per hour; time-based interpolation follows it correctly even if some frames were rejected or the cadence was irregular.\n- **Separate export** (`merge: none`): to combine comet and stars yourself in another program, or to study the tail.\n\nDo **not** use it:\n\n- for a fixed deep-sky object (no benefit, stacking time doubles);\n- when the comet barely moves during the session (a few minutes of total exposure): the star stack is enough;\n- when the path is strongly curved or accelerating during the session (the model is linear): split the series instead.\n\n## Installation\n\n```bash\nastrostack plugin install comet\n```\n\nOr from the application: **Plugins** view, \"Comet stacking\" page, **Install** button.\n\nNo additional Python dependency: the plugin uses NumPy, Astropy and the stacking engine of the astrostack core.\n\n## Parameters\n\n### `comet_stack`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `start` | 2 numbers `[x, y]` | none (required) | Nucleus (x, y) position on the first accepted frame, in pixels. |\n| `end` | 2 numbers `[x, y]` | none (required) | Nucleus (x, y) position on the last accepted frame, in pixels. |\n| `time` | choice: `auto`, `index` | `auto` | Motion interpolation: `auto` uses `DATE-OBS` (falling back to the frame index), `index` forces interpolation by rank. |\n| `method` | choice: `sigma_clip`, `mean` | `sigma_clip` | Stacking method for the comet stack; `sigma_clip` rejects trailed stars. |\n| `kappa_low` | float (1 to 6) | `3.0` | Low rejection threshold, in σ. |\n| `kappa_high` | float (1 to 6) | `2.0` | High rejection threshold, in σ: this is what removes the trailed stars. |\n| `iterations` | integer (1 to 5) | `2` | Number of sigma-rejection passes (ignored with `mean`). |\n| `weighted` | boolean | `true` | Weight each frame by its quality weight (`quality` stage). |\n| `merge` | choice: `mask`, `none` | `mask` | `mask`: comet blended into the star stack; `none`: comet stack exported on its own. |\n| `radius` | float (5 to 2000) | `80.0` | Radius (px) of the inserted comet area (coma and start of the tail); the transition extends to 1.5 × `radius`. |\n\nThe stage has no `mask` parameter: the blended area is defined by `radius` around the nucleus.\n\nTo find `start` and `end`, open the first and last accepted frames in the **Images** view (or **Quality**, click on the frame) and read the nucleus coordinates under the cursor.\n\n## YAML examples\n\nRecommended position: **right after `stack`**, before `drizzle`, `crop` and any post-processing (the star stack and the comet stack must have the same size).\n\n```yaml\npipeline:\n  - masters: {}\n  - quality: {min_stars: 15}\n  - register: {}\n  - stack: {method: sigma_clip, kappa_low: 3.0, kappa_high: 2.5}\n  - comet_stack: {start: [1812.4, 1540.0], end: [1768.9, 1602.3]}\n  - crop: {min_coverage: 0.9}\n  - background: {}\n  - stretch: {method: auto}\n```\n\nExtended comet with a large coma, stronger rejection of trailed stars:\n\n```yaml\npipeline:\n  - stack: {method: sigma_clip}\n  - comet_stack:\n      start: [1204, 988]\n      end: [1310, 1021]\n      kappa_high: 1.8\n      iterations: 3\n      radius: 250\n```\n\nComet stack only (series without reliable timestamps, compositing done elsewhere):\n\n```yaml\npipeline:\n  - stack: {}\n  - comet_stack: {start: [900, 700], end: [940, 690], time: index, merge: none}\n```\n\n## Outputs\n\n- `.work/comet.npy`: the nucleus-aligned stack (float32 array `(C, H, W)`), in the working folder of the project (or group).\n- `ctx.state[\"comet_stack\"]`: `{\"path\": …, \"nucleus\": [x, y], \"radius\": …, \"interpolation\": \"temps\" | \"index\"}` — `nucleus` is the nucleus position in the reference frame, `interpolation` tells which mode was actually used (`temps` means time-based).\n- With `merge: mask`, the current image (`ctx.image`) is replaced by the stars + comet blend and saved as a **checkpoint** (the stage has `checkpoint = True`), so post-processing can be replayed with `--from`.\n- The stage is excluded from the Workshop's interactive preview (`preview = False`): it re-reads the raw frames.\n\n## Limitations\n\n- Motion is assumed to be **linear** between the first and the last frame (constant velocity in reference-frame pixels).\n- Accuracy depends on the manual entry of `start` and `end`: an error of a few pixels blurs the nucleus by as much.\n- Alignment transforms must exist (`register` has run); without them, the identity is used.\n- Blending is skipped (with a warning) if the star stack is missing or does not have the same size as the comet stack: place `comet_stack` right after `stack`, not after `drizzle` or `crop`.\n- A long, faint tail is only inserted within the chosen radius; beyond it, it comes from the star stack (slightly smeared).\n- Computing time is similar to that of a second stack.\n\n## Licences\n\n- Plugin: MIT licence, © Erwan Sturzenegger.\n- Dependencies (provided by the astrostack core): NumPy (BSD-3-Clause), Astropy (BSD-3-Clause).\n"}},{"id":"deconvolution","version":"1.0.0","name":{"fr":"Déconvolution","en":"Deconvolution"},"summary":{"fr":"Richardson-Lucy régularisé avec PSF mesurée sur les étoiles (ou gaussienne/Moffat) : étoiles plus fines, détails plus nets.","en":"Regularised Richardson-Lucy with a PSF measured on the stars (or Gaussian/Moffat): tighter stars, crisper detail."},"category":"post","tags":["deconvolution","richardson-lucy","psf","sharpening"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/deconvolution","min_astrostack":"0.1.0","entry":"celestiax_deconvolution","python_deps":[],"stages":["deconv"],"frame_ops":[],"ai":false,"models":[],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale (extraite du cœur d'astrostack)","en":"Initial release (extracted from the astrostack core)"}},"download":"https://celestiax-plugins.sturzy.ch/dl/deconvolution-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/deconvolution-1.0.0.zip","size":12665,"sha256":"813485586b0b6493fd17639ea34e95166e174fed74c3d9a79534c167ade1a0a1","readme":{"fr":"# Déconvolution\n\nDéconvolution Richardson-Lucy régularisée avec une PSF mesurée sur les étoiles de l'image (ou gaussienne / Moffat) : étoiles plus fines, détails plus nets, sans anneaux autour des étoiles brillantes.\n\n## Fonction\n\nLe plugin fournit une étape : `deconv`.\n\nLa turbulence, la mise au point et l'optique étalent chaque point lumineux selon une **PSF** (fonction d'étalement du point). La déconvolution cherche l'image « avant étalement » qui, reconvoluée par cette PSF, redonne l'image observée.\n\n1. **PSF.**\n   - `measured` (défaut) : astrostack détecte les étoiles (SEP, seuil 8 σ), garde jusqu'à 60 étoiles isolées et non saturées (pic < 80 % du maximum), découpe une vignette autour de chacune (taille ≈ 3 × FWHM, entre 7 et 41 px), la recentre au sous-pixel, la normalise, puis prend la **médiane** des vignettes. Si moins de 3 étoiles conviennent, une PSF gaussienne de même FWHM est utilisée.\n   - `gaussian` ou `moffat` : PSF analytique de FWHM `fwhm` (mesurée sur les étoiles si le champ est vide) ; `beta` règle les ailes de la Moffat.\n2. **Richardson-Lucy.** Algorithme itératif : à chaque itération, l'estimation est convoluée par la PSF, comparée à l'image observée (rapport), et corrigée par ce rapport reconvolué. Les convolutions sont faites par FFT, bords prolongés en miroir. L'image est décalée pour être strictement positive, comme l'exige l'algorithme.\n3. **Régularisation** (limite l'amplification du bruit) :\n   - `tv` : variation totale (Dey et al. 2006), pondérée par `tv_lambda` ; lisse les zones plates en préservant les bords ;\n   - `damped` : RL amorti (White 1994) : les écarts inférieurs à `damping` × bruit ne sont plus amplifiés ;\n   - `none` : Richardson-Lucy pur.\n4. **Luminance puis recolorisation** (`luminance_only`, défaut) : seule la luminance est déconvoluée ; le rapport nouvelle / ancienne luminance (borné entre 0 et 20) est appliqué aux trois canaux, ce qui conserve les couleurs et évite les franges colorées.\n5. **Protection des étoiles brillantes** : un masque d'étoiles (pic > `protect_threshold` × maximum), adouci sur une FWHM, conserve l'original autour de ces étoiles pour éviter les anneaux sombres (effet de Gibbs).\n6. **Dosage** : `amount` mélange le résultat avec l'original.\n\nLes très grandes images (plus de 4096 × 4096 px) sont traitées par tuiles de 2048 px avec recouvrement, pour limiter la mémoire. Dans l'aperçu réduit de l'application, `fwhm` est automatiquement mise à l'échelle.\n\n## Utilité / quand l'utiliser\n\n- **Étoiles empâtées** par la turbulence ou une mise au point imparfaite, sur une lunette ou un télescope intelligent (Vespera, Seestar : petites optiques, échantillonnage large).\n- **Galaxies et nébuleuses à structures fines** (bras spiraux, filaments) : les détails de quelques pixels gagnent en contraste.\n- **Empilements à bon rapport signal/bruit** : la déconvolution a besoin de signal ; plus il y a de poses, plus on peut pousser les itérations.\n\nQuand **ne pas** l'utiliser :\n\n- sur une image très bruitée (peu de poses, ciel très pollué) : le bruit est amplifié avant les détails ;\n- sur une image étirée : Richardson-Lucy suppose des données **linéaires** (le flou est une convolution de la lumière reçue, pas de sa version étirée) ;\n- sur un champ sans étoiles mesurables sans renseigner `fwhm` (l'étape est alors ignorée) ;\n- sur un champ où les étoiles sont allongées ou déformées de façon variable (coma, tilt, suivi) : la PSF unique ne décrit pas ces variations.\n\n**Ordre conseillé** : sur l'image **linéaire**, après `crop` et `background`/`gradient`, avant `denoise` et avant `stretch`.\n\n## Installation\n\n```bash\nastrostack plugin install deconvolution\n```\n\nou depuis la vue **Plugins** de l'application CelestiaX, puis ajoutez l'étape « Déconvolution » (groupe Détails) à la recette.\n\nDépendances Python : aucune en plus du cœur (`python_deps` vide). Le plugin utilise NumPy, SciPy (FFT, décalage sous-pixel) et la détection d'étoiles d'astrostack (SEP), déjà installés.\n\n## Paramètres\n\n### Étape `deconv`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `psf` | choice | `measured` | PSF : `measured` (mesurée sur les étoiles), `gaussian` ou `moffat`. |\n| `fwhm` | float | vide | FWHM (px) des PSF analytiques, de 0,5 à 20 ; vide = mesurée sur les étoiles (facultatif). |\n| `beta` | float | `3.0` | Moffat : paramètre bêta (1,2 à 10) ; plus petit = ailes plus étendues. |\n| `iterations` | int | `20` | Nombre d'itérations (1 à 200). |\n| `regularization` | choice | `tv` | Régularisation : `tv`, `damped` ou `none`. |\n| `tv_lambda` | float | `0.002` | Poids de la variation totale (0 à 0,05). |\n| `damping` | float | `3.0` | RL amorti : seuil en σ du bruit (0 à 20). |\n| `luminance_only` | bool | `true` | Déconvoluer la luminance puis recoloriser. |\n| `protect_stars` | bool | `true` | Garder l'original autour des étoiles brillantes (anti-anneaux). |\n| `protect_threshold` | float | `0.3` | Étoiles protégées : pic > seuil × maximum (0 à 1). |\n| `amount` | float | `1.0` | Mélange avec l'original (0 = original, 1 = déconvolué). |\n| `mask` | text | vide | Masque de post-traitement facultatif (voir ci-dessous). |\n\n**Le paramètre `mask`.** Limite l'effet à une zone : le masque est calculé sur l'image avant l'étape, puis résultat = avant × (1 − m) + après × m. Forme courte : `mask: \"object feather=8\"` (déconvoluer seulement la galaxie ou la nébuleuse), `mask: \"stars invert\"` (tout sauf les étoiles) ; forme dictionnaire : `mask: {type: luminance, low: 0.1, high: 0.4}`. Types : `luminance`, `color`, `stars`, `object`, `range`, `file`, `combine` ; options communes `invert`, `blur` (σ en px), `strength` (0–1). Un masque `object` est souvent le meilleur moyen d'épargner le fond de ciel bruité.\n\n## Exemples YAML\n\nRéglage par défaut, PSF mesurée :\n\n```yaml\npipeline:\n  - crop: {}\n  - background: {grid: 24, degree: 2, kappa: 2.0}\n  - deconv: {iterations: 20, regularization: tv, tv_lambda: 0.002}\n  - denoise: {method: wavelets}\n  - stretch: {method: auto}\n```\n\nGalaxie seulement, RL amorti, effet dosé :\n\n```yaml\npipeline:\n  - gradient: {}\n  - deconv:\n      iterations: 40\n      regularization: damped\n      damping: 3\n      amount: 0.7\n      mask: {type: object, feather: 8}\n  - stretch: {method: ghs}\n```\n\nChamp pauvre en étoiles, PSF Moffat imposée :\n\n```yaml\npipeline:\n  - crop: {}\n  - deconv: {psf: moffat, fwhm: 3.2, beta: 3.0, iterations: 15}\n```\n\n## Sorties\n\n- L'image courante est remplacée par l'image déconvoluée (float32) ; les pixels hors champ (NaN) sont conservés.\n- Aucun fichier écrit.\n- Message console : nombre d'itérations, régularisation, type, taille et FWHM de la PSF. Avertissement si la PSF n'a pas pu être mesurée (repli gaussien) ou si aucune étoile n'est trouvée (étape ignorée).\n\n## Limites\n\n- PSF **unique** pour tout le champ : les étoiles déformées dans les coins (coma, tilt) ne sont pas corrigées et peuvent se dégrader. Vérifiez avec `psf_map` (plugin « analysis ») et recadrez si besoin.\n- Trop d'itérations ou `tv_lambda` trop faible : bruit granuleux, anneaux autour des étoiles moyennes, fond « peau d'orange ». Augmentez progressivement.\n- Les étoiles saturées ne sont pas déconvoluées correctement ; `protect_stars` les laisse intactes.\n- Temps de calcul proportionnel au nombre d'itérations (deux convolutions par FFT à chaque itération).\n\n## Licences\n\n- Plugin : licence **MIT**, © Erwan Sturzenegger.\n- Dépendances (installées avec astrostack) : NumPy et SciPy (BSD), OpenCV (Apache 2.0), SEP (LGPL v3 pour le code dérivé de SExtractor, BSD/MIT pour le reste).\n- Références : W. H. Richardson (1972), L. B. Lucy (1974) ; N. Dey et al. (2006) pour la régularisation TV ; R. L. White (1994) pour le RL amorti.\n","en":"# Deconvolution\n\nRegularised Richardson-Lucy deconvolution with a PSF measured on the image's stars (or Gaussian / Moffat): tighter stars, crisper detail, without rings around bright stars.\n\n## What it does\n\nThe plugin provides one stage: `deconv`.\n\nSeeing, focus and optics spread every point of light according to a **PSF** (point spread function). Deconvolution looks for the \"unblurred\" image which, convolved again with that PSF, gives back the observed image.\n\n1. **PSF.**\n   - `measured` (default): astrostack detects stars (SEP, 8 σ threshold), keeps up to 60 isolated, unsaturated stars (peak < 80 % of the maximum), cuts a stamp around each one (size ≈ 3 × FWHM, between 7 and 41 px), re-centres it at sub-pixel precision, normalises it, then takes the **median** of the stamps. If fewer than 3 stars qualify, a Gaussian PSF with the same FWHM is used.\n   - `gaussian` or `moffat`: analytic PSF with FWHM `fwhm` (measured on the stars if left empty); `beta` sets the Moffat wings.\n2. **Richardson-Lucy.** Iterative algorithm: at each iteration the estimate is convolved with the PSF, compared with the observed image (ratio), and corrected by that ratio convolved back. Convolutions are done by FFT, with mirrored edges. The image is offset to be strictly positive, as the algorithm requires.\n3. **Regularisation** (limits noise amplification):\n   - `tv`: total variation (Dey et al. 2006), weighted by `tv_lambda`; smooths flat areas while keeping edges;\n   - `damped`: damped RL (White 1994): deviations below `damping` × noise are no longer amplified;\n   - `none`: plain Richardson-Lucy.\n4. **Luminance then recolouring** (`luminance_only`, default): only the luminance is deconvolved; the new / old luminance ratio (bounded between 0 and 20) is applied to all three channels, which keeps colours and avoids coloured fringes.\n5. **Bright star protection**: a star mask (peak > `protect_threshold` × maximum), feathered over one FWHM, keeps the original around those stars to avoid dark rings (Gibbs effect).\n6. **Blending**: `amount` mixes the result with the original.\n\nVery large images (over 4096 × 4096 px) are processed in overlapping 2048 px tiles to limit memory use. In the application's reduced preview, `fwhm` is scaled automatically.\n\n## When to use it\n\n- **Bloated stars** caused by seeing or imperfect focus, on a refractor or a smart telescope (Vespera, Seestar: small optics, coarse sampling).\n- **Galaxies and nebulae with fine structure** (spiral arms, filaments): details a few pixels wide gain contrast.\n- **Stacks with a good signal-to-noise ratio**: deconvolution needs signal; the more subframes, the more iterations you can afford.\n\nWhen **not** to use it:\n\n- on a very noisy image (few subframes, heavily light-polluted sky): noise is amplified before detail;\n- on a stretched image: Richardson-Lucy assumes **linear** data (blur is a convolution of the received light, not of its stretched version);\n- on a field without measurable stars unless you set `fwhm` (the stage is otherwise skipped);\n- on a field where stars are elongated or distorted in a variable way (coma, tilt, tracking): a single PSF cannot describe those variations.\n\n**Recommended order**: on the **linear** image, after `crop` and `background`/`gradient`, before `denoise` and before `stretch`.\n\n## Installation\n\n```bash\nastrostack plugin install deconvolution\n```\n\nor from the **Plugins** view of the CelestiaX application, then add the \"Deconvolution\" step (Details group) to the recipe.\n\nPython dependencies: none beyond the core (`python_deps` is empty). The plugin uses NumPy, SciPy (FFT, sub-pixel shift) and astrostack's star detection (SEP), all already installed.\n\n## Parameters\n\n### Stage `deconv`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `psf` | choice | `measured` | PSF: `measured` (on the stars), `gaussian` or `moffat`. |\n| `fwhm` | float | empty | FWHM (px) of the analytic PSFs, 0.5 to 20; empty = measured on the stars (optional). |\n| `beta` | float | `3.0` | Moffat: beta parameter (1.2 to 10); lower = wider wings. |\n| `iterations` | int | `20` | Number of iterations (1 to 200). |\n| `regularization` | choice | `tv` | Regularisation: `tv`, `damped` or `none`. |\n| `tv_lambda` | float | `0.002` | Total variation weight (0 to 0.05). |\n| `damping` | float | `3.0` | Damped RL: threshold in noise σ (0 to 20). |\n| `luminance_only` | bool | `true` | Deconvolve the luminance, then recolour. |\n| `protect_stars` | bool | `true` | Keep the original around bright stars (anti-ringing). |\n| `protect_threshold` | float | `0.3` | Protected stars: peak > threshold × maximum (0 to 1). |\n| `amount` | float | `1.0` | Blend with the original (0 = original, 1 = deconvolved). |\n| `mask` | text | empty | Optional post-processing mask (see below). |\n\n**The `mask` parameter.** Restricts the effect to an area: the mask is computed on the image before the stage, then result = before × (1 − m) + after × m. Short form: `mask: \"object feather=8\"` (deconvolve only the galaxy or nebula), `mask: \"stars invert\"` (everything except stars); dictionary form: `mask: {type: luminance, low: 0.1, high: 0.4}`. Types: `luminance`, `color`, `stars`, `object`, `range`, `file`, `combine`; common options `invert`, `blur` (σ in px), `strength` (0–1). An `object` mask is often the best way to spare the noisy sky background.\n\n## YAML examples\n\nDefault settings, measured PSF:\n\n```yaml\npipeline:\n  - crop: {}\n  - background: {grid: 24, degree: 2, kappa: 2.0}\n  - deconv: {iterations: 20, regularization: tv, tv_lambda: 0.002}\n  - denoise: {method: wavelets}\n  - stretch: {method: auto}\n```\n\nGalaxy only, damped RL, reduced effect:\n\n```yaml\npipeline:\n  - gradient: {}\n  - deconv:\n      iterations: 40\n      regularization: damped\n      damping: 3\n      amount: 0.7\n      mask: {type: object, feather: 8}\n  - stretch: {method: ghs}\n```\n\nStar-poor field, fixed Moffat PSF:\n\n```yaml\npipeline:\n  - crop: {}\n  - deconv: {psf: moffat, fwhm: 3.2, beta: 3.0, iterations: 15}\n```\n\n## Outputs\n\n- The current image is replaced by the deconvolved image (float32); out-of-field pixels (NaN) are kept.\n- No file is written.\n- Console message: number of iterations, regularisation, PSF type, size and FWHM. A warning is shown if the PSF could not be measured (Gaussian fallback) or if no star is found (stage skipped).\n\n## Limitations\n\n- A **single** PSF for the whole field: distorted stars in the corners (coma, tilt) are not corrected and may get worse. Check with `psf_map` (plugin \"analysis\") and crop if needed.\n- Too many iterations or too low a `tv_lambda`: grainy noise, rings around medium stars, \"orange peel\" background. Increase gradually.\n- Saturated stars cannot be deconvolved correctly; `protect_stars` leaves them untouched.\n- Computing time grows with the number of iterations (two FFT convolutions per iteration).\n\n## Licences\n\n- Plugin: **MIT** licence, © Erwan Sturzenegger.\n- Dependencies (installed with astrostack): NumPy and SciPy (BSD), OpenCV (Apache 2.0), SEP (LGPL v3 for code derived from SExtractor, BSD/MIT for the rest).\n- References: W. H. Richardson (1972), L. B. Lucy (1974); N. Dey et al. (2006) for TV regularisation; R. L. White (1994) for damped RL.\n"}},{"id":"deepcr","version":"1.0.0","name":{"fr":"deepCR (rayons cosmiques IA)","en":"deepCR (AI cosmic rays)"},"summary":{"fr":"Détection et effacement des rayons cosmiques pose par pose par le réseau deepCR (PyTorch), avant le dématriçage, plan CFA par plan CFA.","en":"Per-frame cosmic ray detection and removal with the deepCR network (PyTorch), before demosaicing, one CFA plane at a time."},"category":"ai","tags":["ai","cosmic-rays","calibration","deepcr","pytorch"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/deepcr","min_astrostack":"0.1.0","entry":"celestiax_deepcr","python_deps":["deepCR>=0.3.1","torch>=2.0"],"stages":[],"frame_ops":["cosmic_rays"],"ai":true,"models":[],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale : frame_op cosmic_rays (modèles decam, ACS-WFC, WFC3-UVIS fournis par le paquet deepCR).","en":"Initial release: cosmic_rays frame_op (decam, ACS-WFC, WFC3-UVIS models shipped with the deepCR package)."}},"download":"https://celestiax-plugins.sturzy.ch/dl/deepcr-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/deepcr-1.0.0.zip","size":7928,"sha256":"4835b7f6da88c7ead33a8d9c1a358feaede6253e267614f68c68d6384de3ae4d","readme":{"fr":"# deepCR — rayons cosmiques par IA\n\nLe traitement pose par pose (`frame_op`) `cosmic_rays` détecte et efface les impacts de rayons cosmiques avec **deepCR** (Zhang & Bloom 2020, *deepCR: Cosmic Ray Rejection with Deep Learning*, ApJ 889, 24), un réseau U-Net qui prédit, pixel par pixel, la probabilité d'un impact. Les pixels retenus sont remplacés par la médiane de leurs voisins sains (ou par le réseau d'inpainting ACS-WFC).\n\n## Quand l'utiliser\n\n- Poses longues (plusieurs minutes) de capteurs mono, CCD en particulier, où les impacts sont fréquents et nets.\n- Peu de poses à empiler (moins de ~10) : le rejet sigma de l'empilement ne suffit plus à éliminer les impacts.\n- Poses destinées à être utilisées seules (une pose unique de comète, de transitoire…).\n\nAvec de nombreuses poses et un rejet sigma/winsorisé, l'empilement élimine déjà les rayons cosmiques : l'étape est alors inutile et coûteuse.\n\n## Où la placer\n\nDans `frame_ops`, **après `calibrate` et avant `debayer`** :\n\n- pose **mono** : l'image entière est traitée ;\n- pose **CFA** (Bayer, non dématricée) : chacun des 4 plans de couleur (demi-résolution) est traité séparément, pour que la mosaïque de couleurs ne soit pas prise pour des impacts ;\n- pose déjà **RGB** : chaque canal est traité à part (possible, mais le dématriçage a déjà étalé les impacts sur 2–3 pixels : moins efficace).\n\n## Modèles\n\nLes poids sont **fournis par le paquet pip `deepCR`** (aucun téléchargement séparé, `models: []`) :\n\n| `model` | Entraîné sur | Usage |\n|---|---|---|\n| `decam` (défaut) | DECam, caméra grand champ au sol (Blanco 4 m) | le plus proche des poses d'amateurs |\n| `ACS-WFC` | Hubble ACS/WFC (F435W, F606W, F814W) | images spatiales |\n| `WFC3-UVIS` | Hubble WFC3/UVIS | images spatiales |\n\ndeepCR attend des **ADU** : `adu_scale` (65535 par défaut) convertit les pixels normalisés [0, 1] d'astrostack. Pour un capteur 12 ou 14 bits dont les valeurs n'ont pas été étendues à 16 bits, indiquez 4095 ou 16383.\n\n## Dépendances et licence\n\n- `pip install deepCR torch` (bouton « Dépendances » de la vue Plugins ou `astrostack plugin install deepcr --deps`). PyTorch est lourd (plusieurs centaines de Mo) : il n'est jamais installé automatiquement, et n'est importé qu'au lancement de l'étape.\n- deepCR : licence **BSD-3-Clause** (code et poids fournis), © Keming Zhang, Joshua Bloom.\n\n## Paramètres\n\n| Paramètre | Défaut | Rôle |\n|---|---|---|\n| `model` | `decam` | réseau de détection |\n| `threshold` | 0,5 | seuil de probabilité (plus bas = plus de détections, plus de fausses alertes) |\n| `inpaint` | `median` | `median` (médiane 5×5 des voisins sains) ou `ACS-WFC-F606W-2-32` (réseau d'inpainting, pour les images Hubble) |\n| `adu_scale` | 65535 | pixels normalisés → ADU |\n| `patch` | 256 | taille des morceaux passés au réseau |\n| `save_masks` | non | enregistre le masque de chaque pose (`.work/ai_cosmic_rays/<pose>.npy`, bits compactés) |\n\n## Exemple\n\n```yaml\nframe_ops:\n  - calibrate: {}\n  - cosmic_rays: {model: decam, threshold: 0.5}\n  - debayer: {method: rcd}\n```\n\n## Contrôle\n\nLe masque de la première pose traitée par chaque processus est écrit dans `.work/ai_cosmic_rays_diff.npy` (1 = pixel remplacé). Si des cœurs d'étoiles y apparaissent, montez `threshold`.\n\n## Temps de calcul\n\nNon mesuré dans ce dépôt (PyTorch n'est pas installé sur la machine de test ; seuls les tests sans PyTorch\nsont exécutés). Le réseau tourne sur le CPU, pose par pose, dans les processus de chargement en parallèle :\ncomptez plusieurs secondes par pose de 20 Mpx et vérifiez sur une pose avant de lancer tout un lot.\n\n## Limites\n\n- Réseaux entraînés sur des données professionnelles (DECam, Hubble) : sur des poses d'amateurs sous-échantillonnées (étoiles de 1–2 px), des étoiles peuvent être prises pour des impacts — vérifiez le masque de contrôle et ajustez `threshold`.\n- Sur les plans CFA, la résolution est divisée par 2 : les impacts très fins sont mieux détectés, mais les petites étoiles ressemblent davantage à des impacts.\n- Pas d'accélération GPU sur Mac (deepCR n'utilise que CUDA) : calcul sur CPU.\n- Aucun bénéfice quand l'empilement comporte assez de poses pour un rejet statistique.\n","en":"# deepCR — AI cosmic ray removal\n\nThe per-frame operation (`frame_op`) `cosmic_rays` detects and erases cosmic ray hits with **deepCR** (Zhang & Bloom 2020, *deepCR: Cosmic Ray Rejection with Deep Learning*, ApJ 889, 24), a U-Net that predicts, pixel by pixel, the probability of a hit. Flagged pixels are replaced by the median of their clean neighbours (or by the ACS-WFC inpainting network).\n\n## When to use it\n\n- Long exposures (several minutes) from mono sensors, CCDs in particular, where hits are frequent and sharp.\n- Few frames to stack (fewer than ~10): the stack's sigma rejection is no longer enough to remove hits.\n- Frames meant to be used on their own (a single comet frame, a transient…).\n\nWith many frames and sigma/winsorized rejection, stacking already removes cosmic rays: the step is then useless and costly.\n\n## Where to put it\n\nIn `frame_ops`, **after `calibrate` and before `debayer`**:\n\n- **mono** frame: the whole image is processed;\n- **CFA** frame (Bayer, not demosaiced): each of the 4 colour planes (half resolution) is processed separately, so the colour mosaic is not mistaken for hits;\n- already **RGB** frame: each channel is processed on its own (possible, but demosaicing has already spread hits over 2–3 pixels: less effective).\n\n## Models\n\nThe weights are **shipped with the `deepCR` pip package** (no separate download, `models: []`):\n\n| `model` | Trained on | Use |\n|---|---|---|\n| `decam` (default) | DECam, ground-based wide-field camera (Blanco 4 m) | closest to amateur frames |\n| `ACS-WFC` | Hubble ACS/WFC (F435W, F606W, F814W) | space images |\n| `WFC3-UVIS` | Hubble WFC3/UVIS | space images |\n\ndeepCR expects **ADU**: `adu_scale` (65535 by default) converts astrostack's normalised [0, 1] pixels. For a 12- or 14-bit sensor whose values were not expanded to 16 bits, set 4095 or 16383.\n\n## Dependencies and licence\n\n- `pip install deepCR torch` (\"Dependencies\" button in the Plugins view or `astrostack plugin install deepcr --deps`). PyTorch is heavy (several hundred MB): it is never installed automatically and is only imported when the step starts.\n- deepCR: **BSD-3-Clause** licence (code and bundled weights), © Keming Zhang, Joshua Bloom.\n\n## Parameters\n\n| Parameter | Default | Purpose |\n|---|---|---|\n| `model` | `decam` | detection network |\n| `threshold` | 0.5 | probability threshold (lower = more detections, more false alarms) |\n| `inpaint` | `median` | `median` (5×5 median of clean neighbours) or `ACS-WFC-F606W-2-32` (inpainting network, for Hubble images) |\n| `adu_scale` | 65535 | normalised pixels → ADU |\n| `patch` | 256 | size of the chunks fed to the network |\n| `save_masks` | no | saves each frame's mask (`.work/ai_cosmic_rays/<frame>.npy`, packed bits) |\n\n## Example\n\n```yaml\nframe_ops:\n  - calibrate\n  - cosmic_rays: {model: decam, threshold: 0.5}\n  - debayer: {method: rcd}\n```\n\n## Checking the result\n\nThe mask of the first frame processed by each worker is written to `.work/ai_cosmic_rays_diff.npy` (1 = replaced pixel). If star cores show up there, raise `threshold`.\n\n## Processing time\n\nNot measured in this repository (PyTorch is not installed on the test machine; only the PyTorch-free tests run). The network runs on the CPU, frame by frame, inside the parallel loading workers: expect several seconds per 20 Mpx frame and try one frame before launching a whole batch.\n\n## Limitations\n\n- Networks trained on professional data (DECam, Hubble): on undersampled amateur frames (1–2 px stars), stars may be mistaken for hits — check the control mask and adjust `threshold`.\n- On CFA planes the resolution is halved: very thin hits are better detected, but small stars look more like hits.\n- No GPU acceleration on Mac (deepCR only uses CUDA): CPU computation.\n- No benefit when the stack has enough frames for statistical rejection.\n"}},{"id":"denoise","version":"1.0.0","name":{"fr":"Débruitage","en":"Noise reduction"},"summary":{"fr":"Débruitage par ondelettes pilotées par la carte de bruit, NLM (OpenCV) ou BM3D (optionnel), masquable.","en":"Noise reduction with noise-map driven wavelets, NLM (OpenCV) or BM3D (optional), maskable."},"category":"post","tags":["denoise","wavelets","nlm","bm3d"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/denoise","min_astrostack":"0.1.0","entry":"celestiax_denoise","python_deps":[],"stages":["denoise"],"frame_ops":[],"ai":false,"models":[],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale (extraite du cœur d'astrostack)","en":"Initial release (extracted from the astrostack core)"}},"download":"https://celestiax-plugins.sturzy.ch/dl/denoise-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/denoise-1.0.0.zip","size":10890,"sha256":"de994c6056063c2dc645710cebec80311f5df4d5d0cdab87a80821c6cafe4fd9","readme":{"fr":"# Débruitage\n\nRéduit le bruit de l'image par ondelettes pilotées par la carte de bruit locale, par NLM (OpenCV) ou par BM3D (optionnel), avec une chrominance débruitée plus fort que la luminance et un masque facultatif.\n\n## Fonction\n\nLe plugin fournit une étape : `denoise`.\n\n**Séparation luminance / chrominance.** Sur une image couleur (3 canaux), l'étape calcule la luminance Y (moyenne des canaux) et deux composantes de chrominance (u = R − Y, v = B − Y). La luminance est débruitée avec la force demandée ; la chrominance l'est avec une force multipliée par `chroma_strength` (1,5 par défaut), car le bruit coloré (« confettis » rouges, verts, bleus des capteurs couleur) est plus gênant et moins porteur de détails. Les canaux R, G, B sont ensuite reconstruits. Avec `luminance_only: true`, la chrominance n'est pas touchée. Une image monochrome (ou à nombre de canaux différent) est traitée canal par canal.\n\n**Méthodes :**\n\n- `wavelets` (défaut) : transformée en ondelettes « à trous » (starlet B3), qui décompose l'image en `layers` couches de détails de plus en plus larges (1, 2, 4, 8… px) plus un résidu. Chaque couche subit un **seuillage doux** : les coefficients inférieurs à k_j × σ sont mis à zéro, les autres réduits d'autant. Le seuil vaut `k` sur la première couche puis décroît avec l'échelle (k / (1 + 0,5 j)), et tient compte de la façon dont le bruit se répartit entre les couches. Avec `noise_map: true`, σ n'est pas une valeur unique mais une **carte de bruit locale** (RMS robuste de la première couche, calculée par SEP sur des cases de 64 px, étoiles rejetées) : le fond bruité est davantage lissé que les zones de signal fort, et un empilement dont la profondeur varie dans le champ (bords, mosaïque, rotation de champ) est traité de façon homogène. `strength` dose le résultat, globalement ou couche par couche.\n- `nlm` : *Non-Local Means* d'OpenCV (`fastNlMeansDenoising`, image convertie en 16 bits, fenêtres 5 × 5 et recherche 13 × 13, norme L1). Chaque pixel est remplacé par une moyenne de pixels dont le voisinage se ressemble. La force est `h` × σ, où σ est le bruit global estimé sur la première couche d'ondelettes.\n- `bm3d` : *Block-Matching 3D*, via le paquet Python optionnel `bm3d` (σ du bruit multiplié par `h`). Souvent le meilleur rendu sur les textures fines, mais nettement plus lent.\n\n## Utilité / quand l'utiliser\n\n- **Capteurs couleur et télescopes intelligents** (Vespera, Seestar) : bruit chromatique marqué sur des temps de pose courts ; la chrominance renforcée le fait disparaître sans empâter la luminance.\n- **Ciel pollué, faible intégration** : fond granuleux après l'étirement. Débruiter avant l'étirement évite de devoir étirer le bruit.\n- **Empilements hétérogènes** (bords moins couverts, rotation de champ alt-az) : la carte de bruit adapte le seuil localement.\n- **Après une déconvolution**, pour calmer le bruit qu'elle a amplifié.\n\nQuand **ne pas** l'utiliser (ou avec modération) :\n\n- sur une image déjà très propre (longue intégration) : le risque est d'effacer des détails faibles et de donner un aspect « plastique » ;\n- en force maximale sur les étoiles et structures fines : utilisez un masque pour épargner les zones de signal.\n\n**Ordre conseillé** : de préférence sur l'image **linéaire**, après `crop`, `background`/`gradient` et `deconv`, avant `stretch`. Une passe légère après l'étirement, limitée au fond par un masque de luminance, est aussi possible.\n\n## Installation\n\n```bash\nastrostack plugin install denoise\n```\n\nou depuis la vue **Plugins** de l'application CelestiaX, puis ajoutez l'étape « Débruiter » (groupe Détails) à la recette.\n\nDépendances Python : aucune obligatoire (`python_deps` vide) ; NumPy, OpenCV et SEP sont fournis par astrostack.\n\nDépendance **optionnelle**, uniquement pour `method: bm3d` :\n\n```bash\npip install bm3d\n```\n\nSans ce paquet, les méthodes `wavelets` et `nlm` fonctionnent normalement ; `bm3d` s'arrête avec le message « denoise : method bm3d nécessite le paquet bm3d (pip install bm3d) ».\n\n## Paramètres\n\n### Étape `denoise`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `method` | choice | `wavelets` | Méthode : `wavelets`, `nlm` ou `bm3d`. |\n| `layers` | int | `4` | Ondelettes : nombre de couches (1 à 7). Plus de couches = bruit à grande échelle (taches) traité aussi. |\n| `k` | float | `3.0` | Ondelettes : seuil en σ sur la 1re couche, décroissant ensuite (0,5 à 10). |\n| `strength` | float | `1.0` | Force 0–1 ; en YAML, une liste est possible (une valeur par couche, la dernière est répétée). |\n| `h` | float | `1.0` | NLM / BM3D : force relative au bruit (0,1 à 5). |\n| `noise_map` | bool | `true` | Ondelettes : seuils adaptés au bruit local (sinon σ global). |\n| `luminance_only` | bool | `false` | Ne débruiter que la luminance (image couleur). |\n| `chroma_strength` | float | `1.5` | Multiplicateur de force pour la chrominance (0 à 4) : multiplie `k` (ondelettes) ou `h` (NLM / BM3D). |\n| `mask` | text | vide | Masque de post-traitement facultatif (voir ci-dessous). |\n\n**Le paramètre `mask`.** Limite le débruitage à une zone : le masque est calculé sur l'image avant l'étape, puis résultat = avant × (1 − m) + après × m. Exemples : `mask: {type: luminance, low: 0.1, high: 0.4, invert: true}` (débruiter surtout le fond sombre), `mask: \"stars invert\"` (épargner les étoiles), `mask: \"object invert feather=8\"` (fond de ciel uniquement). Types : `luminance`, `color`, `stars`, `object`, `range`, `file`, `combine` ; options communes `invert`, `blur` (σ en px), `strength` (0–1).\n\n## Exemples YAML\n\nRéglage standard sur l'image linéaire :\n\n```yaml\npipeline:\n  - crop: {}\n  - gradient: {}\n  - deconv: {}\n  - denoise: {method: wavelets, layers: 4, k: 3.0, chroma_strength: 1.5}\n  - color: {method: stars}\n  - stretch: {method: auto}\n```\n\nForce par couche (fin bruit très réduit, grandes échelles préservées) et fond seulement :\n\n```yaml\npipeline:\n  - denoise:\n      method: wavelets\n      layers: 5\n      strength: [1.0, 0.8, 0.5, 0.3, 0.1]\n      mask: {type: luminance, low: 0.1, high: 0.4, invert: true}\n  - stretch: {method: auto}\n```\n\nBM3D (paquet `bm3d` installé), après l'étirement, étoiles épargnées :\n\n```yaml\npipeline:\n  - stretch: {method: auto}\n  - denoise: {method: bm3d, h: 0.8, mask: \"stars invert\"}\n```\n\n## Sorties\n\n- L'image courante est remplacée par l'image débruitée (float32) ; les pixels hors champ (NaN) sont conservés.\n- Aucun fichier écrit ; message console « Débruitage <méthode> terminé ».\n\n## Limites\n\n- Tout débruitage retire aussi un peu de signal : les nébulosités les plus faibles et les petites étoiles peuvent pâlir si `k` ou `h` sont trop élevés.\n- Ondelettes : un `k` élevé avec beaucoup de couches peut laisser un fond « marbré » ; baissez `k` ou la force des couches larges.\n- NLM travaille en 16 bits sur une plage limitée par les percentiles 0,01 % – 99,99 % ; son estimation de bruit est globale (pas de carte locale).\n- BM3D est lent sur de grandes images et dépend d'un paquet externe à la licence restrictive (voir ci-dessous).\n\n## Licences\n\n- Plugin : licence **MIT**, © Erwan Sturzenegger.\n- Dépendances installées avec astrostack : NumPy et SciPy (BSD), OpenCV (Apache 2.0), SEP (LGPL v3 pour le code dérivé de SExtractor, BSD/MIT pour le reste).\n- `bm3d` (optionnel, PyPI) : distribué sous une licence propre à ses auteurs, qui à notre connaissance réserve l'usage à des fins **non commerciales** (recherche, évaluation, usage personnel). Vérifiez la licence du paquet (`pip show bm3d` et le fichier de licence fourni) avant tout usage, en particulier commercial. Le plugin ne l'embarque pas et ne l'installe jamais automatiquement.\n","en":"# Noise reduction\n\nReduces image noise with wavelets driven by the local noise map, with NLM (OpenCV) or with BM3D (optional), denoising chrominance harder than luminance, with an optional mask.\n\n## What it does\n\nThe plugin provides one stage: `denoise`.\n\n**Luminance / chrominance split.** On a colour image (3 channels), the stage computes the luminance Y (mean of the channels) and two chrominance components (u = R − Y, v = B − Y). Luminance is denoised at the requested strength; chrominance with a strength multiplied by `chroma_strength` (1.5 by default), because colour noise (the red, green and blue \"confetti\" of colour sensors) is more distracting and carries less detail. The R, G, B channels are then rebuilt. With `luminance_only: true`, chrominance is left untouched. A monochrome image (or one with a different number of channels) is processed channel by channel.\n\n**Methods:**\n\n- `wavelets` (default): \"à trous\" wavelet transform (B3 starlet), which splits the image into `layers` detail layers of increasing scale (1, 2, 4, 8… px) plus a residual. Each layer is **soft-thresholded**: coefficients below k_j × σ are set to zero, the others shrunk by the same amount. The threshold is `k` on the first layer and then decreases with scale (k / (1 + 0.5 j)), taking into account how noise is distributed across layers. With `noise_map: true`, σ is not a single value but a **local noise map** (robust RMS of the first layer, computed by SEP on 64 px cells with stars rejected): the noisy background is smoothed more than areas of strong signal, and a stack whose depth varies across the field (edges, mosaic, field rotation) is treated evenly. `strength` blends the result, globally or layer by layer.\n- `nlm`: OpenCV *Non-Local Means* (`fastNlMeansDenoising`, image converted to 16 bits, 5 × 5 patches and 13 × 13 search window, L1 norm). Each pixel is replaced by an average of pixels whose neighbourhood looks similar. The strength is `h` × σ, where σ is the global noise estimated on the first wavelet layer.\n- `bm3d`: *Block-Matching 3D*, through the optional Python package `bm3d` (noise σ multiplied by `h`). Often the best result on fine textures, but much slower.\n\n## When to use it\n\n- **Colour sensors and smart telescopes** (Vespera, Seestar): strong colour noise with short exposures; the boosted chrominance setting removes it without smearing the luminance.\n- **Light-polluted skies, short total integration**: grainy background after stretching. Denoising before the stretch avoids stretching the noise.\n- **Uneven stacks** (poorly covered edges, alt-az field rotation): the noise map adapts the threshold locally.\n- **After deconvolution**, to calm the noise it amplified.\n\nWhen **not** to use it (or sparingly):\n\n- on an already very clean image (long integration): the risk is erasing faint detail and getting a \"plastic\" look;\n- at full strength on stars and fine structures: use a mask to spare signal areas.\n\n**Recommended order**: preferably on the **linear** image, after `crop`, `background`/`gradient` and `deconv`, before `stretch`. A light pass after stretching, restricted to the background with a luminance mask, is also possible.\n\n## Installation\n\n```bash\nastrostack plugin install denoise\n```\n\nor from the **Plugins** view of the CelestiaX application, then add the \"Denoise\" step (Details group) to the recipe.\n\nPython dependencies: none required (`python_deps` is empty); NumPy, OpenCV and SEP are provided by astrostack.\n\n**Optional** dependency, only for `method: bm3d`:\n\n```bash\npip install bm3d\n```\n\nWithout this package, the `wavelets` and `nlm` methods work normally; `bm3d` stops with the message \"denoise : method bm3d nécessite le paquet bm3d (pip install bm3d)\".\n\n## Parameters\n\n### Stage `denoise`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `method` | choice | `wavelets` | Method: `wavelets`, `nlm` or `bm3d`. |\n| `layers` | int | `4` | Wavelets: number of layers (1 to 7). More layers = large-scale noise (blotches) is also treated. |\n| `k` | float | `3.0` | Wavelets: threshold in σ on the 1st layer, decreasing afterwards (0.5 to 10). |\n| `strength` | float | `1.0` | Strength 0–1; in YAML a list is allowed (one value per layer, the last one is repeated). |\n| `h` | float | `1.0` | NLM / BM3D: strength relative to the noise (0.1 to 5). |\n| `noise_map` | bool | `true` | Wavelets: thresholds adapted to local noise (otherwise global σ). |\n| `luminance_only` | bool | `false` | Denoise only the luminance (colour image). |\n| `chroma_strength` | float | `1.5` | Strength multiplier for chrominance (0 to 4): multiplies `k` (wavelets) or `h` (NLM / BM3D). |\n| `mask` | text | empty | Optional post-processing mask (see below). |\n\n**The `mask` parameter.** Restricts denoising to an area: the mask is computed on the image before the stage, then result = before × (1 − m) + after × m. Examples: `mask: {type: luminance, low: 0.1, high: 0.4, invert: true}` (denoise mostly the dark background), `mask: \"stars invert\"` (spare the stars), `mask: \"object invert feather=8\"` (sky background only). Types: `luminance`, `color`, `stars`, `object`, `range`, `file`, `combine`; common options `invert`, `blur` (σ in px), `strength` (0–1).\n\n## YAML examples\n\nStandard settings on the linear image:\n\n```yaml\npipeline:\n  - crop: {}\n  - gradient: {}\n  - deconv: {}\n  - denoise: {method: wavelets, layers: 4, k: 3.0, chroma_strength: 1.5}\n  - color: {method: stars}\n  - stretch: {method: auto}\n```\n\nPer-layer strength (fine noise strongly reduced, large scales preserved), background only:\n\n```yaml\npipeline:\n  - denoise:\n      method: wavelets\n      layers: 5\n      strength: [1.0, 0.8, 0.5, 0.3, 0.1]\n      mask: {type: luminance, low: 0.1, high: 0.4, invert: true}\n  - stretch: {method: auto}\n```\n\nBM3D (`bm3d` package installed), after stretching, stars spared:\n\n```yaml\npipeline:\n  - stretch: {method: auto}\n  - denoise: {method: bm3d, h: 0.8, mask: \"stars invert\"}\n```\n\n## Outputs\n\n- The current image is replaced by the denoised image (float32); out-of-field pixels (NaN) are kept.\n- No file is written; console message \"Débruitage <method> terminé\".\n\n## Limitations\n\n- Any denoising also removes some signal: the faintest nebulosity and small stars can fade if `k` or `h` is too high.\n- Wavelets: a high `k` with many layers can leave a \"mottled\" background; lower `k` or the strength of the large layers.\n- NLM works in 16 bits over a range limited by the 0.01 % – 99.99 % percentiles; its noise estimate is global (no local map).\n- BM3D is slow on large images and relies on an external package with a restrictive licence (see below).\n\n## Licences\n\n- Plugin: **MIT** licence, © Erwan Sturzenegger.\n- Dependencies installed with astrostack: NumPy and SciPy (BSD), OpenCV (Apache 2.0), SEP (LGPL v3 for code derived from SExtractor, BSD/MIT for the rest).\n- `bm3d` (optional, PyPI): distributed under its authors' own licence which, to our knowledge, restricts use to **non-commercial** purposes (research, evaluation, personal use). Check the package licence (`pip show bm3d` and the licence file it ships) before any use, especially commercial. The plugin does not bundle it and never installs it automatically.\n"}},{"id":"details","version":"1.0.0","name":{"fr":"Détails & HDR","en":"Details & HDR"},"summary":{"fr":"HDR multi-échelle (compression des zones brillantes) et netteté locale (CLAHE ou masque flou, fond protégé).","en":"Multi-scale HDR (compression of bright areas) and local sharpening (CLAHE or unsharp mask, background protected)."},"category":"post","tags":["hdr","sharpen","clahe","unsharp-mask"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/details","min_astrostack":"0.1.0","entry":"celestiax_details","python_deps":[],"stages":["hdr","sharpen"],"frame_ops":[],"ai":false,"models":[],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale (extraite du cœur d'astrostack)","en":"Initial release (extracted from the astrostack core)"}},"download":"https://celestiax-plugins.sturzy.ch/dl/details-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/details-1.0.0.zip","size":11512,"sha256":"52fa8765247f10c2338d427b52f4e0b611e0b36c979d123fdc054d9bca8d8a2f","readme":{"fr":"# Détails & HDR\n\nDeux outils de mise en valeur des détails : une compression HDR multi-échelle des zones brillantes (`hdr`) et une netteté locale sur la luminance (`sharpen`, CLAHE ou masque flou), fond de ciel protégé et couleurs conservées.\n\n## Fonction\n\nLe plugin fournit deux étapes : `hdr` et `sharpen`.\n\n### `hdr` — compression multi-échelle des zones brillantes\n\nCertains objets ont une dynamique énorme : le cœur de M42, le bulbe d'une galaxie ou d'un amas globulaire sont « brûlés » dès que l'on étire assez pour voir les extensions faibles. L'étape `hdr` :\n\n1. calcule la luminance (moyenne des canaux) et passe en **domaine logarithmique** ;\n2. sépare un **fond grande échelle** (flou d'échelle 2^`layers` px, gaussien, ou filtre guidé si `edge_aware`) des **détails** (tout le reste) ;\n3. **comprime uniquement le fond** au-dessus d'un seuil (`threshold` × maximum du fond) avec une pente 1 − `amount`, via un genou doux (fonction *softplus*) pour éviter toute cassure ; les détails, eux, sont réinjectés intacts ;\n4. applique le rapport nouvelle / ancienne luminance aux trois canaux : les **couleurs sont conservées** ;\n5. option `rescale` : étire linéairement les valeurs situées au-dessus du seuil pour ramener le maximum (99,99e percentile) à son niveau d'origine, sans toucher au fond.\n\nRésultat : le cœur lumineux redevient lisible (structures visibles) tandis que les zones faibles ne bougent pas. Dans l'aperçu réduit de l'application, `layers` est automatiquement adapté à l'échelle.\n\n### `sharpen` — netteté locale\n\nTravaille sur la luminance (pondération Rec. 709) d'une image **étirée** (valeurs ramenées dans 0–1), puis remplace la luminance en conservant les rapports R:G:B.\n\n- `unsharp` (défaut) : **masque flou**. Les détails (luminance − flou gaussien de `sigma` px) sont ajoutés, multipliés par `amount`. Un poids protège le fond : il vaut 0 sous le seuil `threshold` (par défaut : médiane + 3 × MAD du fond, calculé automatiquement) et monte progressivement à 1 au-dessus, si bien que le bruit du ciel n'est pas accentué.\n- `clahe` : **CLAHE** (égalisation d'histogramme adaptative à contraste limité, OpenCV) sur une grille de `tile` × `tile` tuiles, limitée par `clip_limit`, puis mélangée à l'original selon `amount`. Augmente le contraste local des nébuleuses (structures moyennes), plutôt que la netteté fine.\n\n## Utilité / quand l'utiliser\n\n- `hdr` : **M42, M31, M8, amas globulaires, noyaux de galaxies**, et plus généralement tout objet dont le centre sature après l'étirement. Particulièrement utile sur les images de télescopes intelligents (Vespera, Seestar) de M42, où le Trapèze disparaît dans le blanc.\n- `sharpen` en `unsharp` : faire ressortir les bras d'une galaxie, les filaments d'une nébuleuse, après l'étirement ; `sigma` petit (1–2 px) pour les détails fins, plus grand pour les structures.\n- `sharpen` en `clahe` : nébuleuses étendues peu contrastées (nébuleuses en émission, sombres).\n\nQuand **ne pas** les utiliser :\n\n- `hdr` sur un objet sans zone brillante (champ d'étoiles, nébuleuse faible) : aucun effet utile ;\n- `sharpen` sur une image **linéaire** (non étirée) : l'étape travaille dans 0–1 et suppose une image étirée ;\n- `sharpen` sur une image encore bruitée : débruitez d'abord (plugin « denoise »), sinon le bruit des zones de signal sera aussi accentué ;\n- des forces élevées : halos sombres autour des étoiles et des bords nets (masque flou), aspect artificiel (CLAHE).\n\n**Ordre conseillé** : `hdr` après un premier `stretch` (quand le cœur apparaît brûlé), éventuellement suivi d'un second étirement léger ; `sharpen` en fin de chaîne, après `stretch` et `denoise`, avant `saturation` et `export`.\n\n## Installation\n\n```bash\nastrostack plugin install details\n```\n\nou depuis la vue **Plugins** de l'application CelestiaX, puis ajoutez « HDR multi-échelle » (groupe Tons) ou « Netteté locale » (groupe Détails) à la recette.\n\nDépendances Python : aucune en plus du cœur (`python_deps` vide) ; NumPy et OpenCV sont fournis par astrostack.\n\nOptionnel : `hdr` avec `edge_aware: true` utilise le filtre guidé d'OpenCV (`cv2.ximgproc`), présent seulement dans les modules « contrib » (paquet `opencv-contrib-python-headless`, qui remplace alors `opencv-python-headless`). Sans ces modules, l'étape utilise silencieusement un flou gaussien.\n\n## Paramètres\n\n### Étape `hdr`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `layers` | int | `5` | Échelle du fond comprimé : 2^`layers` px (2 à 9). Plus grand = compression plus globale. |\n| `amount` | float | `0.7` | Force de compression (0–1). |\n| `threshold` | float | `0.3` | Luminosité (fraction du maximum) à partir de laquelle on compresse (0,01 à 1). |\n| `edge_aware` | bool | `false` | Filtre guidé : moins de halos aux bords nets (nécessite OpenCV contrib). |\n| `rescale` | bool | `false` | Ramène le maximum au niveau d'origine. |\n| `mask` | text | vide | Masque de post-traitement facultatif (voir ci-dessous). |\n\n### Étape `sharpen`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `method` | choice | `unsharp` | `clahe` : contraste local ; `unsharp` : accentuation des détails. |\n| `amount` | float | `0.7` | Force (mélange pour `clahe`, gain des détails pour `unsharp`), de 0 à 3. |\n| `clip_limit` | float | `2.0` | Limite de contraste CLAHE (0,5 à 10). |\n| `tile` | int | `8` | Nombre de tuiles CLAHE par côté (2 à 32). |\n| `sigma` | float | `2.0` | Échelle des détails `unsharp`, en px (0,3 à 20). |\n| `threshold` | float | vide | Luminance sous laquelle le fond est protégé (`unsharp`), 0 à 1 ; vide = automatique (facultatif). |\n| `mask` | text | vide | Masque de post-traitement facultatif (voir ci-dessous). |\n\n**Le paramètre `mask`.** Les deux étapes acceptent les masques de post-traitement d'astrostack. Le masque est calculé sur l'image avant l'étape, puis résultat = avant × (1 − m) + après × m. Forme courte : `mask: \"stars invert\"` (ne pas accentuer les étoiles), `mask: \"object feather=8\"` (limiter à la nébuleuse ou à la galaxie) ; forme dictionnaire : `mask: {type: luminance, low: 0.1, high: 0.4}`. Types : `luminance`, `color`, `stars`, `object`, `range`, `file`, `combine` ; options communes `invert`, `blur` (σ en px), `strength` (0–1).\n\n## Exemples YAML\n\nM42 : cœur comprimé après l'étirement, puis netteté :\n\n```yaml\npipeline:\n  - gradient: {}\n  - color: {method: stars}\n  - stretch: {method: auto, target_background: 0.2}\n  - hdr: {layers: 5, amount: 0.7, threshold: 0.3, rescale: true}\n  - sharpen: {method: unsharp, amount: 0.5, sigma: 1.5, mask: \"stars invert\"}\n  - export: {formats: [tiff16, png]}\n```\n\nGalaxie : netteté limitée à l'objet, sans toucher aux étoiles :\n\n```yaml\npipeline:\n  - denoise: {}\n  - stretch: {method: ghs}\n  - sharpen:\n      amount: 0.8\n      sigma: 2.0\n      mask: {type: combine, op: min, masks: [{type: object, feather: 8}, {type: stars, invert: true}]}\n```\n\nNébuleuse étendue : contraste local CLAHE, effet dosé :\n\n```yaml\npipeline:\n  - stretch: {method: auto}\n  - sharpen: {method: clahe, clip_limit: 2.0, tile: 8, amount: 0.4}\n```\n\n## Sorties\n\n- `hdr` : l'image courante est remplacée (float32, même échelle que l'entrée) ; message console avec la force et le seuil.\n- `sharpen` : l'image courante est remplacée par une image dans 0–1 (float32).\n- Les pixels hors champ (NaN) sont conservés par les deux étapes. Aucun fichier écrit.\n\n## Limites\n\n- `hdr` agit sur la luminance seule : une zone saturée dans un seul canal (étoile colorée brûlée) ne retrouve pas sa couleur.\n- `hdr` sans `edge_aware` peut produire un léger halo sombre autour d'un cœur très contrasté ; `edge_aware` (filtre guidé) l'atténue.\n- `sharpen` ramène l'image dans 0–1 : les valeurs au-delà sont écrêtées (sans changement de teinte).\n- `clahe` travaille en 16 bits et peut accentuer le bruit du fond : utilisez `amount` modéré ou un masque.\n\n## Licences\n\n- Plugin : licence **MIT**, © Erwan Sturzenegger.\n- Dépendances (installées avec astrostack) : NumPy (BSD), OpenCV (Apache 2.0), y compris les modules contrib optionnels (Apache 2.0).\n","en":"# Details & HDR\n\nTwo detail-enhancement tools: a multi-scale HDR compression of bright areas (`hdr`) and local sharpening of the luminance (`sharpen`, CLAHE or unsharp mask), with the sky background protected and colours preserved.\n\n## What it does\n\nThe plugin provides two stages: `hdr` and `sharpen`.\n\n### `hdr` — multi-scale compression of bright areas\n\nSome objects have a huge dynamic range: the core of M42, the bulge of a galaxy or a globular cluster are \"burnt out\" as soon as you stretch enough to reveal the faint outer parts. The `hdr` stage:\n\n1. computes the luminance (mean of the channels) and moves to the **logarithmic domain**;\n2. separates a **large-scale background** (blur at a scale of 2^`layers` px, Gaussian, or guided filter if `edge_aware`) from the **details** (everything else);\n3. **compresses only the background** above a threshold (`threshold` × background maximum) with a slope of 1 − `amount`, through a soft knee (*softplus* function) to avoid any break; the details are added back untouched;\n4. applies the new / old luminance ratio to all three channels: **colours are preserved**;\n5. `rescale` option: linearly stretches the values above the threshold to bring the maximum (99.99th percentile) back to its original level, without touching the background.\n\nResult: the bright core becomes readable again (structures visible) while faint areas do not move. In the application's reduced preview, `layers` is adapted to the scale automatically.\n\n### `sharpen` — local sharpening\n\nWorks on the luminance (Rec. 709 weighting) of a **stretched** image (values brought into 0–1), then replaces the luminance while keeping the R:G:B ratios.\n\n- `unsharp` (default): **unsharp mask**. Details (luminance − Gaussian blur of `sigma` px) are added, multiplied by `amount`. A weight protects the background: it is 0 below the `threshold` (by default median + 3 × MAD of the background, computed automatically) and rises gradually to 1 above it, so sky noise is not enhanced.\n- `clahe`: **CLAHE** (contrast-limited adaptive histogram equalisation, OpenCV) on a grid of `tile` × `tile` tiles, limited by `clip_limit`, then blended with the original according to `amount`. Increases the local contrast of nebulae (medium-scale structures) rather than fine sharpness.\n\n## When to use it\n\n- `hdr`: **M42, M31, M8, globular clusters, galaxy cores**, and more generally any object whose centre saturates after stretching. Especially useful on smart-telescope images (Vespera, Seestar) of M42, where the Trapezium vanishes into white.\n- `sharpen` with `unsharp`: bring out a galaxy's arms or a nebula's filaments after stretching; small `sigma` (1–2 px) for fine detail, larger for structures.\n- `sharpen` with `clahe`: extended, low-contrast nebulae (emission or dark nebulae).\n\nWhen **not** to use them:\n\n- `hdr` on an object without a bright area (star field, faint nebula): no useful effect;\n- `sharpen` on a **linear** (unstretched) image: the stage works in 0–1 and assumes a stretched image;\n- `sharpen` on a still noisy image: denoise first (plugin \"denoise\"), otherwise noise in signal areas will be enhanced too;\n- high strengths: dark halos around stars and sharp edges (unsharp mask), artificial look (CLAHE).\n\n**Recommended order**: `hdr` after a first `stretch` (when the core looks burnt out), possibly followed by a second light stretch; `sharpen` near the end of the chain, after `stretch` and `denoise`, before `saturation` and `export`.\n\n## Installation\n\n```bash\nastrostack plugin install details\n```\n\nor from the **Plugins** view of the CelestiaX application, then add \"Multi-scale HDR\" (Tones group) or \"Local sharpening\" (Details group) to the recipe.\n\nPython dependencies: none beyond the core (`python_deps` is empty); NumPy and OpenCV are provided by astrostack.\n\nOptional: `hdr` with `edge_aware: true` uses OpenCV's guided filter (`cv2.ximgproc`), which is only available in the \"contrib\" modules (package `opencv-contrib-python-headless`, which then replaces `opencv-python-headless`). Without these modules, the stage silently falls back to a Gaussian blur.\n\n## Parameters\n\n### Stage `hdr`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `layers` | int | `5` | Scale of the compressed background: 2^`layers` px (2 to 9). Larger = more global compression. |\n| `amount` | float | `0.7` | Compression strength (0–1). |\n| `threshold` | float | `0.3` | Brightness (fraction of the maximum) above which compression starts (0.01 to 1). |\n| `edge_aware` | bool | `false` | Guided filter: fewer halos at sharp edges (requires OpenCV contrib). |\n| `rescale` | bool | `false` | Bring the maximum back to its original level. |\n| `mask` | text | empty | Optional post-processing mask (see below). |\n\n### Stage `sharpen`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `method` | choice | `unsharp` | `clahe`: local contrast; `unsharp`: detail enhancement. |\n| `amount` | float | `0.7` | Strength (blend for `clahe`, detail gain for `unsharp`), 0 to 3. |\n| `clip_limit` | float | `2.0` | CLAHE contrast limit (0.5 to 10). |\n| `tile` | int | `8` | Number of CLAHE tiles per side (2 to 32). |\n| `sigma` | float | `2.0` | Detail scale for `unsharp`, in px (0.3 to 20). |\n| `threshold` | float | empty | Luminance below which the background is protected (`unsharp`), 0 to 1; empty = automatic (optional). |\n| `mask` | text | empty | Optional post-processing mask (see below). |\n\n**The `mask` parameter.** Both stages accept astrostack's post-processing masks. The mask is computed on the image before the stage, then result = before × (1 − m) + after × m. Short form: `mask: \"stars invert\"` (do not sharpen stars), `mask: \"object feather=8\"` (limit to the nebula or galaxy); dictionary form: `mask: {type: luminance, low: 0.1, high: 0.4}`. Types: `luminance`, `color`, `stars`, `object`, `range`, `file`, `combine`; common options `invert`, `blur` (σ in px), `strength` (0–1).\n\n## YAML examples\n\nM42: core compressed after stretching, then sharpening:\n\n```yaml\npipeline:\n  - gradient: {}\n  - color: {method: stars}\n  - stretch: {method: auto, target_background: 0.2}\n  - hdr: {layers: 5, amount: 0.7, threshold: 0.3, rescale: true}\n  - sharpen: {method: unsharp, amount: 0.5, sigma: 1.5, mask: \"stars invert\"}\n  - export: {formats: [tiff16, png]}\n```\n\nGalaxy: sharpening limited to the object, stars untouched:\n\n```yaml\npipeline:\n  - denoise: {}\n  - stretch: {method: ghs}\n  - sharpen:\n      amount: 0.8\n      sigma: 2.0\n      mask: {type: combine, op: min, masks: [{type: object, feather: 8}, {type: stars, invert: true}]}\n```\n\nExtended nebula: CLAHE local contrast, reduced effect:\n\n```yaml\npipeline:\n  - stretch: {method: auto}\n  - sharpen: {method: clahe, clip_limit: 2.0, tile: 8, amount: 0.4}\n```\n\n## Outputs\n\n- `hdr`: the current image is replaced (float32, same scale as the input); console message with the strength and threshold.\n- `sharpen`: the current image is replaced by an image in 0–1 (float32).\n- Out-of-field pixels (NaN) are kept by both stages. No file is written.\n\n## Limitations\n\n- `hdr` acts on luminance only: an area saturated in a single channel (burnt-out coloured star) does not recover its colour.\n- `hdr` without `edge_aware` can produce a slight dark halo around a very contrasted core; `edge_aware` (guided filter) reduces it.\n- `sharpen` brings the image into 0–1: values above are clipped (without hue change).\n- `clahe` works in 16 bits and can enhance background noise: use a moderate `amount` or a mask.\n\n## Licences\n\n- Plugin: **MIT** licence, © Erwan Sturzenegger.\n- Dependencies (installed with astrostack): NumPy (BSD), OpenCV (Apache 2.0), including the optional contrib modules (Apache 2.0).\n"}},{"id":"gradient-samples","version":"1.0.0","name":{"fr":"Gradient par échantillons","en":"Sample-based gradient removal"},"summary":{"fr":"Retrait des gradients complexes : échantillons de fond placés hors objets et étoiles, interpolation RBF ou spline.","en":"Complex gradient removal: background samples placed away from objects and stars, RBF or spline interpolation."},"category":"post","tags":["gradient","background","light-pollution"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/gradient-samples","min_astrostack":"0.1.0","entry":"celestiax_gradient_samples","python_deps":[],"stages":["gradient"],"frame_ops":[],"ai":false,"models":[],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale (extraite du cœur d'astrostack)","en":"Initial release (extracted from the astrostack core)"}},"download":"https://celestiax-plugins.sturzy.ch/dl/gradient-samples-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/gradient-samples-1.0.0.zip","size":11724,"sha256":"aed0ecd306ca5cc389c86bb4885aca7e1ce22210a1775df88b132925f5403953","readme":{"fr":"# Gradient par échantillons\n\nRetire les gradients de fond complexes (pollution lumineuse, Lune, vignetage) en mesurant le ciel sur des échantillons placés hors des objets et des étoiles, puis en interpolant une surface lisse (RBF ou spline).\n\n## Fonction\n\nLe plugin fournit une étape : `gradient`.\n\nL'étape construit un **modèle du fond de ciel** puis le retire de l'image, canal par canal :\n\n1. **Masque d'exclusion.** Un premier modèle grossier (polynôme robuste sur une grille 12 × 12) est soustrait de la luminance ; sur ce résidu, astrostack repère les objets étendus (nébuleuses, galaxies : masque `object`) et les étoiles (masque `stars`, détection SEP). Ces zones sont exclues de la mesure du fond.\n2. **Placement automatique des échantillons.** L'image est découpée en une grille d'environ `samples` cases. Une case est écartée si moins de 30 % de ses pixels sont libres. Dans chaque case restante, les pixels sont filtrés à 3 × MAD (écart absolu médian), puis la médiane de chaque canal donne la valeur de l'échantillon. Les cases dont le niveau résiduel dépasse le fond médian de plus de `kappa` × MAD (reste de nébulosité, halo d'étoile) sont rejetées, de même que les cases anormalement sombres.\n3. **Points manuels.** Des points supplémentaires peuvent être donnés en fraction de la largeur et de la hauteur (`points`) : la médiane d'une petite case autour de chaque point est ajoutée aux échantillons.\n4. **Interpolation.** Une surface lisse passant (au lissage près) par les échantillons est calculée sur une grille grossière (96 points de large), puis agrandie à la taille de l'image par interpolation bicubique :\n   - `rbf` : fonctions de base radiales *thin-plate spline* (plaque mince) avec terme linéaire, lissage exprimé en unités de bruit ;\n   - `spline` : spline bicubique lissante (linéaire si moins de 16 échantillons).\n5. **Correction.** En mode `subtract`, le modèle est soustrait puis sa médiane est rajoutée (le niveau moyen du fond est conservé). En mode `divide`, l'image est divisée par le modèle normalisé à 1 (correction multiplicative, adaptée au vignetage).\n\nSi moins de 3 échantillons sont disponibles, l'étape est ignorée avec un avertissement.\n\n## Utilité / quand l'utiliser\n\n- **Ciel pollué, gradients irréguliers** : dôme de lumière urbaine sur un côté, lumière de la Lune, gradient qui change de direction pendant la nuit. Là où l'étape `background` du cœur (polynôme de degré faible) laisse des résidus, l'interpolation RBF suit des formes plus complexes.\n- **Télescopes intelligents (Vespera, Seestar)** : champ souvent rempli par une nébuleuse, rotation de champ en alt-az qui mélange les gradients ; l'évitement automatique des objets préserve la nébulosité faible.\n- **Lunette ou capteur couleur sans flat** : `mode: divide` compense un vignetage résiduel.\n- **Champ très rempli** (nébuleuse qui occupe presque tout le cadre) : désactivez `auto` et placez quelques `points` à la main dans les rares zones de vrai fond.\n\nQuand **ne pas** l'utiliser :\n\n- en même temps que l'étape `background` du cœur (choisissez l'une ou l'autre ; l'assistant de l'application ne propose plus `background` quand `gradient` est actif) ;\n- sur une image déjà étirée : le modèle additif n'est valable que sur des données linéaires ;\n- si le fond est déjà plat : un lissage trop faible peut alors retirer un peu de signal diffus.\n\n**Ordre conseillé** : sur l'image **linéaire**, après `crop` (les bords mal couverts fausseraient le modèle) et `channel_align`, avant `color`/`spcc` et avant `stretch`.\n\n## Installation\n\n```bash\nastrostack plugin install gradient-samples\n```\n\nou depuis la vue **Plugins** de l'application CelestiaX (bouton « Installer »), puis ajoutez l'étape « Retirer le gradient (échantillons) » (groupe Fond) à la recette.\n\nDépendances Python : aucune en plus du cœur (`python_deps` vide). Le plugin utilise NumPy, SciPy (`RBFInterpolator`, `SmoothBivariateSpline`), OpenCV, SEP et PyYAML, déjà installés avec astrostack.\n\n## Paramètres\n\n### Étape `gradient`\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `samples` | int | `200` | Nombre d'échantillons visé (taille de la grille), de 16 à 2000. |\n| `kappa` | float | `2.0` | Rejet des cases plus brillantes que le fond + `kappa` × MAD (0,5 à 10). Plus petit = rejet plus sévère. |\n| `method` | choice | `rbf` | Interpolation : `rbf` (thin-plate spline) ou `spline` (spline bicubique lissante). |\n| `smoothing` | float | `1.0` | Lissage (0 = la surface passe exactement par les échantillons), de 0 à 100. |\n| `mode` | choice | `subtract` | `subtract` (gradient additif : pollution, Lune) ou `divide` (vignetage). |\n| `avoid_objects` | bool | `true` | Éviter les objets étendus (masque `object`). |\n| `avoid_stars` | bool | `true` | Éviter les étoiles (masque `stars`). |\n| `auto` | bool | `true` | Placement automatique ; sinon seuls les points manuels sont utilisés. |\n| `points` | text | vide | Points manuels `[[x, y], ...]` en fraction 0–1 de l'image (facultatif). |\n| `mask` | text | vide | Masque de post-traitement facultatif (voir ci-dessous). |\n\n**Le paramètre `mask`.** Comme les autres étapes de post-traitement d'astrostack, `gradient` peut être limitée à une zone. Le masque est calculé sur l'image avant l'étape, puis résultat = avant × (1 − m) + après × m. Il s'écrit sous forme courte (`mask: \"stars invert\"`, `mask: \"luminance low=0.2 high=0.8 invert\"`, `mask: \"object feather=8\"`) ou sous forme de dictionnaire (`mask: {type: luminance, low: 0.1, high: 0.4}`). Types : `luminance`, `color`, `stars`, `object`, `range`, `file`, `combine` ; options communes `invert`, `blur` (σ en px) et `strength` (0–1). Pour un retrait de gradient, le masque est rarement utile : laissez-le vide dans la plupart des cas.\n\n## Exemples YAML\n\nUsage standard après recadrage, sur image linéaire :\n\n```yaml\npipeline:\n  - crop: {min_coverage: 0.9, margin: 8}\n  - channel_align: {max_shift: 5.0}\n  - gradient: {samples: 200, kappa: 2.0, method: rbf, smoothing: 1.0}\n  - color: {method: stars}\n  - stretch: {method: auto, target_background: 0.2, linked: true}\n```\n\nVignetage résiduel (pas de flat), puis gradient de pollution :\n\n```yaml\npipeline:\n  - crop: {}\n  - gradient: {mode: divide, samples: 120, smoothing: 5}\n  - gradient: {mode: subtract, samples: 250}\n  - color: {method: stars}\n```\n\nNébuleuse qui remplit le champ : points placés à la main uniquement.\n\n```yaml\npipeline:\n  - crop: {}\n  - gradient:\n      auto: false\n      method: spline\n      points: [[0.05, 0.05], [0.95, 0.05], [0.05, 0.95], [0.95, 0.95], [0.5, 0.03], [0.03, 0.5]]\n  - stretch: {method: auto}\n```\n\n## Sorties\n\n- L'image courante est corrigée en place (le niveau médian du fond est conservé en mode `subtract`) ; les pixels hors champ (NaN) restent intacts.\n- `.work/gradient_model.npy` : le modèle de fond retiré, tableau (C, H, W) float32.\n- `gradient_samples` dans l'état de la session : positions des échantillons retenus, en fraction de l'image (utilisées par l'interface pour les afficher).\n- Message console : nombre d'échantillons, méthode et mode.\n\n## Limites\n\n- Le modèle ne connaît que ce qu'il mesure : si un objet très faible et très étendu (IFN, nébulosité diffuse) n'est pas détecté par le masque `object`, il peut être partiellement retiré. Augmentez `smoothing`, baissez `kappa` ou passez en points manuels.\n- Avec peu d'échantillons (champ saturé d'objets), l'interpolation peut osciller entre les points : augmentez `smoothing` ou ajoutez des points manuels.\n- Le placement automatique suppose une image linéaire sans NaN massifs ; recadrez d'abord.\n- `divide` suppose un modèle strictement positif (valeurs bornées à 10⁻³ du fond médian).\n\n## Licences\n\n- Plugin : licence **MIT**, © Erwan Sturzenegger.\n- Dépendances (installées avec astrostack) : NumPy et SciPy (BSD), OpenCV (Apache 2.0), SEP (LGPL v3 pour le code dérivé de SExtractor, BSD/MIT pour le reste), PyYAML (MIT).\n","en":"# Sample-based gradient removal\n\nRemoves complex background gradients (light pollution, Moon, vignetting) by measuring the sky on samples placed away from objects and stars, then interpolating a smooth surface (RBF or spline).\n\n## What it does\n\nThe plugin provides one stage: `gradient`.\n\nThe stage builds a **model of the sky background** and removes it from the image, channel by channel:\n\n1. **Exclusion mask.** A first coarse model (robust polynomial on a 12 × 12 grid) is subtracted from the luminance; on that residual, astrostack finds extended objects (nebulae, galaxies: `object` mask) and stars (`stars` mask, SEP detection). These areas are excluded from the background measurement.\n2. **Automatic sample placement.** The image is split into a grid of about `samples` cells. A cell is dropped if fewer than 30 % of its pixels are free. In each remaining cell, pixels are clipped at 3 × MAD (median absolute deviation), and the median of each channel gives the sample value. Cells whose residual level exceeds the median background by more than `kappa` × MAD (leftover nebulosity, star halo) are rejected, as are abnormally dark cells.\n3. **Manual points.** Extra points can be given as fractions of the width and height (`points`): the median of a small box around each point is added to the samples.\n4. **Interpolation.** A smooth surface that goes through the samples (up to the smoothing) is computed on a coarse grid (96 points wide), then resized to the image size with bicubic interpolation:\n   - `rbf`: radial basis functions (*thin-plate spline*) with a linear term, smoothing expressed in noise units;\n   - `spline`: smoothing bicubic spline (linear if there are fewer than 16 samples).\n5. **Correction.** In `subtract` mode the model is subtracted and its median added back (the average background level is kept). In `divide` mode the image is divided by the model normalised to 1 (multiplicative correction, suited to vignetting).\n\nIf fewer than 3 samples are available, the stage is skipped with a warning.\n\n## When to use it\n\n- **Light-polluted skies, irregular gradients**: urban light dome on one side, moonlight, a gradient whose direction changes during the night. Where the core `background` stage (low-degree polynomial) leaves residuals, RBF interpolation follows more complex shapes.\n- **Smart telescopes (Vespera, Seestar)**: the field is often filled by a nebula, and alt-az field rotation mixes gradients; automatic object avoidance preserves faint nebulosity.\n- **Refractor or colour camera without flats**: `mode: divide` compensates residual vignetting.\n- **Very crowded field** (a nebula covering almost the whole frame): turn `auto` off and place a few `points` by hand in the rare areas of true background.\n\nWhen **not** to use it:\n\n- together with the core `background` stage (pick one; the application's advisor no longer suggests `background` when `gradient` is active);\n- on an already stretched image: the additive model only holds for linear data;\n- when the background is already flat: very low smoothing may then remove some diffuse signal.\n\n**Recommended order**: on the **linear** image, after `crop` (poorly covered edges would bias the model) and `channel_align`, before `color`/`spcc` and before `stretch`.\n\n## Installation\n\n```bash\nastrostack plugin install gradient-samples\n```\n\nor from the **Plugins** view of the CelestiaX application (\"Install\" button), then add the \"Remove gradient (samples)\" step (Background group) to the recipe.\n\nPython dependencies: none beyond the core (`python_deps` is empty). The plugin uses NumPy, SciPy (`RBFInterpolator`, `SmoothBivariateSpline`), OpenCV, SEP and PyYAML, all installed with astrostack.\n\n## Parameters\n\n### Stage `gradient`\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `samples` | int | `200` | Target number of samples (grid size), 16 to 2000. |\n| `kappa` | float | `2.0` | Reject cells brighter than background + `kappa` × MAD (0.5 to 10). Lower = stricter rejection. |\n| `method` | choice | `rbf` | Interpolation: `rbf` (thin-plate spline) or `spline` (smoothing bicubic spline). |\n| `smoothing` | float | `1.0` | Smoothing (0 = the surface goes exactly through the samples), 0 to 100. |\n| `mode` | choice | `subtract` | `subtract` (additive gradient: pollution, Moon) or `divide` (vignetting). |\n| `avoid_objects` | bool | `true` | Avoid extended objects (`object` mask). |\n| `avoid_stars` | bool | `true` | Avoid stars (`stars` mask). |\n| `auto` | bool | `true` | Automatic placement; otherwise only manual points are used. |\n| `points` | text | empty | Manual points `[[x, y], ...]` as 0–1 fractions of the image (optional). |\n| `mask` | text | empty | Optional post-processing mask (see below). |\n\n**The `mask` parameter.** Like the other astrostack post-processing stages, `gradient` can be restricted to an area. The mask is computed on the image before the stage, then result = before × (1 − m) + after × m. It can be written in short form (`mask: \"stars invert\"`, `mask: \"luminance low=0.2 high=0.8 invert\"`, `mask: \"object feather=8\"`) or as a dictionary (`mask: {type: luminance, low: 0.1, high: 0.4}`). Types: `luminance`, `color`, `stars`, `object`, `range`, `file`, `combine`; common options `invert`, `blur` (σ in px) and `strength` (0–1). For gradient removal a mask is rarely useful: leave it empty in most cases.\n\n## YAML examples\n\nStandard use after cropping, on a linear image:\n\n```yaml\npipeline:\n  - crop: {min_coverage: 0.9, margin: 8}\n  - channel_align: {max_shift: 5.0}\n  - gradient: {samples: 200, kappa: 2.0, method: rbf, smoothing: 1.0}\n  - color: {method: stars}\n  - stretch: {method: auto, target_background: 0.2, linked: true}\n```\n\nResidual vignetting (no flats), then a light-pollution gradient:\n\n```yaml\npipeline:\n  - crop: {}\n  - gradient: {mode: divide, samples: 120, smoothing: 5}\n  - gradient: {mode: subtract, samples: 250}\n  - color: {method: stars}\n```\n\nNebula filling the field: hand-placed points only.\n\n```yaml\npipeline:\n  - crop: {}\n  - gradient:\n      auto: false\n      method: spline\n      points: [[0.05, 0.05], [0.95, 0.05], [0.05, 0.95], [0.95, 0.95], [0.5, 0.03], [0.03, 0.5]]\n  - stretch: {method: auto}\n```\n\n## Outputs\n\n- The current image is corrected in place (the median background level is kept in `subtract` mode); out-of-field pixels (NaN) are left untouched.\n- `.work/gradient_model.npy`: the removed background model, a (C, H, W) float32 array.\n- `gradient_samples` in the session state: positions of the retained samples, as fractions of the image (used by the interface to display them).\n- Console message: number of samples, method and mode.\n\n## Limitations\n\n- The model only knows what it measures: if a very faint, very extended object (IFN, diffuse nebulosity) is not detected by the `object` mask, it can be partly removed. Increase `smoothing`, lower `kappa` or switch to manual points.\n- With few samples (field crowded with objects), the interpolation can oscillate between points: increase `smoothing` or add manual points.\n- Automatic placement assumes a linear image without large NaN areas; crop first.\n- `divide` assumes a strictly positive model (values floored at 10⁻³ of the median background).\n\n## Licences\n\n- Plugin: **MIT** licence, © Erwan Sturzenegger.\n- Dependencies (installed with astrostack): NumPy and SciPy (BSD), OpenCV (Apache 2.0), SEP (LGPL v3 for code derived from SExtractor, BSD/MIT for the rest), PyYAML (MIT).\n"}},{"id":"graxpert-ai","version":"1.0.0","name":{"fr":"GraXpert IA (fond & bruit)","en":"GraXpert AI (background & noise)"},"summary":{"fr":"Extraction du gradient de fond et débruitage par les réseaux de neurones de GraXpert (ONNX, CoreML/CPU), sur l'image linéaire.","en":"Background gradient extraction and denoising with GraXpert's neural networks (ONNX, CoreML/CPU), on the linear image."},"category":"ai","tags":["ai","graxpert","gradient","background","denoise","onnx"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/graxpert-ai","min_astrostack":"0.1.0","entry":"celestiax_graxpert_ai","python_deps":["onnxruntime>=1.17"],"stages":["ai_background","ai_denoise"],"frame_ops":[],"ai":true,"models":[{"id":"graxpert-denoise-3.0.2","name":{"fr":"GraXpert Débruitage IA 3.0.2","en":"GraXpert AI Denoise 3.0.2"},"url":"https://github.com/Dark-Matters-Astro/graxpert-ai-models/releases/download/tags/denoise-3.0.2/model-3.0.2.zip","filename":"model-3.0.2.zip","size_mb":441,"sha256":"f4f46c14fd91abadb79f1a7fe04c4511d02aeb21474642d98c412a4d33369171","license":"CC BY-NC-SA 4.0","notes":{"fr":"Publié par l'équipe GraXpert (organisation GitHub Dark-Matters-Astro). Archive zip contenant model.onnx (478 Mo une fois extrait, à la première utilisation). Licence CC BY-NC-SA 4.0 : usage non commercial uniquement, attribution « GraXpert Development Team ».","en":"Published by the GraXpert team (Dark-Matters-Astro GitHub organisation). Zip archive containing model.onnx (478 MB once extracted, on first use). CC BY-NC-SA 4.0 licence: non-commercial use only, attribution \"GraXpert Development Team\"."}}],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale : ai_background (modèle BGE de GraXpert, trouvé dans l'installation de GraXpert) et ai_denoise (modèle 3.0.2 téléchargeable).","en":"Initial release: ai_background (GraXpert BGE model, found in the GraXpert installation) and ai_denoise (downloadable 3.0.2 model)."}},"download":"https://celestiax-plugins.sturzy.ch/dl/graxpert-ai-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/graxpert-ai-1.0.0.zip","size":18688,"sha256":"08f0b2e75ec2046e855bef9be6a86500c09e1817016aab021b01c04d6107726e","readme":{"fr":"# GraXpert IA — fond de ciel et débruitage\n\nCe plugin exécute dans CelestiaX les réseaux de neurones de [GraXpert](https://graxpert.com) :\n\n| Étape | Rôle |\n|---|---|\n| `ai_background` | extraction du gradient de fond (pollution lumineuse, Lune, vignettage résiduel) **sans placer d'échantillons** |\n| `ai_denoise` | débruitage par réseau de neurones, qui préserve les étoiles et les structures fines |\n\nLe calcul passe par ONNX Runtime : CoreML (puce Apple : GPU / Neural Engine) quand il est disponible, sinon le CPU. Rien n'est activé ni téléchargé par défaut.\n\n## Quand l'utiliser\n\n- **`ai_background`** : quand le fond n'est pas uniforme et que le modèle polynomial (`background`) ou les échantillons manuels (`gradient-samples`) laissent des résidus, en particulier sur des champs encombrés (nébuleuses étendues, Voie lactée) où il est difficile de trouver du « vrai » fond. Placez-le sur l'image **linéaire**, juste après `crop`, avant la calibration des couleurs et l'étirement.\n- **`ai_denoise`** : sur l'image **linéaire**, après l'extraction du fond et avant l'étirement (comme dans GraXpert). À préférer aux ondelettes quand le signal est faible et que l'on veut garder des étoiles nettes.\n\n## Ce que font les modèles\n\n- **Fond (BGE)** : l'image est réduite à 240×240 px, bordée de 8 px, normalisée par canal ((x − médiane) / MAD × 0,04, écrêtée à ±1) ; le réseau prédit le fond sur cette vignette 256×256, qui est dénormalisée, lissée (σ = 3 px, plus `smoothing` × 20 px) puis agrandie à la taille de l'image. Seules les variations lentes sont donc retirées. Correction par **soustraction** (gradients additifs ; le niveau moyen du fond est conservé) ou **division** (vignettage, flat imparfait).\n- **Débruitage** : normalisation globale par canal (même formule, écrêtage à ±10), tuiles de 256 px avancées de 128 px dont seul le centre 128×128 est conservé (découpage identique à GraXpert, donc sans joint visible), pixels au-delà du seuil (cœurs d'étoiles saturés) laissés intacts, puis mélange avec l'original selon `strength`. Une image mono est présentée au réseau sur 3 canaux identiques.\n\nL'implémentation reproduit `graxpert/background_extraction.py` (branche IA) et `graxpert/denoising.py` de GraXpert 3.x.\n\n## Modèles, provenance et licences\n\n| Modèle | Source | Taille | Licence |\n|---|---|---|---|\n| Débruitage 3.0.2 (`graxpert-denoise-3.0.2`) | [Dark-Matters-Astro/graxpert-ai-models](https://github.com/Dark-Matters-Astro/graxpert-ai-models/releases/tag/tags%2Fdenoise-3.0.2) (organisation de l'équipe GraXpert) | 441 Mo (zip), 478 Mo extrait | CC BY-NC-SA 4.0 |\n| Extraction de fond BGE (1.0.x) | téléchargé **par GraXpert lui-même** | — | CC BY-NC-SA 4.0 |\n\nLes modèles GraXpert sont publiés par la « GraXpert Development Team » sous licence **Creative Commons BY-NC-SA 4.0** : **usage non commercial uniquement**, attribution obligatoire, partage dans les mêmes conditions. Le code de GraXpert est sous GPL-3.0 ; ce plugin ne contient aucun code de GraXpert (réimplémentation de la chaîne de pré/post-traitement) et ne redistribue aucun modèle.\n\n**Téléchargement du modèle de débruitage** (jamais automatique) : vue Plugins → GraXpert IA → Modèles → Télécharger, ou\n\n```\nastrostack plugin models graxpert-ai --download graxpert-denoise-3.0.2\n```\n\nL'archive est vérifiée (SHA-256) puis `model.onnx` en est extrait à la première utilisation.\n\n**Modèle d'extraction de fond** : GraXpert ne le publie pas à une adresse publique (il est distribué par un serveur S3 dont les identifiants sont internes à l'application). Pour l'utiliser : installez GraXpert, ouvrez son gestionnaire de modèles IA et téléchargez le modèle « Background Extraction ». Le plugin le trouve ensuite automatiquement :\n\n- macOS : `~/Library/Application Support/GraXpert/bge-ai-models/<version>/model.onnx`\n- Linux : `~/.local/share/GraXpert/bge-ai-models/<version>/model.onnx`\n- Windows : `%LOCALAPPDATA%\\GraXpert\\GraXpert\\bge-ai-models\\<version>\\model.onnx`\n\n(la version la plus récente est choisie), ou indiquez le fichier dans `model_path`, ou copiez-le dans `~/.cache/astrostack/models/graxpert-bge/model.onnx`. Sans modèle, l'étape s'arrête avec un message explicatif (`ModelMissing`).\n\n## Paramètres\n\n### `ai_background`\n\n| Paramètre | Défaut | Rôle |\n|---|---|---|\n| `correction` | `subtraction` | `subtraction` (pollution lumineuse) ou `division` (vignettage) |\n| `smoothing` | 0 | lissage supplémentaire du fond prédit (0–1, comme le curseur de GraXpert) |\n| `output` | `corrected` | `background` pour visualiser le fond prédit |\n| `model_path` | vide | chemin de `model.onnx` (vide : recherche automatique) |\n| `device` | `auto` | `auto` (CoreML/GPU puis CPU) ou `cpu` |\n\n### `ai_denoise`\n\n| Paramètre | Défaut | Rôle |\n|---|---|---|\n| `strength` | 0,5 | 0 = original, 1 = sortie du réseau seule |\n| `batch_size` | 4 | tuiles par lot (arrondi à une puissance de 2 entre 1 et 32) |\n| `device` | `auto` | `auto` ou `cpu` |\n| `mask` | vide | masque optionnel, ex. `stars invert` pour ne débruiter que le fond |\n\n## Exemple\n\n```yaml\npipeline:\n  - stack: {}\n  - crop: {}\n  - ai_background: {correction: subtraction}\n  - ai_denoise: {strength: 0.6, mask: \"luminance low=0.1 high=0.5 invert\"}\n  - color: {}\n  - stretch: {method: auto}\n  - export: {}\n```\n\n## Contrôle\n\nChaque étape enregistre une image de contrôle dans `.work/` : `ai_background_diff.npy` (le fond retiré) et `ai_denoise_diff.npy` (le bruit retiré, avant − après). Regardez-les : une structure reconnaissable (nébuleuse, bras de galaxie) dans l'une ou l'autre signifie que le réseau a retiré du signal.\n\n## Temps de calcul (Mac M4 Max)\n\n| Cas | CoreML | CPU |\n|---|---|---|\n| `ai_denoise`, 640×480 | 0,5 s (3 s au premier appel : chargement et compilation du modèle) | 7,5 s |\n| `ai_denoise`, 3000×2000 | 9 s | ≈ 2,5 min (extrapolé) |\n| `ai_background` | < 0,5 s quelle que soit la taille (une seule inférence 256×256) | idem |\n\n`ai_background` est rejouée dans l'aperçu en direct ; `ai_denoise` non (modèle de 478 Mo).\n\n## Limites\n\n- Les modèles sont **non commerciaux** (CC BY-NC-SA 4.0) : n'utilisez pas les images traitées à des fins commerciales sans l'accord de l'équipe GraXpert.\n- Le modèle de fond n'est disponible qu'au travers de GraXpert (pas de téléchargement direct).\n- Le fond est prédit à 256×256 px : un gradient très local (reflet, halo d'étoile brillante) n'est pas corrigé ; une nébuleuse qui remplit tout le champ peut être en partie prise pour du fond.\n- CoreML calcule en précision réduite : l'écart avec le CPU reste de l'ordre du bruit (au plus ~1 σ sur quelques pixels). Utilisez `device: cpu` pour un résultat bit à bit reproductible.\n- Débruitage IA = interprétation : à éviter avant une photométrie ou une astrométrie précises.\n","en":"# GraXpert AI — sky background and denoising\n\nThis plugin runs [GraXpert](https://graxpert.com)'s neural networks inside CelestiaX:\n\n| Step | Purpose |\n|---|---|\n| `ai_background` | background gradient extraction (light pollution, Moon, residual vignetting) **without placing samples** |\n| `ai_denoise` | neural-network denoising that preserves stars and fine structures |\n\nInference runs through ONNX Runtime: CoreML (Apple silicon GPU / Neural Engine) when available, otherwise the CPU. Nothing is enabled or downloaded by default.\n\n## When to use it\n\n- **`ai_background`**: when the background is uneven and the polynomial model (`background`) or manual samples (`gradient-samples`) leave residuals, especially in crowded fields (extended nebulae, Milky Way) where \"true\" background is hard to find. Place it on the **linear** image, right after `crop`, before colour calibration and stretching.\n- **`ai_denoise`**: on the **linear** image, after background extraction and before stretching (as in GraXpert). Prefer it to wavelets when the signal is faint and you want to keep sharp stars.\n\n## What the models do\n\n- **Background (BGE)**: the image is shrunk to 240×240 px, padded by 8 px and normalised per channel ((x − median) / MAD × 0.04, clipped to ±1); the network predicts the background on this 256×256 thumbnail, which is de-normalised, smoothed (σ = 3 px, plus `smoothing` × 20 px) and resized back to full size. Only slow variations are therefore removed. Correction by **subtraction** (additive gradients; the mean background level is kept) or **division** (vignetting, imperfect flat).\n- **Denoising**: global per-channel normalisation (same formula, clipped to ±10), 256 px tiles with a 128 px stride, keeping only the central 128×128 of each tile (same tiling as GraXpert, hence no visible seams), pixels above the threshold (saturated star cores) left untouched, then blended with the original according to `strength`. Mono images are fed to the network as 3 identical channels.\n\nThe implementation reproduces GraXpert 3.x's `graxpert/background_extraction.py` (AI branch) and `graxpert/denoising.py`.\n\n## Models, origin and licences\n\n| Model | Source | Size | Licence |\n|---|---|---|---|\n| Denoise 3.0.2 (`graxpert-denoise-3.0.2`) | [Dark-Matters-Astro/graxpert-ai-models](https://github.com/Dark-Matters-Astro/graxpert-ai-models/releases/tag/tags%2Fdenoise-3.0.2) (GraXpert team organisation) | 441 MB (zip), 478 MB extracted | CC BY-NC-SA 4.0 |\n| Background extraction BGE (1.0.x) | downloaded **by GraXpert itself** | — | CC BY-NC-SA 4.0 |\n\nGraXpert's models are published by the \"GraXpert Development Team\" under the **Creative Commons BY-NC-SA 4.0** licence: **non-commercial use only**, attribution required, share-alike. GraXpert's code is GPL-3.0; this plugin contains no GraXpert code (it re-implements the pre/post-processing chain) and redistributes no model.\n\n**Downloading the denoise model** (never automatic): Plugins view → GraXpert AI → Models → Download, or\n\n```\nastrostack plugin models graxpert-ai --download graxpert-denoise-3.0.2\n```\n\nThe archive is checked (SHA-256) and `model.onnx` is extracted from it on first use.\n\n**Background extraction model**: GraXpert does not publish it at a public address (it is served from an S3 server whose credentials are internal to the application). To use it: install GraXpert, open its AI model manager and download the \"Background Extraction\" model. The plugin then finds it automatically:\n\n- macOS: `~/Library/Application Support/GraXpert/bge-ai-models/<version>/model.onnx`\n- Linux: `~/.local/share/GraXpert/bge-ai-models/<version>/model.onnx`\n- Windows: `%LOCALAPPDATA%\\GraXpert\\GraXpert\\bge-ai-models\\<version>\\model.onnx`\n\n(the newest version wins), or set the file in `model_path`, or copy it to `~/.cache/astrostack/models/graxpert-bge/model.onnx`. Without a model, the step stops with an explanatory message (`ModelMissing`).\n\n## Parameters\n\n### `ai_background`\n\n| Parameter | Default | Purpose |\n|---|---|---|\n| `correction` | `subtraction` | `subtraction` (light pollution) or `division` (vignetting) |\n| `smoothing` | 0 | extra smoothing of the predicted background (0–1, like GraXpert's slider) |\n| `output` | `corrected` | `background` to display the predicted background |\n| `model_path` | empty | path to `model.onnx` (empty: automatic lookup) |\n| `device` | `auto` | `auto` (CoreML/GPU then CPU) or `cpu` |\n\n### `ai_denoise`\n\n| Parameter | Default | Purpose |\n|---|---|---|\n| `strength` | 0.5 | 0 = original, 1 = network output only |\n| `batch_size` | 4 | tiles per batch (rounded to a power of 2 between 1 and 32) |\n| `device` | `auto` | `auto` or `cpu` |\n| `mask` | empty | optional mask, e.g. `stars invert` to denoise the background only |\n\n## Example\n\n```yaml\npipeline:\n  - stack: {}\n  - crop: {}\n  - ai_background: {correction: subtraction}\n  - ai_denoise: {strength: 0.6, mask: \"luminance low=0.1 high=0.5 invert\"}\n  - color: {}\n  - stretch: {method: auto}\n  - export: {}\n```\n\n## Checking the result\n\nEach step writes a control image to `.work/`: `ai_background_diff.npy` (the removed background) and `ai_denoise_diff.npy` (the removed noise, before − after). Look at them: a recognisable structure (nebula, galaxy arm) in either one means the network removed signal.\n\n## Processing time (Mac M4 Max)\n\n| Case | CoreML | CPU |\n|---|---|---|\n| `ai_denoise`, 640×480 | 0.5 s (3 s on first call: model loading and compilation) | 7.5 s |\n| `ai_denoise`, 3000×2000 | 9 s | ≈ 2.5 min (extrapolated) |\n| `ai_background` | < 0.5 s whatever the size (a single 256×256 inference) | same |\n\n`ai_background` is replayed in the live preview; `ai_denoise` is not (478 MB model).\n\n## Limitations\n\n- The models are **non-commercial** (CC BY-NC-SA 4.0): do not use processed images commercially without the GraXpert team's consent.\n- The background model is only available through GraXpert (no direct download).\n- The background is predicted at 256×256 px: very local gradients (reflections, bright-star halos) are not corrected; a nebula filling the whole field may be partly taken for background.\n- CoreML computes in reduced precision: the difference with the CPU stays at noise level (at most ~1 σ on a few pixels). Use `device: cpu` for bit-exact reproducibility.\n- AI denoising is an interpretation: avoid it before precise photometry or astrometry.\n"}},{"id":"stars-tools","version":"1.0.0","name":{"fr":"Outils étoiles","en":"Star tools"},"summary":{"fr":"Retrait des étoiles (image sans étoiles + calque), ré-ajout, réduction des étoiles (érosion masquée, Blanshan), réduction des halos colorés.","en":"Star removal (starless image + star layer), recombination, star reduction (masked erosion, Blanshan), coloured halo reduction."},"category":"post","tags":["starless","star-reduction","halo"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/stars-tools","min_astrostack":"0.1.0","entry":"celestiax_stars_tools","python_deps":[],"stages":["starless","stars_add","star_reduce","halo_reduce"],"frame_ops":[],"ai":false,"models":[],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale (extraite du cœur d'astrostack)","en":"Initial release (extracted from the astrostack core)"}},"download":"https://celestiax-plugins.sturzy.ch/dl/stars-tools-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/stars-tools-1.0.0.zip","size":15046,"sha256":"c9aa0f5d9b9b05fef0c10cd393aa2d6354253e0ef7b1a57906bd6438de997a19","readme":{"fr":"# Outils étoiles\n\nSéparez les étoiles du fond, traitez la nébuleuse sans elles puis réintégrez-les, réduisez leur taille et atténuez les halos colorés des lunettes.\n\n## Fonction\n\nLe plugin fournit quatre étapes de post-traitement (`pipeline:`) pour astrostack (application CelestiaX).\n\n- **`starless`** : retire les étoiles de l'image. Les étoiles sont détectées avec SEP sur la luminance (seuil en multiples du bruit), puis chaque étoile est couverte par sa zone de segmentation, agrandie jusqu'au niveau du fond (disque de rayon `(1 + grow) × rayon isophote + min_grow`). Les trous sont remplis par un remplissage en pyramide (rapide, défaut) ou par les algorithmes d'inpainting d'OpenCV Telea ou Navier-Stokes. Un bruit gaussien de même niveau que le fond (estimé par MAD) est ajouté dans les zones remplies pour éviter les plages trop lisses. Le calque d'étoiles est la différence « image − image sans étoiles ».\n- **`stars_add`** : ré-ajoute ce calque d'étoiles à l'image courante, soit par addition exacte (sans étoiles + étoiles = original), soit en mode « screen » `1 − (1 − image)(1 − étoiles)`, qui évite de saturer les étoiles sur un fond éclairci. L'intensité est dosée par `amount`.\n- **`star_reduce`** : réduit les étoiles sous un masque d'étoiles (disques adoucis autour des étoiles détectées). Deux méthodes :\n  - `erosion` : minimum local (érosion morphologique à noyau elliptique, `iterations` passes, légèrement lissée), mélangé à l'image selon `amount` × masque ;\n  - `transfer` : méthode de Bill Blanshan, une courbe de transfert (MTF) appliquée à l'image et à un fond sans étoiles estimé par remplissage, qui rétrécit le profil des étoiles sans creuser le fond autour.\n  `protect_large` permet d'épargner les grosses étoiles saturées (`protect`) ou au contraire de ne traiter qu'elles (`only`).\n- **`halo_reduce`** : dans un anneau autour des étoiles les plus brillantes (disque extérieur de `radius_factor` × rayon isophote, moins le cœur de l'étoile), les pixels dont la teinte HSV est proche de `hue` sont désaturés (`amount`) et assombris (`darken`). Le poids décroît linéairement avec l'écart de teinte jusqu'à `hue_range`.\n\n## Utilité / quand l'utiliser\n\n- **Nébuleuses étendues (Vespera, Seestar, lunettes courtes)** : `starless` avant le traitement du fond (étirement plus fort, `saturation`, réduction du bruit, netteté), puis `stars_add` pour réintégrer des étoiles propres. Enchaînement conseillé : `starless` → traitement du fond → `stars_add`.\n- **Champs très denses (Voie lactée, amas)** : `star_reduce` rend les étoiles moins envahissantes et met en valeur la nébulosité. Préférez `transfer` pour un rendu naturel, `erosion` pour une action plus directe.\n- **Lunette à chromatisme (doublet ED, objectif non apochromatique)** : `halo_reduce` atténue les halos bleus/violets autour des étoiles brillantes. Visez `hue: 270` pour un halo violet, `240` pour un halo bleu.\n- **Quand ne pas l'utiliser** : sur une galaxie compacte où les étoiles sont peu nombreuses, `starless` apporte peu et peut laisser des traces ; évitez `star_reduce` fort sur des amas globulaires (le cœur de l'amas serait érodé). `halo_reduce` ne sert à rien sur une image monochrome (étape ignorée).\n- **Image linéaire ou étirée** : `star_reduce` et `halo_reduce` s'appliquent sur une image **étirée**. Placez de préférence `starless` **après** `stretch` : `stars_add` avertit si un calque pris sur l'image linéaire est ajouté à une image étirée (étoiles trop faibles).\n\n## Installation\n\n```\nastrostack plugin install stars-tools\n```\n\nOu depuis la vue **Plugins** de l'application CelestiaX. Aucune dépendance Python supplémentaire (`python_deps` vide) : le plugin utilise NumPy, OpenCV et SEP, déjà requis par le cœur astrostack.\n\n## Paramètres\n\n### `starless`\n\n| Nom | Type | Défaut | Description |\n|---|---|---|---|\n| `method` | choix (`pyramid`, `telea`, `ns`) | `pyramid` | Remplissage : pyramide (rapide), Telea, Navier-Stokes |\n| `threshold` | réel (1–50) | 2.5 | Seuil de détection des étoiles (× bruit) |\n| `grow` | réel (0–5) | 0.8 | Agrandissement du masque (× rayon isophote) |\n| `min_grow` | entier (0–20) | 2 | Agrandissement minimal (px) |\n| `max_radius` | réel (1–500), facultatif | vide | Ignore les objets plus gros (px) ; vide = aucune limite |\n| `noise` | booléen | `true` | Ajoute le bruit du fond dans les zones remplies |\n| `keep` | choix (`starless`, `stars`, `both`) | `starless` | Image gardée dans le pipeline : sans étoiles, calque d'étoiles seul, ou image inchangée (les deux fichiers sont sauvés) |\n\n### `stars_add`\n\n| Nom | Type | Défaut | Description |\n|---|---|---|---|\n| `mode` | choix (`add`, `screen`) | `add` | `add` : exact (sans étoiles + étoiles = original) ; `screen` : 1 − (1 − a)(1 − b) |\n| `amount` | réel (0–2) | 1.0 | Intensité des étoiles |\n| `file` | texte, facultatif | vide | Calque d'étoiles `.npy` ; vide = celui de l'étape `starless` |\n\n### `star_reduce`\n\n| Nom | Type | Défaut | Description |\n|---|---|---|---|\n| `method` | choix (`erosion`, `transfer`) | `erosion` | `erosion` : minimum local ; `transfer` : courbe de Bill Blanshan |\n| `amount` | réel (0–1) | 0.6 | Force de la réduction |\n| `iterations` | entier (1–5) | 1 | Nombre de passes |\n| `kernel` | entier impair (3–9) | 3 | Taille du noyau d'érosion (px) |\n| `threshold` | réel (1.5–50) | 3.0 | Seuil de détection des étoiles (× bruit) |\n| `mask_scale` | réel (0.5–5) | 1.5 | Rayon du masque (× rayon isophote) |\n| `soften` | réel (0–5) | 1.0 | Adoucissement du masque |\n| `protect_large` | choix (`none`, `protect`, `only`) | `none` | `protect` : épargne les grosses étoiles ; `only` : ne traite qu'elles |\n| `large_radius` | réel (1–200), facultatif | vide | Rayon (px) au-delà duquel une étoile est « grosse » ; vide = 3 × rayon médian |\n| `mask` | texte, facultatif | vide | Masque de post-traitement (voir ci-dessous) |\n\n### `halo_reduce`\n\n| Nom | Type | Défaut | Description |\n|---|---|---|---|\n| `amount` | réel (0–1) | 0.7 | Désaturation des halos |\n| `darken` | réel (0–1) | 0.3 | Atténuation de la luminance de l'anneau |\n| `radius_factor` | réel (1.2–10) | 3.0 | Rayon extérieur de l'anneau (× rayon isophote) |\n| `hue` | réel (0–360) | 250 | Teinte ciblée (degrés HSV : 240 bleu, 270 violet) |\n| `hue_range` | réel (5–180) | 60 | Tolérance de teinte (degrés) |\n| `bright_fraction` | réel (0.01–1) | 0.2 | Fraction des étoiles les plus brillantes traitées |\n| `threshold` | réel (1.5–50) | 5.0 | Seuil de détection des étoiles (× bruit) |\n| `mask` | texte, facultatif | vide | Masque de post-traitement (voir ci-dessous) |\n\n### Le paramètre `mask`\n\n`star_reduce` et `halo_reduce` acceptent les masques du cœur astrostack. Le masque (valeurs de 0 à 1) est calculé sur l'image avant l'étape ; le résultat vaut `avant × (1 − m) + après × m`. Forme courte (pratique dans l'application) ou dictionnaire YAML : `mask: \"luminance low=0.2 high=0.8 invert\"`, `mask: \"stars grow=2\"`, `mask: \"object feather=8 invert\"`, `mask: {type: combine, op: min, masks: [...]}`. Types disponibles : `luminance`, `color`, `stars`, `object`, `range`, `file`, `combine` ; options communes `invert`, `blur`, `strength`. Exemple : `mask: \"object invert\"` réduit les étoiles hors de la nébuleuse seulement.\n\n## Exemples YAML\n\nNébuleuse traitée sans étoiles, puis étoiles réintégrées en mode « screen » :\n\n```yaml\npipeline:\n  - stretch: {}\n  - starless: {method: pyramid, threshold: 2.5, grow: 0.8}\n  - saturation: {amount: 0.6}        # plugin color-tools\n  - stars_add: {mode: screen, amount: 0.9}\n```\n\nRéduction des étoiles d'un champ de Voie lactée, grosses étoiles épargnées :\n\n```yaml\npipeline:\n  - stretch: {}\n  - star_reduce: {method: transfer, amount: 0.5, protect_large: protect}\n```\n\nLunette à chromatisme, halo violet autour des étoiles brillantes :\n\n```yaml\npipeline:\n  - stretch: {}\n  - halo_reduce: {hue: 270, hue_range: 50, amount: 0.8, darken: 0.2, bright_fraction: 0.3}\n```\n\n## Sorties\n\n- `starless` : `ctx.image` devient l'image sans étoiles (`keep: starless`), le calque d'étoiles (`keep: stars`, valeurs négatives ramenées à 0) ou reste inchangée (`keep: both`). Fichiers `.work/stars_layer.npy` et `.work/starless.npy` ; leurs chemins sont dans les clés d'état `stars_layer` et `starless`. La clé `stars_layer_linear` indique si le calque a été pris avant l'étirement. Les deux images restent aussi en mémoire pour `stars_add`.\n- `stars_add` : `ctx.image` reçoit les étoiles (résultat borné à [0, 1] sur une image étirée). Étape ignorée avec un avertissement si aucun calque n'est disponible ou si ses dimensions diffèrent de l'image (par exemple après un recadrage entre les deux étapes).\n- `star_reduce`, `halo_reduce` : modifient `ctx.image` ; le nombre d'étoiles traitées est affiché dans la console. Les bords NaN de l'image sont préservés.\n\n## Limites\n\n- `starless` est un remplissage classique, sans IA : les très grosses étoiles saturées, leurs aigrettes et les étoiles posées sur une nébuleuse très structurée peuvent laisser des traces.\n- Les objets allongés (rapport b/a < 0,5 : galaxies, filaments) ne sont pas détectés comme étoiles, donc ni retirés ni réduits.\n- `halo_reduce` ne traite que les halos de teinte proche de `hue` ; un halo de diffraction neutre ou des reflets internes ne sont pas corrigés. Image couleur requise.\n- `star_reduce` en `erosion` avec un noyau large ou plusieurs passes peut produire des étoiles « carrées » ou des anneaux sombres ; préférez `transfer` pour les réductions fortes.\n- Toute opération géométrique (recadrage, rotation) entre `starless` et `stars_add` rend le calque incompatible.\n\n## Licences\n\n- Plugin : licence MIT, © Erwan Sturzenegger.\n- Dépendances (fournies par le cœur) : NumPy et SciPy (BSD), OpenCV (Apache 2.0), SEP (LGPL / BSD).\n","en":"# Star tools\n\nSeparate the stars from the background, process the nebula without them and put them back, shrink the stars and tame the coloured halos of refractors.\n\n## What it does\n\nThe plugin provides four post-processing stages (`pipeline:`) for astrostack (the CelestiaX application).\n\n- **`starless`**: removes the stars from the image. Stars are detected with SEP on the luminance (threshold in multiples of the noise), then each star is covered by its segmentation area, grown down to background level (a disc of radius `(1 + grow) × isophotal radius + min_grow`). The holes are filled with a pyramid fill (fast, default) or with OpenCV's Telea or Navier-Stokes inpainting. Gaussian noise matching the background level (estimated with the MAD) is added to the filled areas so they do not look too smooth. The star layer is the difference \"image − starless image\".\n- **`stars_add`**: adds this star layer back onto the current image, either by exact addition (starless + stars = original) or in \"screen\" mode `1 − (1 − image)(1 − stars)`, which avoids clipping the stars on a brightened background. The strength is set by `amount`.\n- **`star_reduce`**: shrinks the stars under a star mask (softened discs around the detected stars). Two methods:\n  - `erosion`: local minimum (morphological erosion with an elliptical kernel, `iterations` passes, slightly smoothed), blended into the image by `amount` × mask;\n  - `transfer`: Bill Blanshan's method, a transfer curve (MTF) applied to the image and to a star-free background estimated by filling, which narrows the star profiles without digging into the surrounding background.\n  `protect_large` spares the big saturated stars (`protect`) or, on the contrary, processes only them (`only`).\n- **`halo_reduce`**: in a ring around the brightest stars (outer disc of `radius_factor` × isophotal radius, minus the star core), pixels whose HSV hue is close to `hue` are desaturated (`amount`) and darkened (`darken`). The weight decreases linearly with the hue difference up to `hue_range`.\n\n## Why / when to use it\n\n- **Extended nebulae (Vespera, Seestar, short refractors)**: `starless` before processing the background (stronger stretch, `saturation`, noise reduction, sharpening), then `stars_add` to bring back clean stars. Recommended order: `starless` → background processing → `stars_add`.\n- **Very dense fields (Milky Way, clusters)**: `star_reduce` makes the stars less overwhelming and brings out the nebulosity. Prefer `transfer` for a natural look, `erosion` for a more direct effect.\n- **Refractor with chromatic aberration (ED doublet, non-apochromatic lens)**: `halo_reduce` reduces blue/purple halos around bright stars. Use `hue: 270` for a purple halo, `240` for a blue one.\n- **When not to use it**: on a compact galaxy with few stars, `starless` brings little and may leave artefacts; avoid a strong `star_reduce` on globular clusters (the cluster core would be eroded). `halo_reduce` is useless on a monochrome image (the stage is skipped).\n- **Linear or stretched image**: `star_reduce` and `halo_reduce` are meant for a **stretched** image. Preferably place `starless` **after** `stretch`: `stars_add` warns when a layer taken from the linear image is added to a stretched image (stars too faint).\n\n## Installation\n\n```\nastrostack plugin install stars-tools\n```\n\nOr from the **Plugins** view of the CelestiaX application. No extra Python dependency (`python_deps` is empty): the plugin uses NumPy, OpenCV and SEP, already required by the astrostack core.\n\n## Parameters\n\n### `starless`\n\n| Name | Type | Default | Description |\n|---|---|---|---|\n| `method` | choice (`pyramid`, `telea`, `ns`) | `pyramid` | Fill method: pyramid (fast), Telea, Navier-Stokes |\n| `threshold` | float (1–50) | 2.5 | Star detection threshold (× noise) |\n| `grow` | float (0–5) | 0.8 | Mask growth (× isophotal radius) |\n| `min_grow` | int (0–20) | 2 | Minimum growth (px) |\n| `max_radius` | float (1–500), optional | empty | Ignore larger objects (px); empty = no limit |\n| `noise` | bool | `true` | Add background noise in the filled areas |\n| `keep` | choice (`starless`, `stars`, `both`) | `starless` | Image kept in the pipeline: starless, star layer only, or unchanged image (both files are saved) |\n\n### `stars_add`\n\n| Name | Type | Default | Description |\n|---|---|---|---|\n| `mode` | choice (`add`, `screen`) | `add` | `add`: exact (starless + stars = original); `screen`: 1 − (1 − a)(1 − b) |\n| `amount` | float (0–2) | 1.0 | Star intensity |\n| `file` | text, optional | empty | Star layer `.npy` file; empty = the one from the `starless` stage |\n\n### `star_reduce`\n\n| Name | Type | Default | Description |\n|---|---|---|---|\n| `method` | choice (`erosion`, `transfer`) | `erosion` | `erosion`: local minimum; `transfer`: Bill Blanshan's curve |\n| `amount` | float (0–1) | 0.6 | Reduction strength |\n| `iterations` | int (1–5) | 1 | Number of passes |\n| `kernel` | odd int (3–9) | 3 | Erosion kernel size (px) |\n| `threshold` | float (1.5–50) | 3.0 | Star detection threshold (× noise) |\n| `mask_scale` | float (0.5–5) | 1.5 | Mask radius (× isophotal radius) |\n| `soften` | float (0–5) | 1.0 | Mask softening |\n| `protect_large` | choice (`none`, `protect`, `only`) | `none` | `protect`: spares big stars; `only`: processes only them |\n| `large_radius` | float (1–200), optional | empty | Radius (px) above which a star is \"big\"; empty = 3 × median radius |\n| `mask` | text, optional | empty | Post-processing mask (see below) |\n\n### `halo_reduce`\n\n| Name | Type | Default | Description |\n|---|---|---|---|\n| `amount` | float (0–1) | 0.7 | Halo desaturation |\n| `darken` | float (0–1) | 0.3 | Luminance reduction in the ring |\n| `radius_factor` | float (1.2–10) | 3.0 | Outer radius of the ring (× isophotal radius) |\n| `hue` | float (0–360) | 250 | Target hue (HSV degrees: 240 blue, 270 purple) |\n| `hue_range` | float (5–180) | 60 | Hue tolerance (degrees) |\n| `bright_fraction` | float (0.01–1) | 0.2 | Fraction of the brightest stars processed |\n| `threshold` | float (1.5–50) | 5.0 | Star detection threshold (× noise) |\n| `mask` | text, optional | empty | Post-processing mask (see below) |\n\n### The `mask` parameter\n\n`star_reduce` and `halo_reduce` accept the astrostack core masks. The mask (values from 0 to 1) is computed on the image before the stage; the result is `before × (1 − m) + after × m`. Short form (handy in the application) or YAML dictionary: `mask: \"luminance low=0.2 high=0.8 invert\"`, `mask: \"stars grow=2\"`, `mask: \"object feather=8 invert\"`, `mask: {type: combine, op: min, masks: [...]}`. Available types: `luminance`, `color`, `stars`, `object`, `range`, `file`, `combine`; common options `invert`, `blur`, `strength`. Example: `mask: \"object invert\"` reduces only the stars outside the nebula.\n\n## YAML examples\n\nNebula processed without stars, then stars added back in \"screen\" mode:\n\n```yaml\npipeline:\n  - stretch: {}\n  - starless: {method: pyramid, threshold: 2.5, grow: 0.8}\n  - saturation: {amount: 0.6}        # color-tools plugin\n  - stars_add: {mode: screen, amount: 0.9}\n```\n\nStar reduction on a Milky Way field, big stars spared:\n\n```yaml\npipeline:\n  - stretch: {}\n  - star_reduce: {method: transfer, amount: 0.5, protect_large: protect}\n```\n\nRefractor with chromatic aberration, purple halo around bright stars:\n\n```yaml\npipeline:\n  - stretch: {}\n  - halo_reduce: {hue: 270, hue_range: 50, amount: 0.8, darken: 0.2, bright_fraction: 0.3}\n```\n\n## Outputs\n\n- `starless`: `ctx.image` becomes the starless image (`keep: starless`), the star layer (`keep: stars`, negative values clipped to 0) or stays unchanged (`keep: both`). Files `.work/stars_layer.npy` and `.work/starless.npy`; their paths are stored in the `stars_layer` and `starless` state keys. The `stars_layer_linear` key records whether the layer was taken before stretching. Both images are also kept in memory for `stars_add`.\n- `stars_add`: `ctx.image` receives the stars (result clipped to [0, 1] on a stretched image). The stage is skipped with a warning if no layer is available or if its size differs from the image (for example after a crop between the two stages).\n- `star_reduce`, `halo_reduce`: modify `ctx.image`; the number of processed stars is printed in the console. NaN borders of the image are preserved.\n\n## Limitations\n\n- `starless` is a classic fill, without AI: very large saturated stars, their diffraction spikes and stars sitting on a highly structured nebula may leave artefacts.\n- Elongated objects (b/a ratio < 0.5: galaxies, filaments) are not detected as stars, so they are neither removed nor reduced.\n- `halo_reduce` only handles halos whose hue is close to `hue`; neutral diffraction halos or internal reflections are not corrected. A colour image is required.\n- `star_reduce` in `erosion` mode with a large kernel or several passes can produce \"square\" stars or dark rings; prefer `transfer` for strong reductions.\n- Any geometric operation (crop, rotation) between `starless` and `stars_add` makes the layer incompatible.\n\n## Licences\n\n- Plugin: MIT licence, © Erwan Sturzenegger.\n- Dependencies (provided by the core): NumPy and SciPy (BSD), OpenCV (Apache 2.0), SEP (LGPL / BSD).\n"}},{"id":"trail-mask","version":"1.0.0","name":{"fr":"Masque des traînées","en":"Trail mask"},"summary":{"fr":"Détecte les traînées de satellites et d'avions dans chaque pose et les exclut de l'empilement.","en":"Detects satellite and aircraft trails in each frame and excludes them from the stack."},"category":"calibration","tags":["satellites","trails","rejection"],"authors":["Erwan Sturzenegger"],"license":"MIT","homepage":"https://celestiax-plugins.sturzy.ch/plugins/trail-mask","min_astrostack":"0.1.0","entry":"celestiax_trail_mask","python_deps":[],"stages":[],"frame_ops":["trail_mask"],"ai":false,"models":[],"screenshots":[],"changelog":{"1.0.0":{"fr":"Version initiale (extraite du cœur d'astrostack)","en":"Initial release (extracted from the astrostack core)"}},"download":"https://celestiax-plugins.sturzy.ch/dl/trail-mask-1.0.0.zip","download_fallback":"https://raw.githubusercontent.com/erwansturzenegger/CelestiaX-Plugins/main/dist/trail-mask-1.0.0.zip","size":10465,"sha256":"6506acdf3698ece2511c29b155c347caa20f12fa7b49b1cbe4bf7655a9105299","readme":{"fr":"# Masque des traînées\n\nDétecte les traînées de satellites et d'avions dans chaque pose et les exclut de l'empilement en mettant les pixels concernés à NaN.\n\n## Fonction\n\nLe plugin fournit une opération par image (frame_op), `trail_mask`, exécutée en parallèle dans les workers, pose par pose, avant l'empilement.\n\nAlgorithme (détection classique, sans IA) :\n\n1. **Luminance réduite.** La pose est ramenée à une luminance (moyenne des canaux). Une pose CFA non dématricée est moyennée par blocs 2 × 2 ; une image dont le plus grand côté dépasse 4000 px est encore réduite d'un facteur 2, pour garder un calcul rapide.\n2. **Passe-haut et normalisation.** On retire un flou gaussien large (σ = 6 px) : le fond du ciel, les gradients et la pollution lumineuse disparaissent. Le résultat est exprimé en σ du bruit (estimation robuste par médiane et MAD), puis légèrement lissé pour renforcer les lignes fines.\n3. **Seuillage et tri des objets.** Les pixels au-dessus de `threshold` / 2 σ sont regroupés en objets connexes ; les objets compacts (étoiles) et épais (nébuleuses, halos d'étoiles brillantes) sont écartés, seuls les objets longs et fins sont conservés.\n4. **Transformée de Hough probabiliste** (OpenCV) sur ce qui reste, avec une longueur minimale de `min_length` × la plus grande dimension de l'image.\n5. **Validation par profil.** Pour chaque segment candidat, le signal médian le long de la ligne doit dépasser nettement (de `threshold` / 2 σ) celui de deux lignes parallèles voisines : cela élimine les faux positifs dus aux alignements fortuits d'étoiles ou aux bords de nébuleuses. Les segments quasi confondus avec une traînée déjà trouvée (angle < 3°, distance < 2 × `width`) sont fusionnés.\n6. **Prolongement jusqu'aux bords.** Les extrémités faibles d'une traînée échappent souvent à Hough : chaque traînée validée est suivie tronçon par tronçon (à ± 2 px près, pour tolérer un angle imparfait ou une légère courbure) tant que son profil reste significatif.\n7. **Masquage.** Les pixels des traînées (bande de `width` px) passent à NaN. L'empilement du cœur ignore les NaN : la zone est reconstituée à partir des autres poses.\n\nLe nombre de traînées détectées par pose est relevé pendant l'étape `quality` et apparaît dans la colonne `trails` de `quality.csv`.\n\n## Utilité / quand l'utiliser\n\n- **Séances sous les constellations de satellites** (Starlink, OneWeb…), très fréquentes en début et fin de nuit, surtout avec un champ large (Vespera, Seestar, lunette courte).\n- **Petits jeux de poses** (moins de 15 à 20 images) : le rejet sigma de l'empilement ne suffit pas toujours à effacer une traînée brillante ; la masquer en amont évite les résidus.\n- **Proximité d'un aéroport** : traînées d'avions et feux clignotants en pointillés, que le prolongement et la tolérance aux trous (`maxLineGap`) rattrapent.\n- **Poses longues** : chaque pose perdue coûte cher ; masquer une bande est préférable à rejeter toute l'image.\n\nÀ ne **pas** utiliser (ou avec prudence) :\n\n- sur la Lune, les planètes ou le Soleil (images sans étoiles avec de grands bords nets) ;\n- quand les poses sont très nombreuses (plusieurs centaines) et que le rejet sigma de `stack` élimine déjà proprement les traînées : le masque n'apporte alors qu'un peu de temps de calcul en plus ;\n- sur des champs remplis de structures filamentaires très fines et contrastées (bords des Dentelles du Cygne, jets) si des faux positifs apparaissent : augmenter `threshold` ou `min_length`.\n\n## Installation\n\n```bash\nastrostack plugin install trail-mask\n```\n\nOu depuis l'application : vue **Plugins**, fiche « Masque des traînées », bouton **Installer**.\n\nAucune dépendance Python supplémentaire : le plugin utilise NumPy et OpenCV, déjà requis par le cœur astrostack.\n\n## Paramètres\n\n### `trail_mask` (frame_op)\n\n| Paramètre | Type | Défaut | Description |\n|---|---|---|---|\n| `min_length` | réel (0,02 à 1) | `0.15` | Longueur minimale d'une traînée, en fraction de la plus grande dimension de l'image. |\n| `threshold` | réel (1 à 20) | `3.0` | Seuil de détection, en σ du bruit après lissage (plus haut = moins de détections, moins de faux positifs). |\n| `width` | entier (1 à 51) | `7` | Largeur de la bande masquée, en pixels de la pose. |\n| `max_trails` | entier (1 à 50) | `10` | Nombre maximal de traînées retenues par image. |\n\nPas de paramètre `mask` : il s'agit d'une opération par image, et non d'une étape de post-traitement.\n\n## Exemples YAML\n\nPlacement conseillé : **à la fin de `frame_ops`**, après `calibrate`, `cosmetic` et `debayer` (et `banding` s'il est utilisé).\n\n```yaml\nframe_ops:\n  - calibrate\n  - cosmetic: {auto: true}\n  - debayer: {method: bilinear}\n  - trail_mask: {}\n```\n\nTraînées faibles et larges (téléobjectif, poses longues) :\n\n```yaml\nframe_ops:\n  - calibrate\n  - cosmetic: {auto: true}\n  - debayer: {method: rcd}\n  - trail_mask: {threshold: 2.5, width: 11, min_length: 0.1}\n```\n\nChamp riche en filaments, réglage prudent contre les faux positifs :\n\n```yaml\nframe_ops:\n  - calibrate\n  - debayer: {}\n  - trail_mask: {threshold: 5.0, min_length: 0.3, max_trails: 5}\n```\n\n## Sorties\n\n- Aucun fichier écrit : les pixels masqués passent à NaN dans l'image transmise à l'empilement (et au drizzle).\n- `ctx.state[\"trails\"]` : nombre de traînées détectées par pose (`{\"<index>\": n}`), rempli par l'étape `quality` lorsque `trail_mask` fait partie des `frame_ops`.\n- `quality.csv` : colonne `trails` (nombre par pose), visible aussi dans la vue **Qualité**.\n- Pas de checkpoint (opération par image).\n\n## Limites\n\n- Détection rectiligne : les traînées courbes (avions en virage, très longues poses en grand champ distordu) ne sont suivies que localement.\n- Une traînée très faible, sous le seuil du bruit d'une pose isolée, n'est pas détectée (le rejet sigma de l'empilement reste alors le filet de sécurité).\n- Le masque est une bande de largeur fixe : le halo diffus d'une traînée très brillante peut déborder ; augmenter `width`.\n- Faux positifs possibles sur des structures linéaires réelles (bords de nébuleuses, jets, arêtes de diffraction très longues d'une étoile brillante) : ils coûtent seulement un peu de signal sur la pose concernée.\n- Si la même zone est masquée sur toutes les poses (objet linéaire réel pris pour une traînée), elle reste vide (NaN) dans l'empilement.\n- Coût : une détection complète par pose (sur une image réduite pour les CFA et les grands capteurs), exécutée en parallèle dans les workers ; elle est refaite à chaque relecture des poses (mesure de qualité, passes d'empilement en streaming).\n\n## Licences\n\n- Plugin : licence MIT, © Erwan Sturzenegger.\n- Dépendances (fournies par le cœur astrostack) : NumPy (BSD-3-Clause), OpenCV (`opencv-python-headless`, Apache 2.0 pour OpenCV ≥ 4.5 ; le paquet pip contient aussi des bibliothèques tierces sous leurs propres licences).\n","en":"# Trail mask\n\nDetects satellite and aircraft trails in each frame and excludes them from the stack by setting the affected pixels to NaN.\n\n## What it does\n\nThe plugin provides one per-frame operation (frame_op), `trail_mask`, run in parallel in the workers, frame by frame, before stacking.\n\nAlgorithm (classical detection, no AI):\n\n1. **Reduced luminance.** The frame is reduced to a luminance (mean of the channels). A non-debayered CFA frame is averaged over 2 × 2 blocks; an image whose longest side exceeds 4000 px is further downsampled by 2, to keep the computation fast.\n2. **High-pass and normalisation.** A wide Gaussian blur (σ = 6 px) is subtracted: sky background, gradients and light pollution disappear. The result is expressed in noise σ (robust median/MAD estimate), then slightly smoothed to strengthen thin lines.\n3. **Thresholding and object sorting.** Pixels above `threshold` / 2 σ are grouped into connected objects; compact objects (stars) and thick ones (nebulae, halos of bright stars) are discarded, only long, thin objects are kept.\n4. **Probabilistic Hough transform** (OpenCV) on what remains, with a minimum length of `min_length` × the longest image dimension.\n5. **Profile validation.** For each candidate segment, the median signal along the line must clearly exceed (by `threshold` / 2 σ) that of two neighbouring parallel lines: this removes false positives caused by chance star alignments or nebula edges. Segments almost identical to an already found trail (angle < 3°, distance < 2 × `width`) are merged.\n6. **Extension to the edges.** The faint ends of a trail often escape the Hough transform: each validated trail is followed chunk by chunk (within ± 2 px, to tolerate an imperfect angle or a slight curvature) as long as its profile remains significant.\n7. **Masking.** Trail pixels (a band `width` px wide) are set to NaN. The core stacking engine ignores NaN: the area is rebuilt from the other frames.\n\nThe number of trails detected per frame is recorded during the `quality` stage and appears in the `trails` column of `quality.csv`.\n\n## When to use it\n\n- **Sessions under satellite constellations** (Starlink, OneWeb…), very common at the beginning and end of the night, especially with a wide field (Vespera, Seestar, short refractor).\n- **Small frame sets** (fewer than 15 to 20 frames): the stack's sigma rejection does not always erase a bright trail; masking it beforehand avoids residuals.\n- **Near an airport**: aircraft trails and dotted blinking lights, which the extension step and the gap tolerance (`maxLineGap`) catch.\n- **Long exposures**: every lost frame is costly; masking a band is better than rejecting the whole image.\n\nDo **not** use it (or use it with care):\n\n- on the Moon, planets or the Sun (starless images with large sharp edges);\n- when frames are very numerous (several hundred) and the sigma rejection of `stack` already removes trails cleanly: the mask then only adds a little computing time;\n- on fields full of very thin, high-contrast filaments (edges of the Veil Nebula, jets) if false positives appear: raise `threshold` or `min_length`.\n\n## Installation\n\n```bash\nastrostack plugin install trail-mask\n```\n\nOr from the application: **Plugins** view, \"Trail mask\" page, **Install** button.\n\nNo additional Python dependency: the plugin uses NumPy and OpenCV, already required by the astrostack core.\n\n## Parameters\n\n### `trail_mask` (frame_op)\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `min_length` | float (0.02 to 1) | `0.15` | Minimum trail length, as a fraction of the longest image dimension. |\n| `threshold` | float (1 to 20) | `3.0` | Detection threshold, in noise σ after smoothing (higher = fewer detections, fewer false positives). |\n| `width` | integer (1 to 51) | `7` | Width of the masked band, in frame pixels. |\n| `max_trails` | integer (1 to 50) | `10` | Maximum number of trails kept per image. |\n\nNo `mask` parameter: this is a per-frame operation, not a post-processing stage.\n\n## YAML examples\n\nRecommended position: **at the end of `frame_ops`**, after `calibrate`, `cosmetic` and `debayer` (and `banding` if used).\n\n```yaml\nframe_ops:\n  - calibrate\n  - cosmetic: {auto: true}\n  - debayer: {method: bilinear}\n  - trail_mask: {}\n```\n\nFaint, wide trails (telephoto lens, long exposures):\n\n```yaml\nframe_ops:\n  - calibrate\n  - cosmetic: {auto: true}\n  - debayer: {method: rcd}\n  - trail_mask: {threshold: 2.5, width: 11, min_length: 0.1}\n```\n\nFilament-rich field, cautious settings against false positives:\n\n```yaml\nframe_ops:\n  - calibrate\n  - debayer: {}\n  - trail_mask: {threshold: 5.0, min_length: 0.3, max_trails: 5}\n```\n\n## Outputs\n\n- No file written: masked pixels are set to NaN in the image passed to stacking (and drizzle).\n- `ctx.state[\"trails\"]`: number of trails detected per frame (`{\"<index>\": n}`), filled by the `quality` stage when `trail_mask` is part of `frame_ops`.\n- `quality.csv`: `trails` column (count per frame), also shown in the **Quality** view.\n- No checkpoint (per-frame operation).\n\n## Limitations\n\n- Straight-line detection: curved trails (banking aircraft, very long exposures in a distorted wide field) are only followed locally.\n- A very faint trail, below the noise level of a single frame, is not detected (the stack's sigma rejection then remains the safety net).\n- The mask is a fixed-width band: the diffuse glow of a very bright trail may spill over; increase `width`.\n- False positives are possible on real linear structures (nebula edges, jets, very long diffraction spikes of a bright star): they only cost a little signal on the affected frame.\n- If the same area is masked on every frame (a real linear object mistaken for a trail), it remains empty (NaN) in the stack.\n- Cost: one full detection per frame (on a downsampled image for CFA data and large sensors), run in parallel in the workers; it is repeated each time the frames are re-read (quality measurement, streaming stack passes).\n\n## Licences\n\n- Plugin: MIT licence, © Erwan Sturzenegger.\n- Dependencies (provided by the astrostack core): NumPy (BSD-3-Clause), OpenCV (`opencv-python-headless`, Apache 2.0 for OpenCV ≥ 4.5; the pip package also bundles third-party libraries under their own licences).\n"}}]}