Przeglądaj źródła

v.0.2.0.4 [color_photo]

ypv 2 dni temu
rodzic
commit
be4bccbf8c

+ 103 - 75
ПМ.03.01/4.7.200/002/app.js

@@ -105,6 +105,26 @@
 
   let activeScene = "forest";
   let rafId = null;
+  let uploadedPhoto = null;
+  let photoFit = null;
+  let erasing = false;
+  const selectionStrokes = [];
+  const photoFile = document.getElementById("photoFile");
+  const photoReset = document.getElementById("photoReset");
+  const photoStatus = document.getElementById("photoStatus");
+  const objectTempInput = document.getElementById("objectTemp");
+  const objectTempOut = document.getElementById("objectTempOut");
+  const selectionTools = document.getElementById("thermalSelectionTools");
+  const eraseSelection = document.getElementById("eraseSelection");
+  const clearSelection = document.getElementById("clearSelection");
+  const detectObjectsBtn = document.getElementById("detectObjects");
+  const detectStatus = document.getElementById("detectStatus");
+  const detectedObjectsEl = document.getElementById("detectedObjects");
+  let detectorModel = null;
+  let autoDetections = [];
+  const maskCanvas = document.createElement("canvas");
+  maskCanvas.width = NV_W; maskCanvas.height = NV_H;
+  const maskCtx = maskCanvas.getContext("2d");
 
   /* ---------- Утилиты ---------- */
   const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
