Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 13eeec7119 | |||
| 0629f1b5ec | |||
| 11c7d2e98b | |||
| 88bba213e2 |
+652
-118
@@ -1,80 +1,194 @@
|
||||
"""Pagina HTML della calibrazione a scacchiera (servita da camera_service su /calibrazione, #83).
|
||||
"""Pagina HTML dell'acquisizione camera (servita da camera_service su /calibrazione e /acquisizione, #83 #87).
|
||||
|
||||
Cosa fa: una pagina sola, autonoma e offline (niente CDN, JS e CSS inline), in
|
||||
italiano. Parla con le rotte dello stesso servizio (/camera/sources,
|
||||
/camera/calibration, /camera/calibrate).
|
||||
#84: calibrazione densa, un solo dato dell'operatore (lato dello scacco in mm):
|
||||
scacchiera che riempie il campo, griglia trovata da sola, mappa di distorsione.
|
||||
Cosa fa: una pagina sola, autonoma e offline (niente CDN, niente font esterni,
|
||||
JS e CSS inline), in italiano, stile scuro TMF. Quattro sezioni: Sorgente,
|
||||
Anteprima (dal vivo, con nitidezza/saturazione/livello medio), Parametri camera
|
||||
(esposizione e guadagno), Calibrazione a scacchiera.
|
||||
Parla con le rotte dello stesso servizio: /camera/sources, /camera/anteprima,
|
||||
/camera/parametri, /camera/parametri/salva, /camera/calibration, /camera/calibrate.
|
||||
#84: calibrazione densa, un solo dato dell'operatore (lato dello scacco in mm).
|
||||
#87: anteprima, parametri camera, stile TMF.
|
||||
Dipende da: niente. E' una stringa, cosi' il pacchetto compilato non ha file dati.
|
||||
"""
|
||||
|
||||
PAGINA = """<!doctype html>
|
||||
PAGINA = r"""<!doctype html>
|
||||
<html lang="it">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Calibrazione camera</title>
|
||||
<title>Acquisizione camera</title>
|
||||
<style>
|
||||
body { font-family: system-ui, sans-serif; margin: 0; background: #f3f4f6; color: #1f2937; }
|
||||
main { max-width: 960px; margin: 0 auto; padding: 16px; }
|
||||
h1 { font-size: 1.4rem; margin: 0 0 12px; }
|
||||
.scheda { background: #fff; border: 1px solid #d1d5db; border-radius: 8px; padding: 14px; margin-bottom: 14px; }
|
||||
label { display: block; font-size: .85rem; margin-bottom: 4px; color: #4b5563; }
|
||||
select, input[type=number] { padding: 6px 8px; font-size: 1rem; border: 1px solid #9ca3af; border-radius: 6px; }
|
||||
.riga { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; }
|
||||
button { padding: 8px 14px; font-size: 1rem; border: 0; border-radius: 6px; background: #2563eb; color: #fff; cursor: pointer; }
|
||||
button.secondario { background: #6b7280; }
|
||||
/* #87: stile scuro TMF (slate/blu), font di sistema */
|
||||
:root { --sfondo: #0f172a; --pannello: #1e293b; --bordo: #334155; --accento: #3b82f6;
|
||||
--testo: #e2e8f0; --secondario: #94a3b8; --errore: #f87171; --ok: #4ade80; --avviso: #fbbf24; }
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; } /* #87: vale anche dove il CSS imposta display */
|
||||
body { font-family: "Segoe UI", system-ui, sans-serif; margin: 0; background: var(--sfondo); color: var(--testo); }
|
||||
main { max-width: 1500px; margin: 0 auto; padding: 14px; }
|
||||
h1 { font-size: 1.35rem; margin: 0 0 12px; }
|
||||
h2 { font-size: 1.02rem; margin: 0 0 10px; }
|
||||
.griglia { display: grid; grid-template-columns: minmax(0, 1.7fr) minmax(320px, 1fr); gap: 14px; align-items: start; }
|
||||
.colonna { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
|
||||
.scheda { background: var(--pannello); border: 1px solid var(--bordo); border-radius: 8px; padding: 14px; }
|
||||
label { display: block; font-size: .82rem; margin-bottom: 4px; color: var(--secondario); }
|
||||
select, input[type=text] { padding: 6px 8px; font-size: .95rem; color: var(--testo); background: var(--sfondo);
|
||||
border: 1px solid var(--bordo); border-radius: 6px; font-family: inherit; }
|
||||
select { max-width: 100%; }
|
||||
select:focus, input:focus, button:focus-visible { outline: 2px solid var(--accento); outline-offset: 1px; }
|
||||
input[type=range] { width: 100%; accent-color: var(--accento); }
|
||||
input[type=checkbox] { accent-color: var(--accento); }
|
||||
.riga { display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-end; }
|
||||
.nota { font-size: .82rem; color: var(--secondario); margin: 8px 0 0; }
|
||||
button { padding: 7px 13px; font-size: .95rem; border: 0; border-radius: 6px; background: var(--accento); color: #fff;
|
||||
cursor: pointer; font-family: inherit; }
|
||||
button.secondario { background: var(--bordo); color: var(--testo); }
|
||||
button.pericolo { background: #b91c1c; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
.messaggio { margin-top: 10px; font-weight: 600; }
|
||||
.errore { color: #b91c1c; }
|
||||
.ok { color: #15803d; }
|
||||
table { border-collapse: collapse; }
|
||||
td { padding: 3px 14px 3px 0; }
|
||||
td:first-child { color: #4b5563; }
|
||||
img { max-width: 100%; border: 1px solid #d1d5db; border-radius: 6px; margin-top: 8px; }
|
||||
.avviso { color: #92400e; }
|
||||
button:disabled { opacity: .45; cursor: default; }
|
||||
.messaggio { min-height: 1.2em; margin-top: 8px; font-size: .9rem; font-weight: 600; color: var(--secondario); }
|
||||
.errore { color: var(--errore); }
|
||||
.ok { color: var(--ok); }
|
||||
.avviso { color: var(--avviso); font-size: .88rem; }
|
||||
table { border-collapse: collapse; font-size: .88rem; }
|
||||
td { padding: 2px 14px 2px 0; }
|
||||
td:first-child { color: var(--secondario); }
|
||||
.stato { font-size: .9rem; color: var(--secondario); margin-top: 8px; }
|
||||
/* anteprima */
|
||||
.palco { background: #020617; border: 1px solid var(--bordo); border-radius: 6px; min-height: 340px;
|
||||
display: flex; align-items: center; justify-content: center; margin-top: 10px; overflow: hidden; }
|
||||
.cornice { position: relative; display: inline-block; line-height: 0; max-width: 100%; }
|
||||
.cornice img { max-width: 100%; max-height: calc(100vh - 330px); min-height: 200px; border: 0; margin: 0; }
|
||||
#mirino { position: absolute; inset: 0; pointer-events: none;
|
||||
background: linear-gradient(#fbbf24, #fbbf24) center / 2px 100% no-repeat,
|
||||
linear-gradient(#fbbf24, #fbbf24) center / 100% 2px no-repeat; opacity: .85; }
|
||||
#vuoto { padding: 30px 16px; color: var(--secondario); text-align: center; }
|
||||
.indicatori { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-top: 10px; }
|
||||
.indicatore { background: var(--sfondo); border: 1px solid var(--bordo); border-radius: 6px; padding: 8px 10px; }
|
||||
.indicatore .nome { font-size: .78rem; color: var(--secondario); }
|
||||
.indicatore .valore { font-size: 1.35rem; font-weight: 600; font-variant-numeric: tabular-nums; }
|
||||
.indicatore .piccolo { font-size: .76rem; color: var(--secondario); }
|
||||
.barra { height: 6px; background: var(--bordo); border-radius: 3px; margin-top: 4px; overflow: hidden; }
|
||||
.barra > div { height: 100%; width: 0; background: var(--accento); transition: width .15s; }
|
||||
.rosso { color: var(--errore); }
|
||||
/* parametri */
|
||||
.parametro { margin-bottom: 12px; }
|
||||
.parametro .campo { display: flex; align-items: center; gap: 6px; }
|
||||
.parametro .campo input[type=text] { width: 110px; text-align: right; flex: none; }
|
||||
.parametro .unita { font-size: .82rem; color: var(--secondario); min-width: 2.2em; }
|
||||
.parametro .limiti { font-size: .75rem; color: var(--secondario); }
|
||||
@media (max-width: 900px) {
|
||||
.griglia { grid-template-columns: minmax(0, 1fr); }
|
||||
.cornice img { max-height: 60vh; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Calibrazione camera con scacchiera</h1>
|
||||
<h1>Acquisizione camera</h1>
|
||||
|
||||
<div class="scheda">
|
||||
<div class="riga">
|
||||
<div><label for="sorgente">Sorgente</label><select id="sorgente"></select></div>
|
||||
<div><label for="quadrato">Lato dello scacco (mm)</label><input id="quadrato" type="number" min="0.001" step="any" value="2"></div>
|
||||
<div class="griglia">
|
||||
<div class="colonna">
|
||||
<!-- #87: sezione Anteprima -->
|
||||
<section class="scheda" id="sezioneAnteprima">
|
||||
<h2>Anteprima</h2>
|
||||
<div class="riga">
|
||||
<button id="avvia">Avvia anteprima</button>
|
||||
<button id="ferma" class="secondario" disabled>Ferma anteprima</button>
|
||||
<button id="scatta" class="secondario">Scatta</button>
|
||||
<label style="margin:0 0 6px"><input id="grezzo" type="checkbox"> Immagine grezza (senza correzione)</label>
|
||||
<label style="margin:0 0 6px"><input id="mirinoCasella" type="checkbox"> Mirino centrale</label>
|
||||
</div>
|
||||
<div class="palco">
|
||||
<div id="vuoto">Anteprima ferma. Premere «Avvia anteprima» o «Scatta».</div>
|
||||
<div class="cornice" id="cornice" hidden>
|
||||
<img id="immagine" alt="Anteprima della camera">
|
||||
<div id="mirino" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="indicatori">
|
||||
<div class="indicatore">
|
||||
<div class="nome">Nitidezza</div>
|
||||
<div class="valore" id="nitidezza">-</div>
|
||||
<div class="barra"><div id="barraNitidezza"></div></div>
|
||||
<div class="piccolo">massimo visto: <span id="nitidezzaMax">-</span>
|
||||
<button id="azzeraMax" class="secondario" style="padding:1px 7px;font-size:.75rem;margin-left:6px">Azzera</button></div>
|
||||
</div>
|
||||
<div class="indicatore">
|
||||
<div class="nome">Saturati</div>
|
||||
<div class="valore" id="saturati">-</div>
|
||||
<div class="piccolo">pixel a 250 o più; da tenere sotto l'1 %</div>
|
||||
</div>
|
||||
<div class="indicatore">
|
||||
<div class="nome">Livello medio</div>
|
||||
<div class="valore" id="media">-</div>
|
||||
<div class="piccolo">scala 0-255</div>
|
||||
</div>
|
||||
<div class="indicatore">
|
||||
<div class="nome">Frame pieno</div>
|
||||
<div class="valore" id="dimensioni">-</div>
|
||||
<div class="piccolo" id="raddrizzato"> </div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="msgAnteprima" class="messaggio"></div>
|
||||
</section>
|
||||
</div>
|
||||
<p style="font-size:.85rem;color:#4b5563;margin:10px 0 0">
|
||||
Servono una scacchiera che riempie tutto il campo della camera, piana, ferma e ben illuminata, e il lato di uno scacco.
|
||||
La griglia si trova da sola; il risultato corregge anche la distorsione dell'ottica.</p>
|
||||
</div>
|
||||
|
||||
<div class="scheda">
|
||||
<div class="riga">
|
||||
<button id="acquisisci">Acquisisci e calibra</button>
|
||||
<div><label for="file">oppure un file immagine</label><input id="file" type="file" accept="image/*"></div>
|
||||
<button id="carica" class="secondario">Carica immagine e calibra</button>
|
||||
</div>
|
||||
<div id="messaggio" class="messaggio"></div>
|
||||
</div>
|
||||
<div class="colonna">
|
||||
<!-- #87: sezione Sorgente -->
|
||||
<section class="scheda" id="sezioneSorgente">
|
||||
<h2>Sorgente</h2>
|
||||
<label for="sorgente">Camera o cartella</label>
|
||||
<select id="sorgente"></select>
|
||||
<div class="stato" id="statoSorgente">-</div>
|
||||
<div id="msgSorgente" class="messaggio"></div>
|
||||
</section>
|
||||
|
||||
<div class="scheda" id="risultato" hidden>
|
||||
<strong>Risultato del calcolo</strong>
|
||||
<table id="tabella"></table>
|
||||
<div id="avviso" class="avviso"></div>
|
||||
<div class="riga" style="margin-top:10px">
|
||||
<button id="salva">Salva</button>
|
||||
<span style="font-size:.85rem;color:#4b5563">Da camera, salvando si acquisisce e si calcola di nuovo: tenere la scacchiera ferma.</span>
|
||||
</div>
|
||||
<img id="overlay" alt="Angoli trovati sulla scacchiera">
|
||||
</div>
|
||||
<!-- #87: sezione Parametri camera -->
|
||||
<section class="scheda" id="sezioneParametri">
|
||||
<h2>Parametri camera</h2>
|
||||
<div id="parametri"><div class="nota">-</div></div>
|
||||
<div class="riga" id="salvaParametriRiga" hidden>
|
||||
<button id="salvaParametri" class="secondario">Salva come predefiniti</button>
|
||||
</div>
|
||||
<div id="msgParametri" class="messaggio"></div>
|
||||
</section>
|
||||
|
||||
<div class="scheda">
|
||||
<strong>Calibrazione salvata</strong>
|
||||
<div id="stato">-</div>
|
||||
<div class="riga" style="margin-top:10px">
|
||||
<button id="elimina" class="pericolo" disabled>Elimina</button>
|
||||
<section class="scheda" id="sezioneCalibrazione">
|
||||
<h2>Calibrazione</h2>
|
||||
<div class="riga">
|
||||
<div><label for="quadrato">Lato dello scacco (mm)</label><input id="quadrato" type="text" inputmode="decimal" value="2" size="8"></div>
|
||||
</div>
|
||||
<p class="nota">
|
||||
Servono una scacchiera che riempie tutto il campo della camera, piana, ferma e ben illuminata, e il lato di uno scacco.
|
||||
La griglia si trova da sola; il risultato corregge anche la distorsione dell'ottica.
|
||||
Durante il calcolo l'anteprima si sospende.</p>
|
||||
<div class="riga" style="margin-top:10px">
|
||||
<button id="acquisisci">Acquisisci e calibra</button>
|
||||
<button id="scegliFile" class="secondario">Scegli immagine...</button>
|
||||
<input id="file" type="file" accept="image/*" hidden>
|
||||
<span id="nomeFile" class="nota" style="margin:0 0 6px">nessuna immagine scelta</span>
|
||||
<button id="carica" class="secondario">Carica immagine e calibra</button>
|
||||
</div>
|
||||
<div id="messaggio" class="messaggio"></div>
|
||||
|
||||
<div id="risultato" hidden style="margin-top:10px">
|
||||
<strong>Risultato del calcolo</strong>
|
||||
<table id="tabella"></table>
|
||||
<div id="avviso" class="avviso"></div>
|
||||
<div class="riga" style="margin-top:10px">
|
||||
<button id="salva">Salva</button>
|
||||
<span class="nota" style="margin:0 0 6px">Da camera, salvando si acquisisce e si calcola di nuovo: tenere la scacchiera ferma.</span>
|
||||
</div>
|
||||
<img id="overlay" alt="Angoli trovati sulla scacchiera" style="max-width:100%;margin-top:8px;border:1px solid var(--bordo);border-radius:6px">
|
||||
</div>
|
||||
|
||||
<div style="margin-top:14px">
|
||||
<strong>Calibrazione salvata</strong>
|
||||
<div id="stato" class="stato">-</div>
|
||||
<div class="riga" style="margin-top:10px">
|
||||
<button id="elimina" class="pericolo" disabled>Elimina calibrazione</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
@@ -82,31 +196,437 @@ PAGINA = """<!doctype html>
|
||||
<script>
|
||||
"use strict";
|
||||
var $ = function (id) { return document.getElementById(id); };
|
||||
var ultimo = null; // ultimo calcolo, per «Salva»
|
||||
var ultimo = null; // ultimo calcolo di calibrazione, per «Salva»
|
||||
|
||||
function messaggio(testo, classe) {
|
||||
var m = $("messaggio");
|
||||
// ---- utilita'
|
||||
|
||||
// numero all'italiana (virgola decimale); cifre = decimali fissi, omesso = fino a 4
|
||||
function fmt(v, cifre) {
|
||||
var n = Number(v);
|
||||
if (!isFinite(n)) return "-";
|
||||
var o = cifre === undefined ? { maximumFractionDigits: 4 } : { minimumFractionDigits: cifre, maximumFractionDigits: cifre };
|
||||
return n.toLocaleString("it-IT", o);
|
||||
}
|
||||
// numero senza separatore delle migliaia, per le caselle di input
|
||||
function fmtCasella(v) { return Number(v).toLocaleString("it-IT", { maximumFractionDigits: 6, useGrouping: false }); }
|
||||
// legge un numero scritto con virgola o con punto
|
||||
function leggiNumero(testo) {
|
||||
var n = Number(String(testo).split(" ").join("").replace(",", "."));
|
||||
return isFinite(n) && String(testo).trim() !== "" ? n : NaN;
|
||||
}
|
||||
function dataItaliana(iso) {
|
||||
var d = new Date(iso);
|
||||
if (isNaN(d.getTime())) return String(iso);
|
||||
return d.toLocaleString("it-IT", { day: "2-digit", month: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit" }).replace(",", "");
|
||||
}
|
||||
function dire(id, testo, classe) {
|
||||
var m = $(id);
|
||||
m.textContent = testo || "";
|
||||
m.className = "messaggio " + (classe || "");
|
||||
}
|
||||
function messaggio(testo, classe) { dire("messaggio", testo, classe); }
|
||||
function pausa(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
|
||||
function memoria(chiave, valore) { // localStorage sempre protetto: puo' essere bloccato
|
||||
try {
|
||||
if (valore === undefined) return localStorage.getItem(chiave);
|
||||
localStorage.setItem(chiave, valore);
|
||||
} catch (e) { /* niente memoria, la pagina funziona lo stesso */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
function numero(v, cifre) { return Number(v).toFixed(cifre); }
|
||||
// testo d'errore da una risposta; #87: rotte nuove assenti in un servizio vecchio -> messaggio chiaro
|
||||
async function dettaglio(risposta) {
|
||||
var testo;
|
||||
try { var j = await risposta.json(); testo = j.detail || JSON.stringify(j); }
|
||||
catch (e) { testo = "errore " + risposta.status; }
|
||||
if (testo === "Not Found" || testo === "Method Not Allowed") {
|
||||
return "Funzione non disponibile: il servizio della camera è una versione più vecchia (errore " + risposta.status + ").";
|
||||
}
|
||||
return typeof testo === "string" ? testo : JSON.stringify(testo);
|
||||
}
|
||||
|
||||
// ---- Sorgente
|
||||
|
||||
async function caricaSorgenti() {
|
||||
var sel = $("sorgente");
|
||||
try {
|
||||
var r = await fetch("/camera/sources");
|
||||
var j = await r.json();
|
||||
(j.sources || []).forEach(function (s) {
|
||||
var o = document.createElement("option");
|
||||
o.value = s.name;
|
||||
o.textContent = s.label || s.name;
|
||||
sel.appendChild(o);
|
||||
});
|
||||
} catch (e) { dire("msgSorgente", "Elenco delle sorgenti non disponibile.", "errore"); }
|
||||
if (!sel.options.length) dire("msgSorgente", "Nessuna sorgente camera trovata.", "errore");
|
||||
var ricordata = memoria("tmf.acq.sorgente"); // #87: ultima scelta ricordata
|
||||
if (ricordata) {
|
||||
for (var i = 0; i < sel.options.length; i++) if (sel.options[i].value === ricordata) sel.value = ricordata;
|
||||
}
|
||||
cambioSorgente(false);
|
||||
}
|
||||
|
||||
// #87: cambiando sorgente si azzerano gli indicatori e si rileggono parametri e calibrazione
|
||||
function cambioSorgente(salva) {
|
||||
if (salva) memoria("tmf.acq.sorgente", $("sorgente").value);
|
||||
var era = A.attiva;
|
||||
fermaAnteprima();
|
||||
azzeraIndicatori();
|
||||
dire("msgAnteprima", "");
|
||||
aggiornaStato();
|
||||
caricaParametri();
|
||||
if (era) avviaAnteprima();
|
||||
}
|
||||
|
||||
// ---- Anteprima (#87)
|
||||
|
||||
var A = { attiva: false, gen: 0, inVolo: false, url: null, nitMax: 0 };
|
||||
|
||||
function azzeraIndicatori() {
|
||||
A.nitMax = 0;
|
||||
["nitidezza", "saturati", "media", "dimensioni", "nitidezzaMax"].forEach(function (i) { $(i).textContent = "-"; });
|
||||
$("saturati").className = "valore";
|
||||
$("barraNitidezza").style.width = "0";
|
||||
$("raddrizzato").textContent = " ";
|
||||
}
|
||||
|
||||
function pulsantiAnteprima() {
|
||||
$("avvia").disabled = A.attiva;
|
||||
$("ferma").disabled = !A.attiva;
|
||||
}
|
||||
|
||||
function mostraImmagine(blob) {
|
||||
var vecchio = A.url;
|
||||
A.url = URL.createObjectURL(blob);
|
||||
$("immagine").src = A.url;
|
||||
if (vecchio) URL.revokeObjectURL(vecchio); // niente memoria che cresce a ogni frame
|
||||
$("cornice").hidden = false;
|
||||
$("vuoto").hidden = true;
|
||||
}
|
||||
|
||||
function aggiornaIndicatori(h) {
|
||||
var nit = parseFloat(h.get("X-Nitidezza"));
|
||||
var sat = parseFloat(h.get("X-Saturati-Pct"));
|
||||
var media = parseFloat(h.get("X-Media"));
|
||||
if (isFinite(nit)) {
|
||||
if (nit > A.nitMax) A.nitMax = nit;
|
||||
$("nitidezza").textContent = fmt(nit, 1);
|
||||
$("nitidezzaMax").textContent = fmt(A.nitMax, 1);
|
||||
$("barraNitidezza").style.width = (A.nitMax > 0 ? Math.round(100 * nit / A.nitMax) : 0) + "%";
|
||||
}
|
||||
if (isFinite(sat)) {
|
||||
$("saturati").textContent = fmt(sat, 2) + " %";
|
||||
$("saturati").className = "valore" + (sat > 1 ? " rosso" : ""); // oltre l'1 % si perde dettaglio
|
||||
}
|
||||
if (isFinite(media)) $("media").textContent = fmt(media, 1);
|
||||
var w = h.get("X-Larghezza"), a = h.get("X-Altezza");
|
||||
if (w && a) $("dimensioni").textContent = fmt(w, 0) + " x " + fmt(a, 0);
|
||||
var r = h.get("X-Raddrizzato");
|
||||
$("raddrizzato").textContent = r === "si" ? "raddrizzata dalla calibrazione" : r === "no" ? "non raddrizzata" : " ";
|
||||
}
|
||||
|
||||
// una richiesta di anteprima; ritorna "ok" | "errore" | "fatale" (errore che non passa riprovando)
|
||||
async function unaAnteprima(lato) {
|
||||
var sorgente = $("sorgente").value;
|
||||
if (!sorgente) { dire("msgAnteprima", "Scegliere una sorgente.", "errore"); return "fatale"; }
|
||||
var g = A.gen;
|
||||
A.inVolo = true;
|
||||
try {
|
||||
var r = await fetch("/camera/anteprima", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ source: sorgente, grezzo: $("grezzo").checked, lato_max: lato, timeout_ms: 5000 })
|
||||
});
|
||||
if (!r.ok) {
|
||||
var d = await dettaglio(r);
|
||||
if (g === A.gen) dire("msgAnteprima", d, "errore");
|
||||
return r.status >= 500 ? "errore" : "fatale"; // 503/504: la camera puo' tornare
|
||||
}
|
||||
var blob = await r.blob();
|
||||
if (g !== A.gen) return "ok"; // frame di una sorgente o di un ciclo ormai chiuso: si scarta
|
||||
mostraImmagine(blob);
|
||||
aggiornaIndicatori(r.headers);
|
||||
dire("msgAnteprima", "");
|
||||
return "ok";
|
||||
} catch (e) {
|
||||
if (g === A.gen) dire("msgAnteprima", "Servizio non raggiungibile.", "errore");
|
||||
return "errore";
|
||||
} finally {
|
||||
A.inVolo = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ciclo sequenziale: la richiesta dopo parte solo a risposta arrivata, almeno 300 ms dopo la precedente
|
||||
async function ciclo(g) {
|
||||
while (A.inVolo) await pausa(50);
|
||||
while (A.attiva && g === A.gen) {
|
||||
var t0 = Date.now();
|
||||
var esito = await unaAnteprima(1280);
|
||||
if (g !== A.gen) return;
|
||||
if (esito === "fatale") { fermaAnteprima(); return; }
|
||||
await pausa(esito === "errore" ? 1500 : Math.max(300 - (Date.now() - t0), 0));
|
||||
}
|
||||
}
|
||||
|
||||
function avviaAnteprima() {
|
||||
if (A.attiva) return;
|
||||
A.attiva = true;
|
||||
A.gen++;
|
||||
pulsantiAnteprima();
|
||||
ciclo(A.gen);
|
||||
}
|
||||
|
||||
function fermaAnteprima() {
|
||||
A.attiva = false;
|
||||
A.gen++;
|
||||
pulsantiAnteprima();
|
||||
}
|
||||
|
||||
// «Scatta»: ferma il ciclo e mostra un frame solo, alla risoluzione piena (fino a 4096 px)
|
||||
async function scatta() {
|
||||
fermaAnteprima();
|
||||
$("scatta").disabled = true;
|
||||
dire("msgAnteprima", "Scatto in corso...", "");
|
||||
while (A.inVolo) await pausa(50);
|
||||
await unaAnteprima(4096);
|
||||
$("scatta").disabled = false;
|
||||
}
|
||||
|
||||
$("avvia").onclick = avviaAnteprima;
|
||||
$("ferma").onclick = fermaAnteprima;
|
||||
$("scatta").onclick = scatta;
|
||||
$("azzeraMax").onclick = function () { A.nitMax = 0; $("nitidezzaMax").textContent = "-"; $("barraNitidezza").style.width = "0"; };
|
||||
$("mirinoCasella").onchange = function () { $("mirino").hidden = !$("mirinoCasella").checked; };
|
||||
|
||||
// ---- Parametri camera (#87)
|
||||
|
||||
var ORDINE = ["esposizione", "esposizione_auto", "guadagno", "guadagno_auto"];
|
||||
var ETICHETTE = { esposizione: "Esposizione", esposizione_auto: "Esposizione automatica",
|
||||
guadagno: "Guadagno", guadagno_auto: "Guadagno automatico" };
|
||||
var UNITA = { esposizione: "µs", guadagno: "dB" };
|
||||
var ETICHETTE_SCELTE = { Off: "Spenta", Once: "Una volta", Continuous: "Continua" };
|
||||
var P = { el: {}, dati: {}, pendenti: {}, timer: null, inScrittura: false, gen: 0 };
|
||||
|
||||
function usaLog(d) { return typeof d.min === "number" && typeof d.max === "number" && d.min > 0 && d.max / d.min >= 100; }
|
||||
function haCursore(d) { return typeof d.min === "number" && typeof d.max === "number" && d.max > d.min; }
|
||||
function aPosizione(d, v) {
|
||||
var t = usaLog(d) ? Math.log(Math.max(v, d.min) / d.min) / Math.log(d.max / d.min) : (v - d.min) / (d.max - d.min);
|
||||
return Math.round(1000 * Math.min(Math.max(t, 0), 1));
|
||||
}
|
||||
function daPosizione(d, p) {
|
||||
var t = p / 1000;
|
||||
return usaLog(d) ? d.min * Math.pow(d.max / d.min, t) : d.min + t * (d.max - d.min);
|
||||
}
|
||||
// porta il valore nei limiti e sul passo della camera
|
||||
function adatta(d, v) {
|
||||
if (typeof d.min === "number") v = Math.max(v, d.min);
|
||||
if (typeof d.max === "number") v = Math.min(v, d.max);
|
||||
if (typeof d.passo === "number" && d.passo > 0) {
|
||||
var base = typeof d.min === "number" ? d.min : 0;
|
||||
v = base + Math.round((v - base) / d.passo) * d.passo;
|
||||
if (typeof d.max === "number") v = Math.min(v, d.max);
|
||||
}
|
||||
return Number(v.toFixed(6));
|
||||
}
|
||||
|
||||
async function caricaParametri() {
|
||||
var sorgente = $("sorgente").value;
|
||||
var g = ++P.gen;
|
||||
P.pendenti = {};
|
||||
clearTimeout(P.timer);
|
||||
$("salvaParametriRiga").hidden = true;
|
||||
dire("msgParametri", "");
|
||||
if (!sorgente) { $("parametri").textContent = "-"; return; }
|
||||
try {
|
||||
var r = await fetch("/camera/parametri?source=" + encodeURIComponent(sorgente));
|
||||
if (g !== P.gen) return;
|
||||
if (!r.ok) {
|
||||
$("parametri").textContent = "";
|
||||
dire("msgParametri", await dettaglio(r), "errore");
|
||||
return;
|
||||
}
|
||||
costruisciParametri(await r.json());
|
||||
} catch (e) {
|
||||
if (g === P.gen) dire("msgParametri", "Servizio non raggiungibile.", "errore");
|
||||
}
|
||||
}
|
||||
|
||||
function costruisciParametri(j) {
|
||||
var box = $("parametri");
|
||||
box.textContent = "";
|
||||
P.el = {};
|
||||
P.dati = j.parametri || {};
|
||||
var nomi = ORDINE.filter(function (n) { return P.dati[n]; });
|
||||
if (!j.regolabile || !nomi.length) {
|
||||
var n = document.createElement("div");
|
||||
n.className = "nota";
|
||||
n.textContent = "Questa sorgente non ha parametri regolabili.";
|
||||
box.appendChild(n);
|
||||
$("salvaParametriRiga").hidden = true;
|
||||
return;
|
||||
}
|
||||
nomi.forEach(function (nome) { box.appendChild(creaParametro(nome, P.dati[nome])); });
|
||||
$("salvaParametriRiga").hidden = false;
|
||||
}
|
||||
|
||||
function creaParametro(nome, d) {
|
||||
var riga = document.createElement("div");
|
||||
riga.className = "parametro";
|
||||
var et = document.createElement("label");
|
||||
et.textContent = ETICHETTE[nome] + (UNITA[nome] ? " (" + UNITA[nome] + ")" : "");
|
||||
riga.appendChild(et);
|
||||
var el = { tipo: d.tipo };
|
||||
var bloccato = d.scrivibile === false;
|
||||
if (d.tipo === "scelta") {
|
||||
var sel = document.createElement("select");
|
||||
(d.scelte || []).forEach(function (s) {
|
||||
var o = document.createElement("option");
|
||||
o.value = s;
|
||||
o.textContent = ETICHETTE_SCELTE[s] || s;
|
||||
sel.appendChild(o);
|
||||
});
|
||||
sel.value = d.valore;
|
||||
sel.disabled = bloccato;
|
||||
sel.onchange = function () { modifica(nome, sel.value); };
|
||||
riga.appendChild(sel);
|
||||
el.select = sel;
|
||||
} else {
|
||||
var campo = document.createElement("div");
|
||||
campo.className = "campo";
|
||||
var cur = null;
|
||||
var casella = document.createElement("input");
|
||||
if (haCursore(d)) {
|
||||
cur = document.createElement("input");
|
||||
cur.type = "range";
|
||||
cur.min = 0; cur.max = 1000; cur.step = 1;
|
||||
cur.value = aPosizione(d, d.valore);
|
||||
cur.disabled = bloccato;
|
||||
cur.oninput = function () { // il cursore aggiorna la casella subito, la scrittura arriva dopo 300 ms
|
||||
var v = adatta(d, daPosizione(d, Number(cur.value)));
|
||||
casella.value = fmtCasella(v);
|
||||
modifica(nome, v);
|
||||
};
|
||||
campo.appendChild(cur);
|
||||
}
|
||||
casella.type = "text";
|
||||
casella.inputMode = "decimal";
|
||||
casella.value = fmtCasella(d.valore);
|
||||
casella.disabled = bloccato;
|
||||
casella.onchange = function () {
|
||||
var v = leggiNumero(casella.value);
|
||||
if (isNaN(v)) { dire("msgParametri", "Valore non valido per " + ETICHETTE[nome].toLowerCase() + ".", "errore"); casella.value = fmtCasella(P.dati[nome].valore); return; }
|
||||
v = adatta(d, v);
|
||||
casella.value = fmtCasella(v);
|
||||
if (cur) cur.value = aPosizione(d, v);
|
||||
modifica(nome, v);
|
||||
};
|
||||
campo.appendChild(casella);
|
||||
var u = document.createElement("span");
|
||||
u.className = "unita";
|
||||
u.textContent = UNITA[nome] || "";
|
||||
campo.appendChild(u);
|
||||
riga.appendChild(campo);
|
||||
if (typeof d.min === "number" || typeof d.max === "number") {
|
||||
var lim = document.createElement("div");
|
||||
lim.className = "limiti";
|
||||
lim.textContent = "da " + (typeof d.min === "number" ? fmt(d.min) : "?") + " a " + (typeof d.max === "number" ? fmt(d.max) : "?") +
|
||||
(typeof d.passo === "number" ? ", passo " + fmt(d.passo) : "") + (usaLog(d) ? " (cursore logaritmico)" : "");
|
||||
riga.appendChild(lim);
|
||||
}
|
||||
el.cursore = cur;
|
||||
el.casella = casella;
|
||||
}
|
||||
P.el[nome] = el;
|
||||
return riga;
|
||||
}
|
||||
|
||||
// una modifica dell'operatore: si accoda e parte dopo 300 ms dall'ultima
|
||||
function modifica(nome, valore) {
|
||||
P.pendenti[nome] = valore;
|
||||
var aut = nome + "_auto";
|
||||
// impostare un valore manuale spegne prima l'automatico corrispondente
|
||||
if ((nome === "esposizione" || nome === "guadagno") && P.el[aut] && P.el[aut].select && P.el[aut].select.value !== "Off") {
|
||||
P.pendenti[aut] = "Off";
|
||||
P.el[aut].select.value = "Off";
|
||||
}
|
||||
clearTimeout(P.timer);
|
||||
P.timer = setTimeout(scriviParametri, 300);
|
||||
}
|
||||
|
||||
async function scriviParametri() {
|
||||
if (P.inScrittura) { P.timer = setTimeout(scriviParametri, 100); return; }
|
||||
var valori = P.pendenti;
|
||||
P.pendenti = {};
|
||||
if (!Object.keys(valori).length) return;
|
||||
P.inScrittura = true;
|
||||
try {
|
||||
var r = await fetch("/camera/parametri", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ source: $("sorgente").value, valori: valori })
|
||||
});
|
||||
if (!r.ok) {
|
||||
dire("msgParametri", await dettaglio(r), "errore");
|
||||
if (r.status !== 404 && r.status !== 405) caricaParametri(); // si rilegge cosa ha la camera
|
||||
return;
|
||||
}
|
||||
aggiornaValori(await r.json());
|
||||
dire("msgParametri", "Parametri applicati.", "ok");
|
||||
} catch (e) {
|
||||
dire("msgParametri", "Servizio non raggiungibile.", "errore");
|
||||
} finally {
|
||||
P.inScrittura = false;
|
||||
}
|
||||
}
|
||||
|
||||
// rilegge i valori dalla risposta, lasciando stare quelli che l'operatore sta ancora toccando
|
||||
function aggiornaValori(j) {
|
||||
var dati = j.parametri || {};
|
||||
Object.keys(dati).forEach(function (nome) {
|
||||
var el = P.el[nome], d = dati[nome];
|
||||
if (!el || P.pendenti.hasOwnProperty(nome)) return;
|
||||
P.dati[nome].valore = d.valore;
|
||||
if (el.select) el.select.value = d.valore;
|
||||
if (el.casella && document.activeElement !== el.casella) el.casella.value = fmtCasella(d.valore);
|
||||
if (el.cursore && document.activeElement !== el.cursore) el.cursore.value = aPosizione(P.dati[nome], d.valore);
|
||||
});
|
||||
}
|
||||
|
||||
$("salvaParametri").onclick = async function () {
|
||||
$("salvaParametri").disabled = true;
|
||||
try {
|
||||
var r = await fetch("/camera/parametri/salva", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ source: $("sorgente").value })
|
||||
});
|
||||
if (!r.ok) dire("msgParametri", await dettaglio(r), "errore");
|
||||
else dire("msgParametri", "Predefiniti salvati: si ricaricano all'apertura della camera.", "ok");
|
||||
} catch (e) {
|
||||
dire("msgParametri", "Servizio non raggiungibile.", "errore");
|
||||
} finally {
|
||||
$("salvaParametri").disabled = false;
|
||||
}
|
||||
};
|
||||
|
||||
// ---- Calibrazione (logica di #83 e #84; #87: lato precompilato, data italiana, conferma in pagina)
|
||||
|
||||
function righe(d) {
|
||||
return [
|
||||
["Scala", numero(d.px_per_mm, 4) + " px/mm (" + numero(d.mm_per_px, 5) + " mm/px)"],
|
||||
["Scala", fmt(d.px_per_mm, 4) + " px/mm (" + fmt(d.mm_per_px, 5) + " mm/px)"],
|
||||
["Metodo", d.metodo !== "densa" ? "planare (senza correzione della distorsione)" : "densa (immagine raddrizzata)"],
|
||||
["Griglia trovata", d.cols + " x " + d.rows + " angoli (" + d.n_corners + ")"]
|
||||
["Griglia trovata", d.cols + " x " + d.rows + " angoli (" + fmt(d.n_corners, 0) + ")"]
|
||||
].concat(d.metodo !== "densa" ? [
|
||||
["Errore di riproiezione (RMS)", numero(d.rms_px, 3) + " px"],
|
||||
["Variazione di scala nell'area", numero(d.scale_spread_pct, 2) + " %"]
|
||||
["Errore di riproiezione (RMS)", fmt(d.rms_px, 3) + " px"],
|
||||
["Variazione di scala nell'area", fmt(d.scale_spread_pct, 2) + " %"]
|
||||
] : [
|
||||
["Residuo massimo", numero(d.residuo_max_px, 3) + " px"],
|
||||
["Residuo RMS", numero(d.residuo_rms_px, 3) + " px"],
|
||||
["Copertura del campo", numero(d.copertura_pct, 1) + " %"]
|
||||
["Residuo massimo", fmt(d.residuo_max_px, 3) + " px"],
|
||||
["Residuo RMS", fmt(d.residuo_rms_px, 3) + " px"],
|
||||
["Copertura del campo", fmt(d.copertura_pct, 1) + " %"]
|
||||
]).concat([
|
||||
["Lato dello scacco", d.square_mm + " mm"],
|
||||
["Immagine", d.image_width + " x " + d.image_height + " px"]
|
||||
["Lato dello scacco", fmt(d.square_mm) + " mm"],
|
||||
["Immagine", fmt(d.image_width, 0) + " x " + fmt(d.image_height, 0) + " px"]
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -123,58 +643,45 @@ function tabella(el, d) {
|
||||
});
|
||||
}
|
||||
|
||||
async function dettaglio(risposta) {
|
||||
try { var j = await risposta.json(); return j.detail || JSON.stringify(j); }
|
||||
catch (e) { return "errore " + risposta.status; }
|
||||
}
|
||||
|
||||
async function caricaSorgenti() {
|
||||
var sel = $("sorgente");
|
||||
try {
|
||||
var r = await fetch("/camera/sources");
|
||||
var j = await r.json();
|
||||
(j.sources || []).forEach(function (s) {
|
||||
var o = document.createElement("option");
|
||||
o.value = s.name;
|
||||
o.textContent = s.label || s.name;
|
||||
sel.appendChild(o);
|
||||
});
|
||||
} catch (e) { messaggio("Elenco delle sorgenti non disponibile.", "errore"); }
|
||||
if (!sel.options.length) messaggio("Nessuna sorgente camera trovata.", "errore");
|
||||
aggiornaStato();
|
||||
}
|
||||
|
||||
async function aggiornaStato() {
|
||||
var sorgente = $("sorgente").value;
|
||||
var stato = $("stato");
|
||||
annullaConferma();
|
||||
$("elimina").disabled = true;
|
||||
if (!sorgente) { stato.textContent = "-"; return; }
|
||||
var r = await fetch("/camera/calibration?source=" + encodeURIComponent(sorgente));
|
||||
if (r.status === 404) { stato.textContent = "Sorgente non calibrata."; return; }
|
||||
if (!r.ok) { stato.textContent = await dettaglio(r); return; }
|
||||
var d = await r.json();
|
||||
stato.textContent = "";
|
||||
var t = document.createElement("table");
|
||||
tabella(t, d);
|
||||
var quando = document.createElement("div");
|
||||
quando.textContent = "Calibrata il " + d.calibrated_at;
|
||||
stato.appendChild(t);
|
||||
stato.appendChild(quando);
|
||||
$("elimina").disabled = false;
|
||||
}
|
||||
|
||||
function parametri() {
|
||||
return { quadrato: $("quadrato").value };
|
||||
if (!sorgente) { stato.textContent = "-"; $("statoSorgente").textContent = "-"; return; }
|
||||
try {
|
||||
var r = await fetch("/camera/calibration?source=" + encodeURIComponent(sorgente));
|
||||
if (sorgente !== $("sorgente").value) return; // nel frattempo si e' cambiata sorgente
|
||||
if (r.status === 404) {
|
||||
stato.textContent = "Sorgente non calibrata.";
|
||||
$("statoSorgente").textContent = "non calibrata";
|
||||
return;
|
||||
}
|
||||
if (!r.ok) { stato.textContent = await dettaglio(r); return; }
|
||||
var d = await r.json();
|
||||
stato.textContent = "";
|
||||
var t = document.createElement("table");
|
||||
tabella(t, d);
|
||||
var quando = document.createElement("div");
|
||||
quando.textContent = "Calibrata il " + dataItaliana(d.calibrated_at);
|
||||
stato.appendChild(t);
|
||||
stato.appendChild(quando);
|
||||
$("elimina").disabled = false;
|
||||
$("statoSorgente").textContent = "calibrata: " + fmt(d.px_per_mm, 2) + " px/mm";
|
||||
if (d.square_mm) $("quadrato").value = fmtCasella(d.square_mm); // #87: parte dal lato gia' usato
|
||||
} catch (e) {
|
||||
stato.textContent = "Servizio non raggiungibile.";
|
||||
}
|
||||
}
|
||||
|
||||
// avvisi sulla qualita' (solo calibrazione densa): copertura bassa o residuo alto
|
||||
function avvisi(d) {
|
||||
var a = [];
|
||||
if (d.metodo !== "densa") {
|
||||
if (d.scale_spread_pct > 1) a.push("Attenzione: la scala varia di " + numero(d.scale_spread_pct, 2) + " % nell'area: scacchiera inclinata o ottica non telecentrica.");
|
||||
if (d.scale_spread_pct > 1) a.push("Attenzione: la scala varia di " + fmt(d.scale_spread_pct, 2) + " % nell'area: scacchiera inclinata o ottica non telecentrica.");
|
||||
} else {
|
||||
if (d.copertura_pct < 70) a.push("Attenzione: la scacchiera copre solo il " + numero(d.copertura_pct, 1) + " % del campo (meno del 70 %): la correzione ai bordi non e' misurata.");
|
||||
if (d.residuo_max_px > 0.5) a.push("Attenzione: residuo massimo " + numero(d.residuo_max_px, 3) + " px (oltre 0,5 px): scacchiera non piana, sfocata o con scacchi irregolari.");
|
||||
if (d.copertura_pct < 70) a.push("Attenzione: la scacchiera copre solo il " + fmt(d.copertura_pct, 1) + " % del campo (meno del 70 %): la correzione ai bordi non è misurata.");
|
||||
if (d.residuo_max_px > 0.5) a.push("Attenzione: residuo massimo " + fmt(d.residuo_max_px, 3) + " px (oltre 0,5 px): scacchiera non piana, sfocata o con scacchi irregolari.");
|
||||
}
|
||||
return a.join(" ");
|
||||
}
|
||||
@@ -182,16 +689,19 @@ function avvisi(d) {
|
||||
async function calcola(conFile, salva) {
|
||||
var sorgente = $("sorgente").value;
|
||||
if (!sorgente) { messaggio("Scegliere una sorgente.", "errore"); return; }
|
||||
var p = parametri();
|
||||
var lato = leggiNumero($("quadrato").value);
|
||||
if (!(lato > 0)) { messaggio("Il lato dello scacco deve essere un numero maggiore di zero.", "errore"); return; }
|
||||
var f = new FormData();
|
||||
f.append("source", sorgente);
|
||||
f.append("square_mm", p.quadrato);
|
||||
f.append("square_mm", String(lato)); // al servizio sempre con il punto
|
||||
f.append("save", salva ? "true" : "false");
|
||||
if (conFile) {
|
||||
var file = $("file").files[0];
|
||||
if (!file) { messaggio("Scegliere un file immagine.", "errore"); return; }
|
||||
f.append("image", file);
|
||||
}
|
||||
var eraAttiva = A.attiva; // #87: l'anteprima si sospende e poi riprende
|
||||
if (eraAttiva) fermaAnteprima();
|
||||
messaggio("Calcolo in corso...", "");
|
||||
["acquisisci", "carica", "salva"].forEach(function (i) { $(i).disabled = true; });
|
||||
try {
|
||||
@@ -209,6 +719,7 @@ async function calcola(conFile, salva) {
|
||||
messaggio("Servizio non raggiungibile.", "errore");
|
||||
} finally {
|
||||
["acquisisci", "carica", "salva"].forEach(function (i) { $(i).disabled = false; });
|
||||
if (eraAttiva) avviaAnteprima();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,14 +727,37 @@ $("acquisisci").onclick = function () { calcola(false, false); };
|
||||
$("carica").onclick = function () { calcola(true, false); };
|
||||
// «Salva» rifa il calcolo con save=true sulla stessa origine (altra acquisizione se da camera)
|
||||
$("salva").onclick = function () { calcola(ultimo ? ultimo.conFile : false, true); };
|
||||
// #87: il pulsante del file e' in italiano, l'input nativo resta nascosto
|
||||
$("scegliFile").onclick = function () { $("file").click(); };
|
||||
$("file").onchange = function () {
|
||||
$("nomeFile").textContent = $("file").files[0] ? $("file").files[0].name : "nessuna immagine scelta";
|
||||
};
|
||||
|
||||
// #87: «Elimina calibrazione» chiede conferma in pagina con un secondo clic (niente finestre del browser)
|
||||
var confermaTimer = null;
|
||||
function annullaConferma() {
|
||||
clearTimeout(confermaTimer);
|
||||
confermaTimer = null;
|
||||
$("elimina").textContent = "Elimina calibrazione";
|
||||
}
|
||||
$("elimina").onclick = async function () {
|
||||
if (!confermaTimer) {
|
||||
$("elimina").textContent = "Confermi? Clic ancora per eliminare";
|
||||
confermaTimer = setTimeout(annullaConferma, 4000);
|
||||
return;
|
||||
}
|
||||
annullaConferma();
|
||||
var sorgente = $("sorgente").value;
|
||||
if (!confirm("Eliminare la calibrazione salvata di " + sorgente + "?")) return;
|
||||
var r = await fetch("/camera/calibration?source=" + encodeURIComponent(sorgente), { method: "DELETE" });
|
||||
messaggio(r.ok ? "Calibrazione eliminata." : await dettaglio(r), r.ok ? "ok" : "errore");
|
||||
try {
|
||||
var r = await fetch("/camera/calibration?source=" + encodeURIComponent(sorgente), { method: "DELETE" });
|
||||
messaggio(r.ok ? "Calibrazione eliminata." : await dettaglio(r), r.ok ? "ok" : "errore");
|
||||
} catch (e) {
|
||||
messaggio("Servizio non raggiungibile.", "errore");
|
||||
}
|
||||
aggiornaStato();
|
||||
};
|
||||
$("sorgente").onchange = aggiornaStato;
|
||||
|
||||
$("sorgente").onchange = function () { cambioSorgente(true); };
|
||||
caricaSorgenti();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Test della pagina Acquisizione camera (#87): contenuto statico di PAGINA, senza servizio."""
|
||||
|
||||
import importlib.util
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
_FILE = Path(__file__).resolve().parents[1] / "calibrazione_pagina.py"
|
||||
_spec = importlib.util.spec_from_file_location("calibrazione_pagina", _FILE)
|
||||
_mod = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(_mod)
|
||||
PAGINA = _mod.PAGINA
|
||||
|
||||
|
||||
def test_titolo_e_stile_scuro():
|
||||
assert "<title>Acquisizione camera</title>" in PAGINA
|
||||
assert "#0f172a" in PAGINA and "#1e293b" in PAGINA and "#3b82f6" in PAGINA
|
||||
|
||||
|
||||
def test_rotte_usate():
|
||||
for rotta in ("/camera/sources", "/camera/anteprima", "/camera/parametri",
|
||||
"/camera/parametri/salva", "/camera/calibrate", "/camera/calibration"):
|
||||
assert '"' + rotta in PAGINA, rotta
|
||||
|
||||
|
||||
def test_offline_e_senza_finestre_del_browser():
|
||||
for vietato in ("alert(", "confirm(", "prompt(", "http://", "https://"):
|
||||
assert vietato not in PAGINA, vietato
|
||||
|
||||
|
||||
def test_id_principali():
|
||||
ids = set(re.findall(r'id="([^"]+)"', PAGINA))
|
||||
attesi = {"sorgente", "avvia", "ferma", "scatta", "grezzo", "mirinoCasella", "immagine",
|
||||
"nitidezza", "nitidezzaMax", "saturati", "media", "dimensioni",
|
||||
"parametri", "salvaParametri", "quadrato", "acquisisci", "scegliFile", "file",
|
||||
"carica", "salva", "elimina", "stato", "statoSorgente"}
|
||||
assert attesi <= ids, attesi - ids
|
||||
# ogni id usato dal JS con $("...") esiste nel markup
|
||||
usati = set(re.findall(r'\$\("([^"]+)"\)', PAGINA))
|
||||
assert usati <= ids, usati - ids
|
||||
|
||||
|
||||
def test_sezioni_e_testi_italiani():
|
||||
for testo in ("Sorgente", "Anteprima", "Parametri camera", "Calibrazione",
|
||||
"Salva come predefiniti", "Scegli immagine...", "Questa sorgente non ha parametri regolabili",
|
||||
"Immagine grezza (senza correzione)"):
|
||||
assert testo in PAGINA, testo
|
||||
assert "it-IT" in PAGINA # numeri con la virgola
|
||||
assert "Choose File" not in PAGINA
|
||||
|
||||
|
||||
def test_localstorage_protetto():
|
||||
# ogni uso di localStorage sta dentro un try
|
||||
for m in re.finditer(r"localStorage[.]", PAGINA):
|
||||
assert "try {" in PAGINA[max(0, m.start() - 200):m.start()]
|
||||
@@ -17,6 +17,7 @@ import math
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import cv2 # #86: soglia/componenti connesse per la maschera del pezzo
|
||||
import numpy as np
|
||||
from visionsuite.core.image import Image
|
||||
|
||||
@@ -113,12 +114,41 @@ def _locate_reference(gray: np.ndarray, polarity: str) -> dict:
|
||||
return pezzo.found_poses[0].to_dict()
|
||||
|
||||
|
||||
def _candidate_anchors(gray: np.ndarray, dxf_path: Path, px_per_mm: float) -> list[tuple[float, float, float]]:
|
||||
def _maschera_pezzo(gray: np.ndarray, polarity: str, px_per_mm: float = 71.0) -> np.ndarray:
|
||||
"""Immagine con solo il pezzo: fuori dal blob staccato dal bordo e' sfondo (#86).
|
||||
|
||||
Otsu (INV se dark), componenti connesse, la piu' grande che NON tocca il
|
||||
bordo immagine (piastre del prisma, ombre e angoli neri della foto
|
||||
raddrizzata ci sono attaccati), dilatata di ~0,3 mm (minimo 15 px).
|
||||
"""
|
||||
flag = cv2.THRESH_BINARY_INV if polarity == "dark" else cv2.THRESH_BINARY
|
||||
_, binary = cv2.threshold(gray, 0, 255, flag | cv2.THRESH_OTSU)
|
||||
n, labels, stats, _ = cv2.connectedComponentsWithStats(binary, connectivity=8)
|
||||
h, w = gray.shape[:2]
|
||||
best, best_area = 0, 0
|
||||
for i in range(1, n): # 0 = sfondo
|
||||
x, y, cw, ch, area = (int(v) for v in stats[i])
|
||||
if x == 0 or y == 0 or x + cw >= w or y + ch >= h:
|
||||
continue # tocca il bordo immagine: non e' il pezzo
|
||||
if area > best_area:
|
||||
best, best_area = i, area
|
||||
if best == 0:
|
||||
raise CostruttoreError("pezzo non trovato: nessun blob staccato dal bordo")
|
||||
raggio = max(15, int(round(0.3 * px_per_mm))) # margine in funzione della scala
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2 * raggio + 1, 2 * raggio + 1))
|
||||
zona = cv2.dilate((labels == best).astype(np.uint8), kernel) > 0
|
||||
sfondo = 255 if polarity == "dark" else 0
|
||||
return np.where(zona, gray, np.uint8(sfondo)).astype(np.uint8)
|
||||
|
||||
|
||||
def _candidate_anchors(gray: np.ndarray, dxf_path: Path, px_per_mm: float,
|
||||
polarity: str = "dark") -> list[tuple[float, float, float]]:
|
||||
"""Pose (riga, col, angolo) del disegno sull'immagine: ICP da 4 orientamenti.
|
||||
|
||||
Il disegno e' in px (origine DXF, y capovolta); si parte da ognuno dei 4
|
||||
angoli con i centroidi sovrapposti e l'ICP rifinisce. Ritorna le posa trovate
|
||||
(anche per orientamenti che non convergono: le giudica la ricetta eseguita).
|
||||
Centroide e ICP lavorano sull'immagine mascherata sul solo pezzo (#86).
|
||||
"""
|
||||
from visionsuite.calibration import ScaleCalibration
|
||||
from visionsuite.dxf.compare import DXFCompare, _stack
|
||||
@@ -126,6 +156,7 @@ def _candidate_anchors(gray: np.ndarray, dxf_path: Path, px_per_mm: float) -> li
|
||||
|
||||
cmp_ = DXFCompare(dxf_path, ScaleCalibration(px_per_mm=px_per_mm))
|
||||
drawing = _stack(cmp_.drawing_contours())
|
||||
gray = _maschera_pezzo(gray, polarity, px_per_mm) # #86: via piastre, ombre, angoli neri
|
||||
measured = _stack(cmp_.measured_contours(Image(gray)))
|
||||
if len(drawing) < 3:
|
||||
raise CostruttoreError("DXF senza geometria utilizzabile")
|
||||
@@ -134,18 +165,22 @@ def _candidate_anchors(gray: np.ndarray, dxf_path: Path, px_per_mm: float) -> li
|
||||
dc, mc = drawing.mean(axis=0), measured.mean(axis=0)
|
||||
|
||||
anchors = []
|
||||
errori = [] # #86: motivo di ogni orientamento caduto, per la diagnosi in campo
|
||||
for theta in _START_ANGLES:
|
||||
# traslazione che porta il centroide del disegno ruotato sul misurato
|
||||
rr, cc = Pose(0.0, 0.0, theta).apply(dc[0], dc[1])
|
||||
start = Pose(float(mc[0] - rr), float(mc[1] - cc), theta)
|
||||
try:
|
||||
result = cmp_.compare(Image(gray), initial_pose=start)
|
||||
except Exception: # noqa: BLE001 - un orientamento che cade non ferma gli altri
|
||||
except Exception as exc: # noqa: BLE001 - un orientamento che cade non ferma gli altri
|
||||
errori.append(f"{theta:g}gradi: {type(exc).__name__}: {exc}") # #86
|
||||
continue
|
||||
# transform: misurato -> disegno; la posa del disegno e' l'inversa
|
||||
m = np.linalg.inv(result.transform)
|
||||
angle = math.degrees(math.atan2(m[1, 0], m[0, 0]))
|
||||
anchors.append((float(m[0, 2]), float(m[1, 2]), angle))
|
||||
if not anchors and errori: # #86: nessuna ancora -> il motivo risale al chiamante
|
||||
raise CostruttoreError("disegno non sovrapponibile al pezzo (ICP fallito): " + "; ".join(errori))
|
||||
return anchors
|
||||
|
||||
|
||||
@@ -199,7 +234,7 @@ def build_dxf_compare(
|
||||
raise CostruttoreError("DXF illeggibile: nessuna entita' geometrica")
|
||||
|
||||
reference_pose = _locate_reference(frame, polarity)
|
||||
anchors = _candidate_anchors(frame, dxf_path, px_per_mm)
|
||||
anchors = _candidate_anchors(frame, dxf_path, px_per_mm, polarity) # #86
|
||||
if not anchors:
|
||||
raise CostruttoreError("disegno non sovrapponibile al pezzo (ICP fallito)")
|
||||
|
||||
|
||||
@@ -21,6 +21,8 @@ from src.vision.costruttori import (
|
||||
CALIBRATION_FILE,
|
||||
DXF_FILE,
|
||||
CostruttoreError,
|
||||
_candidate_anchors,
|
||||
_maschera_pezzo,
|
||||
build_dxf_compare,
|
||||
)
|
||||
from src.vision.runner import run_graph
|
||||
@@ -112,3 +114,37 @@ def test_dxf_illeggibile_solleva():
|
||||
def test_parametri_ricetta_invalidi(kwargs):
|
||||
with pytest.raises(CostruttoreError):
|
||||
build_dxf_compare(a_scene(), SAMPLE_DXF.read_bytes(), **kwargs)
|
||||
|
||||
|
||||
def test_maschera_pezzo_tiene_solo_il_blob_staccato_dal_bordo():
|
||||
# #86: pezzo scuro staccato + rettangoli scuri attaccati al bordo + angolo nero
|
||||
img = np.full((500, 600), 230, np.uint8)
|
||||
img[200:300, 250:400] = 20 # il pezzo
|
||||
img[0:60, 100:220] = 15 # attaccato al bordo alto
|
||||
img[420:500, 300:420] = 15 # attaccato al bordo basso
|
||||
img[0:80, 0:80] = 0 # angolo nero (borderValue=0 del raddrizzamento)
|
||||
out = _maschera_pezzo(img, "dark", px_per_mm=4.0)
|
||||
assert (out[200:300, 250:400] == 20).all() # il pezzo resta
|
||||
assert (out[0:60, 100:220] == 255).all() # i rettangoli sono sfondo
|
||||
assert (out[420:500, 300:420] == 255).all()
|
||||
assert (out[0:80, 0:80] == 255).all() # angolo nero cancellato
|
||||
|
||||
|
||||
def test_maschera_pezzo_senza_blob_staccato_solleva():
|
||||
img = np.full((200, 200), 230, np.uint8)
|
||||
img[:, 0:50] = 10 # solo una fascia attaccata al bordo
|
||||
with pytest.raises(CostruttoreError, match="staccato dal bordo"):
|
||||
_maschera_pezzo(img, "dark")
|
||||
|
||||
|
||||
def test_ricetta_dxf_icp_fallito_riporta_il_motivo(monkeypatch, tmp_path):
|
||||
# #86: l'errore "ICP fallito" porta il messaggio degli orientamenti caduti
|
||||
from visionsuite.dxf.compare import DXFCompare
|
||||
|
||||
def boom(self, *a, **k):
|
||||
raise ValueError("negative dimensions are not allowed")
|
||||
|
||||
monkeypatch.setattr(DXFCompare, "compare", boom)
|
||||
with pytest.raises(CostruttoreError, match="ICP fallito.*negative dimensions"):
|
||||
_candidate_anchors(a_scene(), SAMPLE_DXF, PX_PER_MM)
|
||||
|
||||
|
||||
Vendored
+1
-1
Submodule vendor/visionsuite updated: 2e73691cc3...e0d19dee7e
Reference in New Issue
Block a user