Procházet zdrojové kódy

v.0.2.0.6 [color_man]

ypv před 2 dny
rodič
revize
ec7867563a

+ 49 - 36
ПМ.03.01/4.7.200/002/app.js

@@ -109,6 +109,7 @@
   let photoFit = null;
   let personBox = null;
   let personModel = null;
+  let personMask = null;
   let detectingPerson = false;
   const photoFile = document.getElementById("photoFile");
   const photoReset = document.getElementById("photoReset");
@@ -398,65 +399,77 @@
   // 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
+    if(!personBox || !photoFit || !personMask) return;
+    const {data:maskData,width:maskW,height:maskH}=personMask;
+    const [bx,by,bw,bh]=personBox;
     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 img=octx.createImageData(NV_W,NV_H), 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));
+    // Map the model's segmentation mask into the letterboxed photo area.
+    for(let py=Math.max(0,Math.floor(by));py<Math.min(NV_H,Math.ceil(by+bh));py++){
+      for(let px=Math.max(0,Math.floor(bx));px<Math.min(NV_W,Math.ceil(bx+bw));px++){
+        const nx=(px-bx)/Math.max(1,bw), ny=(py-by)/Math.max(1,bh);
+        const mx=Math.min(maskW-1,Math.max(0,Math.floor((px-photoFit.x)/photoFit.w*maskW)));
+        const my=Math.min(maskH-1,Math.max(0,Math.floor((py-photoFit.y)/photoFit.h*maskH)));
+        if(px<photoFit.x||px>=photoFit.x+photoFit.w||py<photoFit.y||py>=photoFit.y+photoFit.h) continue;
+        if(maskData[my*maskW+mx]===0) continue;
+        // A stylized anatomical heat profile: cool peripheral areas, warmer core,
+        // head and upper chest as distinct local maxima. Not real thermometry.
+        const head=Math.exp(-((((nx-.50)/.17)**2)+(((ny-.105)/.10)**2))*2.0);
+        const chest=Math.exp(-((((nx-.51)/.23)**2)+(((ny-.36)/.20)**2))*1.65);
+        const core=Math.exp(-((((nx-.50)/.29)**2)+(((ny-.43)/.34)**2))*1.25);
+        const shoulder=Math.exp(-((((nx-.50)/.34)**2)+(((ny-.24)/.13)**2))*1.3);
+        const outer=Math.max(0,Math.min(1,1-Math.pow(Math.abs(nx-.5)*2,1.25)*.62-Math.pow(Math.max(0,ny-.35),1.15)*.25));
+        let temp=ambient+3+10*outer+12*core+25*head+22*chest+5*shoulder;
+        let t=clamp((temp-(ambient+5-span/2))/Math.max(1,span),0,1);
+        // Body-specific blue/green periphery to yellow/orange/red hot areas.
+        const bodyStops=[[0,18,85],[0,75,210],[0,185,125],[170,230,30],[255,145,0],[245,45,20],[255,215,170]];
+        const c=lerpStops(bodyStops,t);
+        const idx=(py*NV_W+px)*4;
+        d[idx]=c[0];d[idx+1]=c[1];d[idx+2]=c[2];
+        // Preserve photographic details: semi-transparent overlay, stronger in hot core.
+        d[idx+3]=Math.round(95+55*Math.max(head,chest,core));
+      }
     }
     octx.putImageData(img,0,0);