@@ -142,6 +162,7 @@
 
   function drawNV() {
     const scene = scenes[activeScene];
+    if (uploadedPhoto) { drawUploadedNV(); return; }
 
     nvCtx.fillStyle = "#010806";
     nvCtx.fillRect(0, 0, NV_W, NV_H);
@@ -260,6 +281,7 @@
 
   function drawThermal() {
     const scene = scenes[activeScene];
+    if (uploadedPhoto) { drawUploadedThermal(); return; }
     const ambient = parseFloat(ambientInput.value);
     const span    = parseFloat(spanInput.value);
     const paletteName = paletteInput.value;
@@ -319,7 +341,6 @@
   function onControlsChange() {
     updateOutputs();
     scheduleRender();
-    renderPhotoSimulations();
   }
 
   /* ---------- Подписки ---------- */
@@ -347,85 +368,93 @@
   }
 
 
-  /* ---------- Симуляция на загружаемой фотографии ---------- */
-  const photoFile = document.getElementById("photoFile");
-  const photoReset = document.getElementById("photoReset");
-  const photoStatus = document.getElementById("photoStatus");
-  const photoNvCanvas = document.getElementById("photoNvCanvas");
-  const photoThermalCanvas = document.getElementById("photoThermalCanvas");
-  const photoNvReadout = document.getElementById("photoNvReadout");
-  const photoThermalReadout = document.getElementById("photoThermalReadout");
-  const photoNvCtx = photoNvCanvas?.getContext("2d");
-  const photoThermalCtx = photoThermalCanvas?.getContext("2d");
-  let uploadedPhoto = null;
-
-  function fitPhotoCanvas(ctx, canvas, image) {
-    ctx.clearRect(0, 0, canvas.width, canvas.height);
-    const scale = Math.min(canvas.width / image.width, canvas.height / image.height);
-    const w = image.width * scale, h = image.height * scale;
-    ctx.drawImage(image, (canvas.width-w)/2, (canvas.height-h)/2, w, h);
+  /* ---------- Фото заменяет встроенную сцену в тех же canvas ---------- */
+  function fitRect(image) {
+    const scale=Math.min(NV_W/image.width,NV_H/image.height);
+    const w=image.width*scale,h=image.height*scale;
+    return {x:(NV_W-w)/2,y:(NV_H-h)/2,w,h};
   }
-
-  function renderPhotoSimulations() {
-    if (!uploadedPhoto || !photoNvCtx || !photoThermalCtx) return;
-    fitPhotoCanvas(photoNvCtx, photoNvCanvas, uploadedPhoto);
-    fitPhotoCanvas(photoThermalCtx, photoThermalCanvas, uploadedPhoto);
-    const source = photoNvCtx.getImageData(0, 0, NV_W, NV_H);
-    const thermalSource = photoThermalCtx.getImageData(0, 0, NV_W, NV_H);
-    const nvGain = parseFloat(gainInput.value);
-    const luxFactor = clamp(parseFloat(luxInput.value) / 0.05, 0.02, 1);
-    const irFactor = irInput.checked ? 0.32 : 0;
-    const photoNV = source.data;
-    const photoThermal = thermalSource.data;
-    for (let i=0; i<photoNV.length; i+=4) {
-      const luminance = (0.2126*photoNV[i] + 0.7152*photoNV[i+1] + 0.0722*photoNV[i+2]) / 255;
-      const amplified = clamp((luminance * (0.25 + nvGain*1.65) * (0.18 + luxFactor*0.9)) + irFactor*(0.25+luminance), 0, 1);
-      const green = Math.round(255 * Math.pow(amplified, 0.72));
-      photoNV[i] = Math.round(green*0.20); photoNV[i+1] = green; photoNV[i+2] = Math.round(green*0.42);
-      const tl = (0.2126*thermalSource.data[i] + 0.7152*thermalSource.data[i+1] + 0.0722*thermalSource.data[i+2]) / 255;
-      const t = clamp((tl - 0.03) / 0.94, 0, 1);
-      const color = paletteRGB(paletteInput.value, t);
-      photoThermal[i] = color[0]; photoThermal[i+1] = color[1]; photoThermal[i+2] = color[2];
+  function drawPhotoBase(ctx) {
+    ctx.fillStyle="#050505"; ctx.fillRect(0,0,NV_W,NV_H);
+    photoFit=fitRect(uploadedPhoto); ctx.drawImage(uploadedPhoto,photoFit.x,photoFit.y,photoFit.w,photoFit.h);
+  }
+  function drawUploadedNV() {
+    drawPhotoBase(nvCtx);
+    const im=nvCtx.getImageData(0,0,NV_W,NV_H), d=im.data;
+    const gain=parseFloat(gainInput.value), luxFactor=clamp(parseFloat(luxInput.value)/0.05,0.02,1), ir=irInput.checked?0.32:0;
+    for(let i=0;i<d.length;i+=4){
+      const lum=(0.2126*d[i]+0.7152*d[i+1]+0.0722*d[i+2])/255;
+      const amp=clamp((lum*(0.25+gain*1.65)*(0.18+luxFactor*0.9))+ir*(0.25+lum),0,1);
+      const g=Math.round(255*Math.pow(amp,0.72)); d[i]=g*0.20; d[i+1]=g; d[i+2]=g*0.42;
     }
-    photoNvCtx.putImageData(source, 0, 0);
-    photoThermalCtx.putImageData(thermalSource, 0, 0);
-    photoNvReadout.textContent = `Усиление ${nvGain.toFixed(2)}× · ${irInput.checked ? "условная ИК-подсветка" : "без подсветки"}`;
-    photoThermalReadout.textContent = `Псевдопалитра · ${paletteInput.value}`;
+    nvCtx.putImageData(im,0,0);
+    nvCtx.save();nvCtx.globalAlpha=.08;nvCtx.strokeStyle="#7dffb2";
+    for(let y=0;y<NV_H;y+=4){nvCtx.beginPath();nvCtx.moveTo(0,y);nvCtx.lineTo(NV_W,y);nvCtx.stroke();}nvCtx.restore();
+    nvReadout.textContent=`Фото · G=${gain.toFixed(2)}× · ИК=${irInput.checked?"вкл":"выкл"}`;
+    nvFoot.textContent="Учебная симуляция ЭОП: яркость исходного фото условно зависит от усиления, освещённости и ИК-подсветки. Спектральные данные фото отсутствуют.";
   }
-
-  function paletteRGB(name, t) {
-    t = clamp(t, 0, 1);
-    if (name === "whiteHot") return [Math.round(255*t),Math.round(255*t),Math.round(255*t)];
-    if (name === "blackHot") return [Math.round(255*(1-t)),Math.round(255*(1-t)),Math.round(255*(1-t))];
-    let stops;
-    if (name === "ironbow") stops=[[0,0,0],[40,0,70],[140,30,20],[230,120,0],[255,210,40],[255,255,255]];
-    else if (name === "rainbow") stops=[[0,0,70],[0,160,255],[0,220,120],[255,230,0],[255,80,0],[255,255,255]];
-    else stops=[[20,0,30],[120,0,90],[220,40,20],[255,160,0],[255,255,180]];
-    const n=stops.length-1, p=t*n, idx=Math.floor(p), f=p-idx, a=stops[idx], b=stops[Math.min(n,idx+1)];
-    return [0,1,2].map(k=>Math.round(a[k]+(b[k]-a[k])*f));
+  function drawUploadedThermal() {
+    drawPhotoBase(thermalCtx);
+    const base=thermalCtx.getImageData(0,0,NV_W,NV_H), mask=maskCtx.getImageData(0,0,NV_W,NV_H);
+    const d=base.data, m=mask.data, ambient=+ambientInput.value, span=+spanInput.value, center=ambient+10, minT=center-span/2,maxT=center+span/2;
+    for(let i=0;i<d.length;i+=4){
+      const lum=(0.2126*d[i]+0.7152*d[i+1]+0.0722*d[i+2])/255;
+      // Photo luminance is only a visual proxy for the unmarked background, not temperature.
+      let tApp=ambient+(lum-0.5)*span*0.65;
+      if(m[i+3]>0){ const encoded=m[i]; tApp=270+(encoded/255)*90; }
+      const t=clamp((tApp-minT)/(maxT-minT),0,1), c=paletteRGB(paletteInput.value,t);
+      d[i]=c[0];d[i+1]=c[1];d[i+2]=c[2];d[i+3]=255;
+    }
+    thermalCtx.putImageData(base,0,0);
+    thermalReadout.textContent=`Фото · палитра ${paletteInput.value} · ΔT=${span} K`;
+    thermalFoot.textContent="Фон псевдотепловой: яркость фото используется лишь как условная основа. Закрашенные области имеют заданную условную температуру.";
   }
-
-  if (photoFile) photoFile.addEventListener("change", () => {
-    const file = photoFile.files?.[0];
-    if (!file) return;
-    if (!file.type.startsWith("image/")) { photoStatus.textContent = "Выберите файл изображения."; return; }
-    const url = URL.createObjectURL(file);
-    const image = new Image();
-    image.onload = () => {
-      uploadedPhoto = image;
-      renderPhotoSimulations();
-      photoStatus.textContent = `Загружено: ${file.name} (${image.width}×${image.height}). Обработка выполняется локально в браузере.`;
-      URL.revokeObjectURL(url);
-    };
-    image.onerror = () => { photoStatus.textContent = "Не удалось открыть изображение."; URL.revokeObjectURL(url); };
-    image.src = url;
+  function paletteRGB(name,t){
+    t=clamp(t,0,1); if(name==="whiteHot")return [255*t|0,255*t|0,255*t|0];if(name==="blackHot")return [255*(1-t)|0,255*(1-t)|0,255*(1-t)|0];
+    let stops=name==="ironbow"?[[0,0,0],[40,0,70],[140,30,20],[230,120,0],[255,210,40],[255,255,255]]:name==="rainbow"?[[0,0,70],[0,160,255],[0,220,120],[255,230,0],[255,80,0],[255,255,255]]:[[20,0,30],[120,0,90],[220,40,20],[255,160,0],[255,255,180]];
+    return lerpStops(stops,t);
+  }
+  function redrawMask() {
+    maskCtx.clearRect(0,0,NV_W,NV_H);
+    // Auto detections are rectangular educational masks with editable temperatures.
+    for (const det of autoDetections) {
+      const [x,y,w,h] = det.box;
+      const encoded = Math.round(clamp((det.temp-270)/90,0,1)*255);
+      maskCtx.fillStyle = `rgb(${encoded},0,0)`;
+      maskCtx.fillRect(x,y,w,h);
+    }
+    for(const stroke of selectionStrokes){maskCtx.globalCompositeOperation=stroke.erase?"destination-out":"source-over";maskCtx.strokeStyle=`rgb(${Math.round((stroke.temp-270)/90*255)},0,0)`;maskCtx.lineWidth=stroke.radius*2;maskCtx.lineCap="round";maskCtx.lineJoin="round";maskCtx.beginPath();stroke.points.forEach((pt,i)=>i?maskCtx.lineTo(pt.x,pt.y):maskCtx.moveTo(pt.x,pt.y));if(stroke.points.length===1)maskCtx.lineTo(stroke.points[0].x+.01,stroke.points[0].y+.01);maskCtx.stroke();}maskCtx.globalCompositeOperation="source-over";
+  }
+  function canvasPoint(canvas,e){const r=canvas.getBoundingClientRect();return {x:(e.clientX-r.left)*canvas.width/r.width,y:(e.clientY-r.top)*canvas.height/r.height};}
+  thermalCanvas.style.touchAction="none";
+  let drawing=false, currentStroke=null;
+  thermalCanvas.addEventListener("pointerdown",e=>{if(!uploadedPhoto)return;drawing=true;thermalCanvas.setPointerCapture(e.pointerId);currentStroke={temp:+objectTempInput.value,erase:erasing,radius:erasing?22:12,points:[canvasPoint(thermalCanvas,e)]};selectionStrokes.push(currentStroke);});
+  thermalCanvas.addEventListener("pointermove",e=>{if(!drawing||!currentStroke)return;currentStroke.points.push(canvasPoint(thermalCanvas,e));redrawMask();scheduleRender();});
+  thermalCanvas.addEventListener("pointerup",()=>{drawing=false;currentStroke=null;redrawMask();scheduleRender();});
+  thermalCanvas.addEventListener("pointercancel",()=>{drawing=false;currentStroke=null;});
+  if(objectTempInput)objectTempInput.addEventListener("input",()=>{objectTempOut.textContent=`${objectTempInput.value} K`;erasing=false;eraseSelection?.classList.remove("active");});
+  if(eraseSelection)eraseSelection.addEventListener("click",()=>{erasing=!erasing;eraseSelection.classList.toggle("active",erasing);});
+  if(clearSelection)clearSelection.addEventListener("click",()=>{selectionStrokes.length=0;autoDetections=[];if(detectedObjectsEl)detectedObjectsEl.innerHTML="";redrawMask();scheduleRender();});
+  // COCO-SSD object detection is optional and runs locally in the browser after model download.
+  const objectTempDefaults = {person:307, car:335, truck:340, bus:340, motorcycle:330, bicycle:300, dog:306, cat:306, bird:300, horse:305, sheep:300, cow:305, bear:308, elephant:305, laptop:315, tv:300, cell_phone:310, bottle:295, cup:305, chair:295, sofa:300, dining_table:295, keyboard:310, mouse:310};
+  if(detectObjectsBtn) detectObjectsBtn.addEventListener("click", async () => {
+    if(!uploadedPhoto){ if(detectStatus)detectStatus.textContent="Сначала загрузите фотографию."; return; }
+    if(!window.cocoSsd || !window.tf){ if(detectStatus)detectStatus.textContent="Модель распознавания недоступна. Проверьте интернет и перезагрузите страницу; ручная кисть работает."; return; }
+    detectObjectsBtn.disabled=true; if(detectStatus)detectStatus.textContent="Загрузка модели / распознавание…";
+    try {
+      if(!detectorModel){ await window.tf.ready(); detectorModel=await window.cocoSsd.load({base:"lite_mobilenet_v2"}); }
+      const predictions=await detectorModel.detect(uploadedPhoto);
+      autoDetections=predictions.filter(p=>p.score>=0.45).map(p=>({class:p.class,score:p.score,box:[fitRect(uploadedPhoto).x+p.bbox[0]*fitRect(uploadedPhoto).w/uploadedPhoto.width,fitRect(uploadedPhoto).y+p.bbox[1]*fitRect(uploadedPhoto).h/uploadedPhoto.height,p.bbox[2]*fitRect(uploadedPhoto).w/uploadedPhoto.width,p.bbox[3]*fitRect(uploadedPhoto).h/uploadedPhoto.height],temp:objectTempDefaults[p.class]||307}));
+      if(detectedObjectsEl){detectedObjectsEl.innerHTML="";autoDetections.forEach((det,i)=>{const row=document.createElement("div");row.className="detected-row";const label=document.createElement("label");label.className="detected-label";label.textContent=`${i+1}. ${det.class} (${Math.round(det.score*100)}%) · ${det.temp} K`;const slider=document.createElement("input");slider.type="range";slider.min="270";slider.max="360";slider.value=det.temp;slider.setAttribute("aria-label",`Температура объекта ${det.class}`);slider.addEventListener("input",()=>{det.temp=+slider.value;label.textContent=`${i+1}. ${det.class} (${Math.round(det.score*100)}%) · ${det.temp} K`;redrawMask();scheduleRender();});row.append(label,slider);detectedObjectsEl.append(row);});}
+      redrawMask();scheduleRender();if(detectStatus)detectStatus.textContent=autoDetections.length?`Найдено объектов: ${autoDetections.length}. Обнаружение приблизительное, редактируйте маски вручную.`:"Объекты не обнаружены с достаточной уверенностью. Попробуйте ручную кисть.";
+    } catch(err){ console.error(err); if(detectStatus)detectStatus.textContent="Не удалось выполнить распознавание. Можно использовать ручное выделение."; }
+    finally{detectObjectsBtn.disabled=false;}
   });
-  if (photoReset) photoReset.addEventListener("click", () => {
-    uploadedPhoto = null; if (photoFile) photoFile.value = "";
-    [photoNvCanvas, photoThermalCanvas].forEach(c => c && c.getContext("2d").clearRect(0,0,c.width,c.height));
-    if (photoStatus) photoStatus.textContent = "Пока изображение не загружено.";
-    if (photoNvReadout) photoNvReadout.textContent = "—"; if (photoThermalReadout) photoThermalReadout.textContent = "—";
+  if(photoFile)photoFile.addEventListener("change",()=>{
+    const file=photoFile.files?.[0];if(!file)return;if(!file.type.startsWith("image/")){photoStatus.textContent="Выберите файл изображения.";return;}
+    const url=URL.createObjectURL(file), image=new Image();image.onload=()=>{uploadedPhoto=image;selectionStrokes.length=0;autoDetections=[];if(detectedObjectsEl)detectedObjectsEl.innerHTML="";redrawMask();sceneSwitch?.closest("fieldset")?.querySelectorAll("button[data-scene]").forEach(b=>b.disabled=true);if(sceneHint)sceneHint.textContent="Загруженная фотография заменяет встроенную сцену в обоих окнах.";if(photoReset)photoReset.hidden=false;if(selectionTools)selectionTools.hidden=false;photoStatus.textContent=`Загружено: ${file.name} · ${image.width}×${image.height}. Обработка локальная.`;scheduleRender();URL.revokeObjectURL(url);};image.onerror=()=>{photoStatus.textContent="Не удалось открыть изображение.";URL.revokeObjectURL(url);};image.src=url;
   });
+  if(photoReset)photoReset.addEventListener("click",()=>{uploadedPhoto=null;photoFile.value="";selectionStrokes.length=0;autoDetections=[];if(detectedObjectsEl)detectedObjectsEl.innerHTML="";maskCtx.clearRect(0,0,NV_W,NV_H);sceneSwitch?.closest("fieldset")?.querySelectorAll("button[data-scene]").forEach(b=>b.disabled=false);if(selectionTools)selectionTools.hidden=true;photoReset.hidden=true;photoStatus.textContent="Фото не загружено. Отображается встроенная сцена.";scheduleRender();});
 
   /* ---------- Квиз ---------- */
   const answers = {
@@ -482,7 +511,6 @@
   /* ---------- Запуск ---------- */
   updateOutputs();
   render();
-  renderPhotoSimulations();
 
   // Плавный "живой" шум сенсоров
   setInterval(render, 140);

+ 17 - 23
ПМ.03.01/4.7.200/002/index.html

@@ -46,6 +46,20 @@
     <section class="controls" aria-label="Настройки модели">
       <fieldset>
         <legend>Сцена</legend>
+        <div class="photo-upload-inline">
+          <label for="photoFile" class="upload-label">Загрузить фото для замены сцены (JPG, PNG, WebP)</label>
+          <input id="photoFile" type="file" accept="image/*">
+          <button type="button" id="photoReset" hidden>Вернуться к встроенной сцене</button>
+          <span id="photoStatus" class="hint">Фото заменит текущую сцену в обоих окнах.</span>
+        </div>
+        <div class="thermal-selection-tools" id="thermalSelectionTools" hidden>
+          <div class="auto-detect-row"><button type="button" id="detectObjects">Автоматически найти объекты</button><span id="detectStatus" class="hint">Распознавание объектов загружает модель при наличии интернета.</span></div>
+          <div id="detectedObjects" class="detected-objects" aria-live="polite"></div>
+          <strong>Выделение тёплых объектов на тепловизоре</strong>
+          <label>Температура выделения, K <input id="objectTemp" type="range" min="270" max="360" step="1" value="307"><output id="objectTempOut">307 K</output></label>
+          <div class="selection-buttons"><button type="button" id="eraseSelection">Ластик</button><button type="button" id="clearSelection">Очистить выделения</button></div>
+          <p class="hint">Рисуйте мышью или пальцем по тёплым объектам на правом изображении. Выделение назначает условную температуру и не является измерением.</p>
+        </div>
         <div class="scene-switch" id="sceneSwitch">
           <button type="button" data-scene="forest" class="active">Лес</button>
           <button type="button" data-scene="city">Город</button>
@@ -106,29 +120,6 @@
     </section>
 
 
-    <section class="photo-mode" aria-label="Симуляция приборов на реальной фотографии">
-      <h2>Работа с реальной фотографией</h2>
-      <p class="hint photo-intro">Загрузите фотографию и сравните учебную симуляцию ЭОП и тепловизора. Это не настоящие ночные или температурные данные: исходное фото не содержит спектральной информации или измерений температуры.</p>
-      <div class="photo-upload">
-        <label for="photoFile" class="upload-label">Выберите изображение (JPG, PNG, WebP)</label>
-        <input id="photoFile" type="file" accept="image/*">
-        <button type="button" id="photoReset">Очистить фотографию</button>
-        <span id="photoStatus" class="hint">Пока изображение не загружено.</span>
-      </div>
-      <div class="stage photo-stage">
-        <article class="panel nv">
-          <div class="panel-head"><div class="panel-title"><span class="dot"></span>Симуляция ЭОП</div><div class="readout" id="photoNvReadout">—</div></div>
-          <canvas id="photoNvCanvas" width="720" height="405"></canvas>
-          <div class="panel-foot">Серый уровень исходной фотографии преобразуется в зелёное изображение с моделируемым усилением. ИК-подсветка условно повышает видимость.</div>
-        </article>
-        <article class="panel thermal">
-          <div class="panel-head"><div class="panel-title"><span class="dot"></span>Симуляция тепловизора</div><div class="readout" id="photoThermalReadout">—</div></div>
-          <canvas id="photoThermalCanvas" width="720" height="405"></canvas>
-          <div class="panel-foot">Псевдотепловая палитра отображает яркость исходного фото, а не реальную температуру или ИК-излучение.</div>
-        </article>
-      </div>
-    </section>
-
     <section class="quiz" id="quiz">
       <h2>Проверка знаний</h2>
 
@@ -186,6 +177,9 @@
     </section>
   </main>
 
+  <!-- COCO-SSD: необязательное распознавание объектов (требует интернет при первом запуске) -->
+  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.20.0/dist/tf.min.js" defer></script>
+  <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd@2.2.3/dist/coco-ssd.min.js" defer></script>
   <script src="app.js" defer></script>
 </body>
 </html>

+ 4 - 0
ПМ.03.01/4.7.200/002/specification.md

@@ -2,6 +2,10 @@
 
 - **Что изменено:**
 
+
+автоматическое выделение полностью перекрывает обьект. давай упрстим: на фото будет только один человек. Автоматическое выделение находит прямоугольник человека, его не заслоняет и разукрашивает в разные цвета согласно средней температуре человеческого тела: на краях менее ярко, зелеными синими тонами, к центру ярче, голова и сердце самые яркие, красные цвета.
+v.0.2.0.4 [color_photo]
+
 загружаемая фотография должна быть на месте текущей схемы (заменять ее), должны быть и отображаться на схеме выбранные ползунками параметры, в тепловизоре должны быть выделены теплые объекты (предложи, как это сделать)
 v.0.2.0.3 [photo]
 

+ 23 - 0
ПМ.03.01/4.7.200/002/style.css

@@ -428,3 +428,26 @@ input:focus {
 .photo-upload input[type="file"] { max-width: 100%; color: var(--muted); }
 .photo-stage { margin-top: 0; }
 @media (max-width: 620px) { .photo-upload { align-items: flex-start; flex-direction: column; } }
+
+/* Photo replacement / manual thermal marking */
+.photo-upload-inline { display:grid; gap:.55rem; margin-bottom:1rem; }
+.photo-upload-inline input[type=file] { max-width:100%; }
+.photo-upload-inline button, .selection-buttons button { cursor:pointer; }
+.thermal-selection-tools { margin-top:1rem; padding:1rem; border:1px solid rgba(255,170,60,.35); border-radius:12px; display:grid; gap:.65rem; }
+.thermal-selection-tools[hidden] { display:none; }
+.thermal-selection-tools label { display:flex; align-items:center; gap:.7rem; flex-wrap:wrap; }
+.thermal-selection-tools input[type=range] { flex:1; min-width:150px; }
+.selection-buttons { display:flex; gap:.5rem; flex-wrap:wrap; }
+#thermalCanvas { cursor:crosshair; }
+#eraseSelection.active { outline:2px solid #e5a65b; }
+#photoReset[hidden] { display:none; }
+
+/* Automatic object detection controls */
+.auto-detect-row { display:flex; align-items:center; flex-wrap:wrap; gap:.75rem; }
+#detectObjects { border-color:rgba(255,184,107,.65); background:rgba(255,184,107,.10); }
+#detectObjects:disabled { opacity:.65; cursor:wait; }
+.detected-objects { display:grid; gap:.7rem; }
+.detected-row { display:grid; grid-template-columns:minmax(180px,1fr) minmax(120px,1.3fr); align-items:center; gap:.6rem; padding:.65rem; border:1px solid var(--line2); border-radius:10px; }
+.detected-row label { margin:0; color:var(--text); font-size:12px; }
+.detected-row input[type=range] { width:100%; }
+@media(max-width:620px){.detected-row{grid-template-columns:1fr;}}