Carte de profondeur pour des planches qui suivent les volumes

La profondeur de la scène est estimée à partir de la photo (MiDaS small
ou Depth Anything V2 Small) et mélangée aux gris : les planches suivent
les volumes du sujet plutôt que ses lumières et ses ombres.

- Onglet « Profondeur » : part de la carte de profondeur, modèle, et
  détails fins de la photo gravés dans la profondeur (yeux, bouche).
- Répartition des niveaux : rapproche les planches d'aires égales quand
  les valeurs sont tassées sur quelques gris.
- Images 16 bits lues sur toute leur plage (elles étaient écrêtées à 255).
- Le Python d'Inkscape (MinGW, sans pip) ne peut pas charger onnxruntime :
  le calcul tourne dans un environnement à part, installé par
  deploy.ps1 -Depth, lancé en sous-processus, résultat gardé en cache.
- Depth Anything sur la carte graphique (DirectML) avec repli sur le
  processeur ; MiDaS small toujours sur le processeur, DirectML lui
  faisant rendre une carte fausse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AumyrbcuQobB3GbPrFjG9i
This commit is contained in:
AlexandClaude Opus 5.5 committed 2026-10-04 14:19:26 +02:00
1 parent 16589716fd
commit 3ed0fa0987
13 files changed
+1090 -37

No files matched your search

