406 lines
20 KiB
Python
406 lines
20 KiB
Python
#!/usr/bin/env python3
|
|
# coding=utf-8
|
|
"""
|
|
Extension Inkscape : importe la photo d'une planche posee sur la surface de
|
|
travail d'une decoupeuse laser, a l'echelle exacte de la zone de travail.
|
|
|
|
Les 4 reperes de calibration (voir « Board photo: print calibration markers ») sont
|
|
detectes sur la photo, qui est redressee par homographie puis inseree sur la
|
|
page (1 mm photo = 1 mm document) ; le contour de la planche et ses trous
|
|
sont vectorises. Si la detection echoue, la photo brute est inseree avec 4
|
|
viseurs a poser sur les reperes : on relance alors l'extension sur cette
|
|
selection (calibration manuelle).
|
|
|
|
Traitement d'image dans board_photo_vision, geometrie dans board_photo_core,
|
|
sans dependance a inkex.
|
|
"""
|
|
|
|
import base64
|
|
import os
|
|
import sys
|
|
from urllib.parse import unquote, urlparse
|
|
|
|
import inkex
|
|
from inkex.localization import localize
|
|
|
|
# L'extension vit dans son propre sous-dossier des extensions Inkscape, qui
|
|
# n'est pas forcement dans sys.path : on l'y ajoute pour trouver ses modules.
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
import board_photo_common as common # noqa: E402
|
|
import board_photo_core as core # noqa: E402
|
|
import board_photo_remote as remote # noqa: E402
|
|
import board_photo_vision as vision # noqa: E402
|
|
|
|
# Installe _() dans les builtins : catalogue « board_photo » de la langue
|
|
# de l'interface (Inkscape transmet domaine et dossier par l'environnement),
|
|
# textes anglais d'origine sinon.
|
|
localize()
|
|
|
|
# Au-dela, la taille mesuree des reperes trahit une erreur de reglage
|
|
# (positions ou taille des reperes) ou une mauvaise detection.
|
|
MARKER_SIZE_TOLERANCE = 0.05
|
|
|
|
|
|
class BoardPhotoImport(inkex.EffectExtension):
|
|
"""Photo calibree + contour vectorise de la planche, sur des calques dedies."""
|
|
|
|
def add_arguments(self, pars):
|
|
# Un argument par <param> du .inx, memes noms et memes valeurs par defaut.
|
|
pars.add_argument("--tab", default="work_area")
|
|
pars.add_argument("--work_width", type=float, default=400.0)
|
|
pars.add_argument("--work_height", type=float, default=400.0)
|
|
pars.add_argument("--origin_x", type=float, default=30.0)
|
|
pars.add_argument("--origin_y", type=float, default=30.0)
|
|
pars.add_argument("--spacing_x", type=float, default=340.0)
|
|
pars.add_argument("--spacing_y", type=float, default=340.0)
|
|
pars.add_argument("--marker_size", type=float, default=20.0)
|
|
pars.add_argument("--marker_placement", default="corners")
|
|
pars.add_argument("--set_page", type=inkex.Boolean, default=True)
|
|
pars.add_argument("--photo_source", default="file")
|
|
pars.add_argument("--photo", default="")
|
|
pars.add_argument("--remote_host", default="")
|
|
pars.add_argument("--remote_port", type=int, default=5000)
|
|
pars.add_argument("--remote_endpoint", default="capture")
|
|
pars.add_argument("--remote_rotation", type=int, default=0)
|
|
pars.add_argument("--remote_timeout", type=int, default=20)
|
|
pars.add_argument("--resolution", type=float, default=4.0)
|
|
pars.add_argument("--jpeg_quality", type=int, default=85)
|
|
pars.add_argument("--vectorize", type=inkex.Boolean, default=True)
|
|
pars.add_argument("--board_tone", default="lighter")
|
|
pars.add_argument("--threshold", type=int, default=0)
|
|
pars.add_argument("--smoothing", type=float, default=0.5)
|
|
pars.add_argument("--min_hole_area", type=float, default=4.0)
|
|
pars.add_argument("--simplify", type=float, default=0.3)
|
|
pars.add_argument("--outline_color", default="426885887")
|
|
|
|
# ------------------------------------------------------------------
|
|
# Point d'entree
|
|
# ------------------------------------------------------------------
|
|
|
|
def effect(self):
|
|
opt = self.options
|
|
self.notes = []
|
|
if opt.marker_placement == "corners":
|
|
# Pieces de papier aux angles du nid d'abeille : positions deduites.
|
|
opt.origin_x, opt.origin_y, opt.spacing_x, opt.spacing_y = \
|
|
core.corner_layout(opt.work_width, opt.work_height, opt.marker_size)
|
|
problems = core.layout_problems(opt.work_width, opt.work_height, opt.origin_x,
|
|
opt.origin_y, opt.spacing_x, opt.spacing_y,
|
|
opt.marker_size)
|
|
if "non_positive" in problems:
|
|
inkex.errormsg(_("Work area, marker spacing and marker size must be "
|
|
"strictly positive."))
|
|
return
|
|
# Des reperes autour de la zone de travail (hors de portee de la laser)
|
|
# calibrent aussi bien la photo : seule leur gravure l'interdit
|
|
# (« print calibration markers »).
|
|
|
|
selection = list(self.svg.selection.values())
|
|
if selection:
|
|
found = self.manual_points(selection)
|
|
if found is None:
|
|
return
|
|
photo, points, oriented, manual_layer = found
|
|
areas = None
|
|
else:
|
|
photo = self.open_photo()
|
|
if photo is None:
|
|
return
|
|
gray = vision.gray_array(photo)
|
|
try:
|
|
detected = vision.detect_markers(gray)
|
|
except vision.MarkerError as error:
|
|
self.insert_manual(photo, error)
|
|
return
|
|
points, oriented, areas = (detected["points"], detected["oriented"],
|
|
detected["areas"])
|
|
manual_layer = None
|
|
|
|
self.calibrate(photo, points, oriented, areas)
|
|
if manual_layer is not None:
|
|
manual_layer.delete()
|
|
|
|
# ------------------------------------------------------------------
|
|
# Sources de la photo
|
|
# ------------------------------------------------------------------
|
|
|
|
def open_photo(self):
|
|
if self.options.photo_source == "remote":
|
|
return self.remote_photo()
|
|
path = (self.options.photo or "").strip()
|
|
if not path:
|
|
inkex.errormsg(_("Choose the photo of the board in the \"Photo\" tab "
|
|
"(or select a photo and 4 markers for a manual "
|
|
"calibration)."))
|
|
return None
|
|
if not os.path.isfile(path):
|
|
inkex.errormsg(_("Photo not found: {}").format(path))
|
|
return None
|
|
try:
|
|
return vision.load_photo(path)
|
|
except (OSError, ValueError):
|
|
inkex.errormsg(_("This file cannot be read as an image: {}").format(path))
|
|
return None
|
|
|
|
def remote_photo(self):
|
|
"""Photo demandee au serveur de capture de la machine distante."""
|
|
opt = self.options
|
|
try:
|
|
url = remote.remote_url(opt.remote_host, opt.remote_port, opt.remote_endpoint)
|
|
data = remote.fetch_photo(url, opt.remote_timeout)
|
|
except remote.RemoteError as error:
|
|
messages = {
|
|
"no_host": _("Enter the address of the remote machine in the "
|
|
"\"Photo\" tab (for example 192.168.1.20)."),
|
|
"bad_host": _("Invalid remote address: {}"),
|
|
"unreachable": _("The remote machine cannot be reached ({}): check "
|
|
"its address, that the capture server is running "
|
|
"and that the port is open."),
|
|
"timeout": _("The remote machine did not answer in time ({}): "
|
|
"increase the timeout or check the network."),
|
|
"interrupted": _("The transfer of the photo was interrupted ({}), "
|
|
"even after a second attempt: check the network "
|
|
"and try again."),
|
|
"http": _("The capture server returned an error: {}"),
|
|
"not_image": _("The capture server did not return an image: {}"),
|
|
"too_large": _("The image returned by the capture server is too "
|
|
"large ({})."),
|
|
}
|
|
message = messages.get(error.reason, _("Remote capture failed: {}"))
|
|
inkex.errormsg(message.format(error.detail or error.reason))
|
|
return None
|
|
try:
|
|
photo = vision.load_photo(data)
|
|
except (OSError, ValueError):
|
|
inkex.errormsg(_("The capture server did not return a readable image "
|
|
"({}).").format(url))
|
|
return None
|
|
# Camera montee de travers : on tourne la photo avant la detection,
|
|
# pour que l'image inseree en cas d'echec soit deja dans le bon sens.
|
|
photo = vision.rotate_photo(photo, opt.remote_rotation)
|
|
self.notes.append(_("Photo received from {} ({} x {} px).").format(
|
|
url, photo.width, photo.height))
|
|
return photo
|
|
|
|
def image_photo(self, image):
|
|
"""Contenu d'un element <image> : donnees incorporees ou fichier lie."""
|
|
href = image.get("xlink:href") or image.get("href") or ""
|
|
try:
|
|
if href.startswith("data:"):
|
|
return vision.load_photo(base64.b64decode(href.split(",", 1)[1]))
|
|
if href.startswith("file:"):
|
|
href = unquote(urlparse(href).path).lstrip("/") if os.name == "nt" \
|
|
else unquote(urlparse(href).path)
|
|
return vision.load_photo(self.absolute_href(href))
|
|
except (OSError, ValueError, IndexError):
|
|
return None
|
|
|
|
def manual_points(self, selection):
|
|
"""Calibration manuelle : une photo et 4 viseurs poses sur les reperes."""
|
|
images = [e for e in selection if isinstance(e, inkex.Image)]
|
|
others = [e for e in selection if not isinstance(e, inkex.Image)]
|
|
if len(images) != 1 or len(others) != 4:
|
|
inkex.errormsg(_("Manual calibration: select the photo and exactly 4 "
|
|
"small shapes centred on the markers (for example "
|
|
"Ctrl+A in the \"Manual calibration\" layer). "
|
|
"Deselect everything to import a new photo."))
|
|
return None
|
|
image = images[0]
|
|
photo = self.image_photo(image)
|
|
if photo is None:
|
|
inkex.errormsg(_("The selected image cannot be read (embed it, or "
|
|
"check that the linked file still exists)."))
|
|
return None
|
|
|
|
# Du document vers les pixels de la photo, a travers la transformation
|
|
# de l'image et de ses parents.
|
|
to_local = -image.composed_transform()
|
|
x = common.length_uu(self.svg, image.get("x"))
|
|
y = common.length_uu(self.svg, image.get("y"))
|
|
width = common.length_uu(self.svg, image.get("width"))
|
|
height = common.length_uu(self.svg, image.get("height"))
|
|
if width <= 0 or height <= 0:
|
|
inkex.errormsg(_("The selected image has no size."))
|
|
return None
|
|
points = []
|
|
for elem in others:
|
|
local = to_local.apply_to_point(common.center_of(elem))
|
|
points.append(((local.x - x) * photo.width / width,
|
|
(local.y - y) * photo.height / height))
|
|
dots = vision.dots_near(vision.gray_array(photo), points)
|
|
ordered = vision.orient_points(points, [d or 0 for d in dots])
|
|
layer = image.getparent()
|
|
manual_layer = layer if layer is not None and layer.get(common.DATA) == "manual" \
|
|
else None
|
|
return photo, ordered["points"], ordered["oriented"], manual_layer
|
|
|
|
def insert_manual(self, photo, error):
|
|
"""Detection impossible : photo brute + 4 viseurs a poser sur les reperes."""
|
|
opt = self.options
|
|
scale, ox, oy = common.prepare_page(self.svg, opt.work_width, opt.work_height,
|
|
opt.set_page)
|
|
common.remove_layers(self.svg, "manual")
|
|
layer = common.paint_layer(common.new_layer(_("Manual calibration"), "manual"),
|
|
stroke=common.TARGET_COLOR)
|
|
self.svg.add(layer)
|
|
common.set_current_layer(self.svg, layer)
|
|
|
|
# Photo ajustee a la page, proportions conservees.
|
|
fit = min(opt.work_width / photo.width, opt.work_height / photo.height)
|
|
width, height = photo.width * fit * scale, photo.height * fit * scale
|
|
image = self.make_image(photo, ox, oy, width, height)
|
|
layer.add(image)
|
|
|
|
# Viseurs vers les coins de la photo, a deplacer sur les reperes.
|
|
radius = opt.marker_size * 0.4 * scale
|
|
for fx, fy in ((0.1, 0.1), (0.9, 0.1), (0.9, 0.9), (0.1, 0.9)):
|
|
layer.add(common.target(ox + fx * width, oy + fy * height, radius, scale,
|
|
_("Marker target")))
|
|
|
|
reason = {"none": _("no dark shape found"),
|
|
"too_few": _("{} marker(s) found out of 4").format(error.found),
|
|
"layout": _("the markers found do not form a rectangle")}
|
|
inkex.errormsg(_("Automatic marker detection failed ({}).").format(
|
|
reason.get(error.reason, error.reason)))
|
|
inkex.errormsg(_("The raw photo was placed in the \"Manual calibration\" "
|
|
"layer with 4 red targets: move each target onto the "
|
|
"centre of a marker (zoom in), select the layer "
|
|
"content (Ctrl+A) and run this extension again."))
|
|
|
|
# ------------------------------------------------------------------
|
|
# Calibration et calques
|
|
# ------------------------------------------------------------------
|
|
|
|
def calibrate(self, photo, points, oriented, areas):
|
|
opt = self.options
|
|
targets = core.marker_layout(opt.work_height, opt.origin_x, opt.origin_y,
|
|
opt.spacing_x, opt.spacing_y)
|
|
if not core.is_convex_quad(points):
|
|
inkex.errormsg(_("The 4 marker positions do not form a convex "
|
|
"quadrilateral: check them and try again."))
|
|
return
|
|
try:
|
|
matrix = core.homography(points, targets)
|
|
except ValueError:
|
|
inkex.errormsg(_("The 4 marker positions are aligned: check them "
|
|
"and try again."))
|
|
return
|
|
|
|
warnings = []
|
|
if not oriented:
|
|
warnings.append(_("The origin marker (two dots) was not recognised: "
|
|
"the photo is assumed upright (origin at the "
|
|
"bottom left of the photo)."))
|
|
if areas:
|
|
sizes = [(area ** 0.5) * core.local_scale(matrix, point)
|
|
for area, point in zip(areas, points)]
|
|
worst = max(sizes, key=lambda s: abs(s - opt.marker_size))
|
|
if abs(worst - opt.marker_size) > MARKER_SIZE_TOLERANCE * opt.marker_size:
|
|
warnings.append(_("A marker measures {:.1f} mm instead of {:.1f} mm: "
|
|
"check the marker positions and size in the "
|
|
"\"Work area\" tab.").format(worst, opt.marker_size))
|
|
|
|
# Photo agrandie autour de la zone de travail pour montrer les reperes
|
|
# colles autour ; la planche n'est cherchee que dans la zone de travail.
|
|
extent = core.photo_extent(opt.work_width, opt.work_height, opt.origin_x,
|
|
opt.origin_y, opt.spacing_x, opt.spacing_y,
|
|
opt.marker_size, opt.resolution)
|
|
rectified, valid = vision.rectify(photo, matrix, extent[2] - extent[0],
|
|
extent[3] - extent[1], opt.resolution,
|
|
offset=extent[:2])
|
|
board = None
|
|
if opt.vectorize:
|
|
half = opt.marker_size
|
|
exclude = [(x - half, y - half, x + half, y + half) for x, y in targets]
|
|
col = int(round(-extent[0] * opt.resolution))
|
|
row = int(round(-extent[1] * opt.resolution))
|
|
area_w, area_h = vision.output_size(opt.work_width, opt.work_height,
|
|
opt.resolution)
|
|
board = vision.extract_board(
|
|
vision.gray_array(rectified)[row:row + area_h, col:col + area_w],
|
|
valid[row:row + area_h, col:col + area_w], opt.resolution,
|
|
lighter=opt.board_tone == "lighter", threshold=opt.threshold,
|
|
smoothing=opt.smoothing, min_hole_area=opt.min_hole_area,
|
|
simplify=opt.simplify, exclude=exclude)
|
|
if board is None:
|
|
warnings.append(_("No board found on the photo: try the other "
|
|
"\"Board tone\" or set the threshold by hand."))
|
|
|
|
scale, ox, oy = common.prepare_page(self.svg, opt.work_width, opt.work_height,
|
|
opt.set_page)
|
|
self.write_layers(rectified, board, scale, ox, oy, extent)
|
|
if "page_size" in common.page_problems(self.svg):
|
|
warnings.append(_("The page is not the size of the work area: the export "
|
|
"to LaserGRBL takes the bottom left of the page as the "
|
|
"laser origin, so tick \"Set the page to the work area "
|
|
"size\" before cutting."))
|
|
|
|
# Precision : taille d'un pixel de la photo au centre de la zone.
|
|
centre = (opt.work_width / 2.0, opt.work_height / 2.0)
|
|
pixel = 1.0 / core.local_scale(core.homography(targets, points), centre)
|
|
summary = _("Board photo calibrated: {:.2f} mm per photo pixel.").format(pixel)
|
|
summary = " ".join(self.notes + [summary])
|
|
if board is not None:
|
|
summary += " " + _("{} hole(s) found.").format(board["holes"])
|
|
for message in warnings:
|
|
inkex.errormsg(message)
|
|
inkex.errormsg(summary)
|
|
|
|
def make_image(self, picture, x, y, width, height):
|
|
data = vision.encode_image(picture, quality=self.options.jpeg_quality)
|
|
image = inkex.Image()
|
|
image.set("xlink:href", "data:image/jpeg;base64," +
|
|
base64.b64encode(data).decode("ascii"))
|
|
for name, value in (("x", x), ("y", y), ("width", width), ("height", height)):
|
|
image.set(name, common.fmt(value))
|
|
# Etirement exact sur le rectangle : c'est ce qui garantit l'echelle.
|
|
image.set("preserveAspectRatio", "none")
|
|
image.style = inkex.Style({"image-rendering": "optimizeQuality"})
|
|
return image
|
|
|
|
def write_layers(self, rectified, board, scale, ox, oy, extent=None):
|
|
opt = self.options
|
|
for key in ("photo", "outline"):
|
|
common.remove_layers(self.svg, key)
|
|
|
|
photo_layer = common.new_layer(_("Board photo"), "photo", locked=True)
|
|
common.insert_bottom(self.svg, photo_layer)
|
|
x0, y0, x1, y1 = extent or (0.0, 0.0, opt.work_width, opt.work_height)
|
|
image = self.make_image(rectified, ox + x0 * scale, oy + y0 * scale,
|
|
(x1 - x0) * scale, (y1 - y0) * scale)
|
|
image.label = _("Calibrated photo")
|
|
photo_layer.add(image)
|
|
# Zone de travail de la calibration (controle de la page avant export).
|
|
photo_layer.set(common.AREA_ATTR, "{} {}".format(
|
|
common.fmt(opt.work_width), common.fmt(opt.work_height)))
|
|
|
|
if board is not None:
|
|
color, opacity = core.parse_color(opt.outline_color)
|
|
outline_layer = common.paint_layer(
|
|
common.new_layer(_("Board outline"), "outline", locked=True),
|
|
fill=color, stroke=color)
|
|
photo_layer.addnext(outline_layer)
|
|
path = inkex.PathElement()
|
|
path.set("d", core.polylines_to_d(
|
|
core.scale_rings(board["rings"], scale, (ox, oy)), closed=True))
|
|
path.style = inkex.Style({
|
|
"fill-opacity": str(round(0.18 * opacity, 4)),
|
|
"fill-rule": "evenodd",
|
|
"stroke-opacity": str(opacity), "stroke-width": str(0.3 * scale)})
|
|
path.set(common.DATA, common.OUTLINE_SHAPE)
|
|
path.label = _("Board outline ({} holes)").format(board["holes"])
|
|
outline_layer.add(path)
|
|
|
|
cuts = common.find_all(self.svg, "cuts")
|
|
if cuts:
|
|
cuts_layer = cuts[0]
|
|
else:
|
|
cuts_layer = common.new_layer(_("Cuts"), "cuts")
|
|
self.svg.add(cuts_layer)
|
|
common.set_current_layer(self.svg, cuts_layer)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
BoardPhotoImport().run()
|