|
@@ -107,24 +107,14 @@
|
|
|
let rafId = null;
|
|
let rafId = null;
|
|
|
let uploadedPhoto = null;
|
|
let uploadedPhoto = null;
|
|
|
let photoFit = null;
|
|
let photoFit = null;
|
|
|
- let erasing = false;
|
|
|
|
|
- const selectionStrokes = [];
|
|
|
|
|
|
|
+ let personBox = null;
|
|
|
|
|
+ let personModel = null;
|
|
|
|
|
+ let detectingPerson = false;
|
|
|
const photoFile = document.getElementById("photoFile");
|
|
const photoFile = document.getElementById("photoFile");
|
|
|
const photoReset = document.getElementById("photoReset");
|
|
const photoReset = document.getElementById("photoReset");
|
|
|
const photoStatus = document.getElementById("photoStatus");
|
|
const photoStatus = document.getElementById("photoStatus");
|
|
|
- const objectTempInput = document.getElementById("objectTemp");
|
|
|
|
|
- const objectTempOut = document.getElementById("objectTempOut");
|
|
|
|
|
const selectionTools = document.getElementById("thermalSelectionTools");
|
|
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 detectPersonBtn = document.getElementById("detectPerson");
|
|
|
|
|
|
|
|
/* ---------- Утилиты ---------- */
|
|
/* ---------- Утилиты ---------- */
|
|
|
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
|
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
|
@@ -395,66 +385,78 @@
|
|
|
}
|
|
}
|
|
|
function drawUploadedThermal() {
|
|
function drawUploadedThermal() {
|
|
|
drawPhotoBase(thermalCtx);
|
|
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="Фон псевдотепловой: яркость фото используется лишь как условная основа. Закрашенные области имеют заданную условную температуру.";
|
|
|
|
|
|
|
+ const ambient=+ambientInput.value, span=+spanInput.value;
|
|
|
|
|
+ thermalReadout.textContent=`Фото · ${paletteInput.value} · ΔT=${span} K`;
|
|
|
|
|
+ thermalFoot.textContent="Фоновая псевдотепловая окраска условна. Для обнаруженного человека поверх фото нанесена прозрачная учебная карта: края холоднее, центральные области и голова/грудь ярче. Реальных температур фото не содержит.";
|
|
|
|
|
+ if(personBox) drawPersonHeatOverlay();
|
|
|
}
|
|
}
|
|
|
function paletteRGB(name,t){
|
|
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];
|
|
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]];
|
|
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);
|
|
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);
|
|
|
|
|
|
|
+ // Draw an approximate anatomical heat distribution in a detected person box.
|
|
|
|
|
+ // Shape is a lightweight silhouette proxy; original photograph remains visible underneath.
|
|
|
|
|
+ function drawPersonHeatOverlay(){
|
|
|
|
|
+ if(!personBox || !photoFit) return;
|
|
|
|
|
+ const [bx,by,bw,bh]=personBox; // mapped to canvas pixels already
|
|
|
|
|
+ const overlay=document.createElement("canvas"); overlay.width=NV_W; overlay.height=NV_H;
|
|
|
|
|
+ const octx=overlay.getContext("2d");
|
|
|
|
|
+ const x=bx,y=by,w=bw,h=bh;
|
|
|
|
|
+ octx.save(); octx.translate(x,y);
|
|
|
|
|
+ // approximate silhouette: head, shoulders/torso, arms, and legs
|
|
|
|
|
+ octx.fillStyle="#fff";
|
|
|
|
|
+ octx.beginPath(); octx.ellipse(w*.50,h*.11,w*.14,h*.105,0,0,Math.PI*2); octx.fill();
|
|
|
|
|
+ octx.beginPath(); octx.moveTo(w*.34,h*.22);octx.quadraticCurveTo(w*.5,h*.17,w*.66,h*.22);octx.lineTo(w*.82,h*.48);octx.quadraticCurveTo(w*.78,h*.53,w*.70,h*.49);octx.lineTo(w*.64,h*.40);octx.lineTo(w*.63,h*.61);octx.lineTo(w*.59,h*.64);octx.lineTo(w*.57,h*.98);octx.lineTo(w*.47,h*.98);octx.lineTo(w*.46,h*.64);octx.lineTo(w*.41,h*.64);octx.lineTo(w*.39,h*.98);octx.lineTo(w*.29,h*.98);octx.lineTo(w*.34,h*.60);octx.lineTo(w*.32,h*.40);octx.lineTo(w*.24,h*.49);octx.quadraticCurveTo(w*.18,h*.53,w*.16,h*.48);octx.closePath();octx.fill();
|
|
|
|
|
+ octx.restore();
|
|
|
|
|
+ const mask=octx.getImageData(0,0,NV_W,NV_H).data;
|
|
|
|
|
+ const img=octx.createImageData(NV_W,NV_H); const d=img.data;
|
|
|
|
|
+ const palette=paletteInput.value, span=+spanInput.value, ambient=+ambientInput.value;
|
|
|
|
|
+ for(let py=Math.max(0,Math.floor(y));py<Math.min(NV_H,Math.ceil(y+h));py++) for(let px=Math.max(0,Math.floor(x));px<Math.min(NV_W,Math.ceil(x+w));px++){
|
|
|
|
|
+ const i=(py*NV_W+px)*4; if(mask[i+3]<10) continue;
|
|
|
|
|
+ const nx=(px-x)/Math.max(1,w), ny=(py-y)/Math.max(1,h);
|
|
|
|
|
+ // Cool outer limbs; warmer trunk. Localized hot spots for head and chest are stylized.
|
|
|
|
|
+ const headHot=Math.exp(-(((nx-.5)/.16)**2+((ny-.11)/.11)**2)*2.2);
|
|
|
|
|
+ const chestHot=Math.exp(-(((nx-.53)/.22)**2+((ny-.38)/.16)**2)*2.1);
|
|
|
|
|
+ const core=Math.exp(-(((nx-.50)/.32)**2+((ny-.43)/.35)**2)*1.5);
|
|
|
|
|
+ const edge=Math.max(0,1-Math.sqrt(((nx-.5)/.5)**2+((ny-.48)/.55)**2));
|
|
|
|
|
+ let temp=ambient+4+12*edge+13*core+22*headHot+24*chestHot;
|
|
|
|
|
+ let t=clamp((temp-(ambient+10-span/2))/Math.max(1,span),0,1);
|
|
|
|
|
+ const heatStops=[[0,8,70],[0,55,210],[0,185,95],[220,245,0],[255,65,0],[255,245,230]];
|
|
|
|
|
+ const c=lerpStops(heatStops,t); d[i]=c[0];d[i+1]=c[1];d[i+2]=c[2];d[i+3]=Math.round(130+90*Math.max(headHot,chestHot,core));
|
|
|
}
|
|
}
|
|
|
- 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";
|
|
|
|
|
|
|
+ octx.putImageData(img,0,0);
|
|
|
|
|
+ thermalCtx.save();thermalCtx.globalAlpha=.72;thermalCtx.drawImage(overlay,0,0);thermalCtx.restore();
|
|
|
}
|
|
}
|
|
|
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};}
|
|
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;}
|
|
|
|
|
- });
|
|
|
|
|
|
|
+ async function loadPersonDetector(){
|
|
|
|
|
+ if(personModel)return personModel;
|
|
|
|
|
+ if(!window.cocoSsd){throw new Error("Модель распознавания не загрузилась. Проверьте интернет.");}
|
|
|
|
|
+ personModel=await window.cocoSsd.load({base:"mobilenet_v2"});
|
|
|
|
|
+ return personModel;
|
|
|
|
|
+ }
|
|
|
|
|
+ async function detectSinglePerson(){
|
|
|
|
|
+ if(!uploadedPhoto||detectingPerson)return; detectingPerson=true; detectPersonBtn.disabled=true;
|
|
|
|
|
+ photoStatus.textContent="Загрузка модели и поиск человека…";
|
|
|
|
|
+ try{
|
|
|
|
|
+ const model=await loadPersonDetector(); const preds=await model.detect(uploadedPhoto);
|
|
|
|
|
+ const people=preds.filter(p=>p.class==="person"&&p.score>.35).sort((a,b)=>b.score-a.score);
|
|
|
|
|
+ if(!people.length){personBox=null;photoStatus.textContent="Человек не обнаружен. Попробуйте фото с человеком в полный рост, достаточно крупным в кадре.";}
|
|
|
|
|
+ else{
|
|
|
|
|
+ const p=people[0], [ox,oy,ow,oh]=p.bbox, f=photoFit;
|
|
|
|
|
+ const sx=f.w/uploadedPhoto.width, sy=f.h/uploadedPhoto.height;
|
|
|
|
|
+ personBox=[f.x+ox*sx,f.y+oy*sy,ow*sx,oh*sy];
|
|
|
|
|
+ photoStatus.textContent=`Найден человек (${Math.round(p.score*100)}%). Отображается учебная карта распределения температуры.`;
|
|
|
|
|
+ }
|
|
|
|
|
+ }catch(err){photoStatus.textContent=err.message||"Ошибка распознавания.";personBox=null;}
|
|
|
|
|
+ detectingPerson=false;detectPersonBtn.disabled=false;scheduleRender();
|
|
|
|
|
+ }
|
|
|
|
|
+ if(detectPersonBtn)detectPersonBtn.addEventListener("click",detectSinglePerson);
|
|
|
if(photoFile)photoFile.addEventListener("change",()=>{
|
|
if(photoFile)photoFile.addEventListener("change",()=>{
|
|
|
const file=photoFile.files?.[0];if(!file)return;if(!file.type.startsWith("image/")){photoStatus.textContent="Выберите файл изображения.";return;}
|
|
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;
|
|
|
|
|
|
|
+ const url=URL.createObjectURL(file), image=new Image();image.onload=()=>{uploadedPhoto=image;personBox=null;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;if(detectPersonBtn)detectPersonBtn.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();});
|
|
|
|
|
|
|
+ if(photoReset)photoReset.addEventListener("click",()=>{uploadedPhoto=null;personBox=null;photoFile.value="";sceneSwitch?.closest("fieldset")?.querySelectorAll("button[data-scene]").forEach(b=>b.disabled=false);if(selectionTools)selectionTools.hidden=true;if(detectPersonBtn)detectPersonBtn.hidden=true;photoReset.hidden=true;photoStatus.textContent="Фото не загружено. Отображается встроенная сцена.";scheduleRender();});
|
|
|
|
|
|
|
|
/* ---------- Квиз ---------- */
|
|
/* ---------- Квиз ---------- */
|
|
|
const answers = {
|
|
const answers = {
|