+100 -15
View File
@@ -11,6 +11,7 @@ La logique vit dans `gray_iso_layers_core`, sans dependance a inkex.
"""
import base64
import hashlib
import io
import os
import sys
@@ -25,8 +26,16 @@ from inkex.localization import localize
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from gray_iso_layers_core import ( # noqa: E402
gray_to_hex, iso_boards, lines_to_d, parse_color, rings_to_d, scale_lines,
scale_rings)
add_detail, blend_fields, gray_to_hex, guided_filter, iso_boards, lines_to_d, normalize,
parse_color, rings_to_d, scale_lines, scale_rings)
from gray_iso_layers_depth import DepthUnavailable, depth_field # noqa: E402
# Modes Pillow a plus de 8 bits par canal (carte de profondeur en 16 bits).
_DEEP_MODES = ("I", "F")
# Grand cote de l'image envoyee au calcul de profondeur : les modeles
# travaillent a 518 points au plus.
_DEPTH_SIZE = 768
# Installe _() dans les builtins : catalogue « grayisolayers » de la langue
# de l'interface (Inkscape transmet domaine et dossier par l'environnement),
@@ -43,6 +52,7 @@ class GrayIsoLayers(inkex.EffectExtension):
# Un argument par <param> du .inx, memes noms et memes valeurs par defaut.
pars.add_argument("--tab", default="levels")
pars.add_argument("--levels", type=int, default=16)
pars.add_argument("--equalize", type=float, default=0.0)
pars.add_argument("--shapes", default="light")
pars.add_argument("--mark", type=inkex.Boolean, default=True)
pars.add_argument("--blur", type=float, default=1.0)
@@ -51,6 +61,9 @@ class GrayIsoLayers(inkex.EffectExtension):
pars.add_argument("--min_area", type=float, default=0.02)
pars.add_argument("--simplify", type=float, default=0.4)
pars.add_argument("--smooth", type=inkex.Boolean, default=True)
pars.add_argument("--depth_mix", type=float, default=0.0)
pars.add_argument("--depth_model", default="midas_small")
pars.add_argument("--depth_detail", type=float, default=100.0)
pars.add_argument("--fill_mode", default="gray")
pars.add_argument("--fill_color", default="4294967295")
pars.add_argument("--stroke_width", type=float, default=0.2)
@@ -93,12 +106,15 @@ class GrayIsoLayers(inkex.EffectExtension):
"""Traite une image : calcul dans gray_iso_layers_core, ecriture dans le SVG."""
opt = self.options
try:
field = self.load_field(image, opt.resolution)
picture, digest = self.load_picture(image)
field = self.gray_field(picture, opt.resolution)
except Exception as error: # fichier absent, format inconnu, lien casse...
inkex.errormsg(_("Cannot read the image '{}' ({}). Embed it in the "
"document (right-click > Embed Image) or check its "
"link.").format(image.get_id(), error))
return
if opt.depth_mix > 0:
field = self.add_depth(image, picture, digest, field)
rows, cols = field.shape
boards = iso_boards(
@@ -107,7 +123,8 @@ class GrayIsoLayers(inkex.EffectExtension):
preserve_edges=opt.edges,
min_area=opt.min_area / 100.0,
tolerance=opt.simplify,
shapes=opt.shapes)
shapes=opt.shapes,
equalize=opt.equalize / 100.0)
if sum(1 for board in boards if board[2]) < 2:
inkex.errormsg(_("The image '{}' is uniform: only the base level has "
"a shape. Reduce the smoothing or pick a more "
@@ -200,36 +217,104 @@ class GrayIsoLayers(inkex.EffectExtension):
width, height = fitted_width, fitted_height
return left, top, width, height
def load_field(self, image, resolution):
"""Lit le bitmap et renvoie ses gris (0 noir, 1 blanc) en tableau 2D,
ramene a `resolution` points sur son grand cote."""
def add_depth(self, image, picture, digest, field):
"""Melange aux gris `field` la profondeur estimee de l'image, dans la
proportion `depth_mix`. Si elle ne peut pas etre calculee, le dit et
rend les gris seuls."""
import numpy
from PIL import Image
opt = self.options
try:
depth = depth_field(self.color_picture(picture), digest, opt.depth_model)
except DepthUnavailable as error:
inkex.errormsg(_("No depth map for the image '{}' ({}). Install the "
"depth models with 'deploy.ps1 -Depth'. The grays "
"of the image are used alone.").format(
image.get_id(), error))
return field
rows, cols = field.shape
depth = Image.fromarray(numpy.asarray(depth, dtype=numpy.float32))
depth = normalize(numpy.asarray(depth.resize((cols, rows), Image.BICUBIC),
dtype=float))
# La carte sort du modele en basse resolution : ses bords flous sont
# recales sur ceux de la photo.
depth = guided_filter(field, depth, max(2, int(round(max(rows, cols) / 100.0))))
# Les yeux et la bouche, absents de la profondeur, viennent des gris.
depth = add_detail(depth, field, opt.depth_detail / 100.0,
max(rows, cols) / 40.0)
return blend_fields(field, depth, opt.depth_mix / 100.0)
def load_picture(self, image):
"""Lit le bitmap : `(image PIL, empreinte de ses octets)`."""
from PIL import Image
href = image.get("xlink:href") or image.get("href") or ""
if href.startswith("data:"):
header, _sep, payload = href.partition(",")
data = base64.b64decode(payload) if ";base64" in header \
else unquote_to_bytes(payload)
source = io.BytesIO(data)
else:
if href.startswith("file:"):
path = url2pathname(urlparse(href).path)
else:
path = unquote(href)
# Lien relatif : il part du dossier du document.
source = self.absolute_href(path)
with open(self.absolute_href(path), "rb") as handle:
data = handle.read()
picture = Image.open(io.BytesIO(data))
picture.load()
return picture, hashlib.sha1(data).hexdigest()
with Image.open(source) as picture:
# La transparence se lit comme du blanc (fond de page).
rgba = picture.convert("RGBA")
white = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
gray = Image.alpha_composite(white, rgba).convert("L")
@staticmethod
def gray_picture(picture):
"""Gris de l'image, en image PIL : mode « L » (0 a 255), ou « F »
(0 a 1) pour une image a plus de 8 bits par canal."""
import numpy
from PIL import Image
if picture.mode.startswith(_DEEP_MODES):
# Carte de profondeur en 16 bits : Pillow l'ecreterait a 255 en la
# convertissant, on l'etire nous-memes sur 0..1.
values = normalize(numpy.asarray(picture, dtype=float))
return Image.fromarray(values.astype(numpy.float32))
# La transparence se lit comme du blanc (fond de page).
rgba = picture.convert("RGBA")
white = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
return Image.alpha_composite(white, rgba).convert("L")
@classmethod
def gray_field(cls, picture, resolution):
"""Gris de l'image (0 noir, 1 blanc) en tableau 2D, ramene a
`resolution` points sur son grand cote."""
import numpy
from PIL import Image
gray = cls.gray_picture(picture)
zoom = resolution / float(max(gray.size))
size = (max(2, int(round(gray.width * zoom))),
max(2, int(round(gray.height * zoom))))
gray = gray.resize(size, Image.LANCZOS)
return numpy.asarray(gray, dtype=float) / 255.0
scale = 1.0 if gray.mode == "F" else 255.0
return numpy.asarray(gray, dtype=float) / scale
@classmethod
def color_picture(cls, picture):
"""Image RGB envoyee au calcul de profondeur, transparence en blanc,
reduite a `_DEPTH_SIZE` points sur son grand cote."""
import numpy
from PIL import Image
if picture.mode.startswith(_DEEP_MODES):
gray = numpy.asarray(cls.gray_picture(picture), dtype=float)
color = Image.fromarray((gray * 255.0).round().astype(numpy.uint8))
color = color.convert("RGB")
else:
rgba = picture.convert("RGBA")
white = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
color = Image.alpha_composite(white, rgba).convert("RGB")
color.thumbnail((_DEPTH_SIZE, _DEPTH_SIZE), Image.LANCZOS)
return color
if __name__ == "__main__":