-    thermalCtx.save();thermalCtx.globalAlpha=.72;thermalCtx.drawImage(overlay,0,0);thermalCtx.restore();
+    thermalCtx.save();thermalCtx.globalAlpha=.86;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};}
   async function loadPersonDetector(){
     if(personModel)return personModel;
-    if(!window.cocoSsd){throw new Error("Модель распознавания не загрузилась. Проверьте интернет.");}
-    personModel=await window.cocoSsd.load({base:"mobilenet_v2"});
+    if(!window.bodyPix){throw new Error("Модель сегментации не загрузилась. Проверьте интернет.");}
+    personModel=await window.bodyPix.load({architecture:"MobileNetV1",outputStride:16,multiplier:0.75,quantBytes:2});
     return personModel;
   }
   async function detectSinglePerson(){
     if(!uploadedPhoto||detectingPerson)return; detectingPerson=true; detectPersonBtn.disabled=true;
-    photoStatus.textContent="Загрузка модели и поиск человека…";
+    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="Человек не обнаружен. Попробуйте фото с человеком в полный рост, достаточно крупным в кадре.";}
+      const model=await loadPersonDetector();
+      const seg=await model.segmentPerson(uploadedPhoto,{internalResolution:"medium",segmentationThreshold:0.7});
+      const maskData=seg.data, maskW=seg.width, maskH=seg.height;
+      let minX=maskW,minY=maskH,maxX=-1,maxY=-1;
+      for(let y=0;y<maskH;y++)for(let x=0;x<maskW;x++)if(maskData[y*maskW+x]>0){minX=Math.min(minX,x);minY=Math.min(minY,y);maxX=Math.max(maxX,x);maxY=Math.max(maxY,y);}
+      if(maxX<0){personBox=null;personMask=null;photoStatus.textContent="Человек не выделен. Попробуйте фото с человеком крупнее и на контрастном фоне.";}
       else{
-        const p=people[0], [ox,oy,ow,oh]=p.bbox, f=photoFit;
+        // Mask is fitted to image dimensions. Bounding box is derived from segmented pixels,
+        // not detector padding, so the overlay covers the visible person more closely.
+        const f=fitRect(uploadedPhoto);
         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)}%). Отображается учебная карта распределения температуры.`;
+        personBox=[f.x+minX/maskW*f.w,f.y+minY/maskH*f.h,(maxX-minX+1)/maskW*f.w,(maxY-minY+1)/maskH*f.h];
+        personMask={data:maskData,width:maskW,height:maskH};
+        photoStatus.textContent="Силуэт человека выделен по пикселям. Нанесена условная анатомическая тепловая карта.";
       }
-    }catch(err){photoStatus.textContent=err.message||"Ошибка распознавания.";personBox=null;}
+    }catch(err){photoStatus.textContent=err.message||"Ошибка сегментации.";personBox=null;personMask=null;}
     detectingPerson=false;detectPersonBtn.disabled=false;scheduleRender();
   }
   if(detectPersonBtn)detectPersonBtn.addEventListener("click",detectSinglePerson);
   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;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;
+    const url=URL.createObjectURL(file), image=new Image();image.onload=()=>{uploadedPhoto=image;personBox=null;personMask=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;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();});
+  if(photoReset)photoReset.addEventListener("click",()=>{uploadedPhoto=null;personBox=null;personMask=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 = {

+ 2 - 2
ПМ.03.01/4.7.200/002/index.html

@@ -50,7 +50,7 @@
           <label for="photoFile" class="upload-label">Загрузить фото для замены сцены (JPG, PNG, WebP)</label>
           <input id="photoFile" type="file" accept="image/*">
           <button type="button" id="photoReset" hidden>Вернуться к встроенной сцене</button>
-          <button type="button" id="detectPerson" hidden>Найти человека и построить тепловую карту</button>
+          <button type="button" id="detectPerson" hidden>Выделить силуэт и построить тепловую карту</button>
           <span id="photoStatus" class="hint">Фото заменит текущую сцену в обоих окнах.</span>
         </div>
         <div class="thermal-selection-tools" id="thermalSelectionTools" hidden>
@@ -175,7 +175,7 @@
   </main>
 
   <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.17.0/dist/tf.min.js"></script>
-  <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd@2.2.3/dist/coco-ssd.min.js"></script>
+  <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/body-pix@2.0.5/dist/body-pix.min.js"></script>
   <script src="app.js" defer></script>
 </body>
 </html>

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

@@ -3,8 +3,19 @@
 - **Что изменено:**
 
 
+сегментация отлично, менять не надо. Надо сделать более реалистичным фон (черно-белый, неяркий) и самого человека аналогично
+v.0.2.0.6 [color_man]
+
 человек на фото будет по колени снизу, сейчас он считается как весь и контур окрашивания примерно вполовину меньше реального
 v.0.2.0.5 [color_size]
+Исправил подход к окрашиванию: вместо условного силуэта, нарисованного внутри прямоугольника, теперь используется пиксельная сегментация человека (BodyPix). Это принципиальное изменение.
+- Обрабатывается реальный контур выделенного человека, а не геометрическая фигура.
+- Контур рассчитывается по маске модели, поэтому при кадрировании человека по колени или по пояс карта должна соответствовать видимой части тела.
+- Цвета накладываются полупрозрачно, с сохранением деталей фотографии.
+- Тепловой градиент распределяется по силуэту: прохладные периферийные области, более тёплый центр, отдельные яркие зоны головы и грудной области.
+- Прежнее распознавание рамки COCO-SSD заменено сегментацией.
+
+
 
 автоматическое выделение полностью перекрывает обьект. давай упрстим: на фото будет только один человек. Автоматическое выделение находит прямоугольник человека, его не заслоняет и разукрашивает в разные цвета согласно средней температуре человеческого тела: на краях менее ярко, зелеными синими тонами, к центру ярче, голова и сердце самые яркие, красные цвета.
 v.0.2.0.4 [color_photo]