Преглед изворни кода

v.0.2.0.8 [color_artefacts] ✅ DONE

ypv пре 2 дана
родитељ
комит
a61646b4d5

BIN
ПМ.03.01/4.7.200/002/IMG_20261125_112903.jpg


+ 192 - 52
ПМ.03.01/4.7.200/002/app.js

@@ -396,57 +396,100 @@
     nvFoot.textContent="Учебная симуляция ЭОП: яркость исходного фото условно зависит от усиления, освещённости и ИК-подсветки. Спектральные данные фото отсутствуют.";
   }
   function drawUploadedThermal() {
-    // Both the background and the uncolored human remain a dim monochrome photo.
-    // The segmented thermal layer is a restrained transparent color overlay.
-    drawPhotoBase(thermalCtx,true,0.43);
-    const ambient=+ambientInput.value, span=+spanInput.value;
-    thermalReadout.textContent=`Фото · ${paletteInput.value} · ΔT=${span} K`;
-    thermalFoot.textContent="Фон и исходные детали человека приглушены в чёрно-белом виде. Поверх сегментированного силуэта нанесена прозрачная учебная тепловая карта: периферия холоднее, центр и голова/грудь теплее. Это не измерение температуры.";
-    if(personBox) drawPersonHeatOverlay();
+    // Keep the original photograph as a very subdued monochrome texture.
+    // The segmented heat map should be the dominant, high-contrast layer.
+    drawPhotoBase(thermalCtx, true, 0.24);
+    const ambient = +ambientInput.value;
+    const span = +spanInput.value;
+    thermalReadout.textContent = `Фото · T_фона=${ambient} K · ΔT=${span} K · ${paletteInput.value}`;
+    thermalFoot.textContent = `T_фона=${ambient} K: повышение температуры окружения уменьшает температурный контраст и сдвигает цвета человека к холодному краю шкалы. Карта условная, не измеряет температуру.`;
+    if (personBox) drawPersonHeatOverlay();
   }
   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);
   }
-  // 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 || !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 img=octx.createImageData(NV_W,NV_H), d=img.data;
-    const palette=paletteInput.value, span=+spanInput.value, ambient=+ambientInput.value;
-    // 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(78+48*Math.max(head,chest,core));
+  // Draw the teaching heat map inside the filled outer-contour mask derived from BodyPix.
+  // Internal segmentation holes are deliberately ignored; only the external silhouette matters.
+  function drawPersonHeatOverlay() {
+    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 img = octx.createImageData(NV_W, NV_H);
+    const d = img.data;
+    const span = +spanInput.value;
+    const ambient = +ambientInput.value;
+
+    // Fixed illustrative skin-surface temperatures (K), deliberately independent
+    // of ambient temperature. This makes the background-temperature slider affect
+    // the relative contrast exactly as a thermal display reference should.
+    // ΔT controls the width of the display window: narrow range = stronger contrast.
+    const displayCenter = ambient + 10;
+    const displayMin = displayCenter - span / 2;
+    const displaySpan = Math.max(1, span);
+
+    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);
+        const 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;
+
+        // Anatomical heat profile: cooler extremities, warmer torso, strongest
+        // local maxima at the head and upper chest. This is not thermometry.
+        const head = Math.exp(-((((nx - 0.50) / 0.17) ** 2) + (((ny - 0.105) / 0.10) ** 2)) * 2.0);
+        const chest = Math.exp(-((((nx - 0.51) / 0.23) ** 2) + (((ny - 0.36) / 0.20) ** 2)) * 1.65);
+        const core = Math.exp(-((((nx - 0.50) / 0.29) ** 2) + (((ny - 0.43) / 0.34) ** 2)) * 1.25);
+        const shoulder = Math.exp(-((((nx - 0.50) / 0.34) ** 2) + (((ny - 0.24) / 0.13) ** 2)) * 1.3);
+        const outer = clamp(
+          1 - Math.pow(Math.abs(nx - 0.5) * 2, 1.25) * 0.62 - Math.pow(Math.max(0, ny - 0.35), 1.15) * 0.25,
+          0,
+          1
+        );
+
+        // Approximate absolute apparent skin temperatures, Kelvin.
+        // Head/chest are hottest; the outer silhouette remains cooler.
+        const temp = 289 + 3 * outer + 5 * core + 11 * head + 10 * chest + 2 * shoulder;
+        const t = clamp((temp - displayMin) / displaySpan, 0, 1);
+        // Slight gamma compression keeps cooler extremities blue/green while
+        // allowing the head and chest to reach vivid orange/red values.
+        const colorT = Math.pow(t, 1.35);
+
+        // Saturated blue -> cyan -> green -> yellow -> orange -> red scale.
+        const bodyStops = [
+          [0, 18, 105],
+          [0, 75, 220],
+          [0, 190, 220],
+          [0, 220, 105],
+          [210, 245, 0],
+          [255, 145, 0],
+          [255, 35, 0],
+          [255, 225, 185]
+        ];
+        const c = lerpStops(bodyStops, colorT);
+        const idx = (py * NV_W + px) * 4;
+        d[idx] = c[0];
+        d[idx + 1] = c[1];
+        d[idx + 2] = c[2];
+        // High opacity makes the temperature field readable; a little original
+        // monochrome texture remains visible beneath the color.
+        d[idx + 3] = Math.round(205 + 42 * colorT);
       }
     }
-    octx.putImageData(img,0,0);
-    thermalCtx.save();thermalCtx.globalAlpha=.72;thermalCtx.drawImage(overlay,0,0);thermalCtx.restore();
+
+    octx.putImageData(img, 0, 0);
+    thermalCtx.save();
+    thermalCtx.globalAlpha = 0.90;
+    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(){
@@ -455,24 +498,121 @@
     personModel=await window.bodyPix.load({architecture:"MobileNetV1",outputStride:16,multiplier:0.75,quantBytes:2});
     return personModel;
   }
+  // Build a render-only silhouette from the BodyPix result:
+  // keep the largest foreground component and fill every background pocket
+  // enclosed by its OUTER contour. The model output itself is never modified.
+  function makeOuterContourMask(rawData, width, height) {
+    const size = width * height;
+    const foreground = new Uint8Array(size);
+    for (let i = 0; i < size; i++) foreground[i] = rawData[i] > 0 ? 1 : 0;
+
+    // 1) Find the largest 8-connected foreground component (the person).
+    const visited = new Uint8Array(size);
+    const queue = new Int32Array(size);
+    let largestComponent = new Uint8Array(size);
+    let largestSize = 0;
+    const neighbours = [-1, 1, -width, width, -width - 1, -width + 1, width - 1, width + 1];
+
+    for (let start = 0; start < size; start++) {
+      if (!foreground[start] || visited[start]) continue;
+      let head = 0, tail = 0;
+      queue[tail++] = start;
+      visited[start] = 1;
+
+      while (head < tail) {
+        const idx = queue[head++];
+        const x = idx % width;
+        const y = (idx / width) | 0;
+        for (let n = 0; n < neighbours.length; n++) {
+          const next = idx + neighbours[n];
+          if (next < 0 || next >= size) continue;
+          const nx = next % width;
+          const ny = (next / width) | 0;
+          if (Math.abs(nx - x) > 1 || Math.abs(ny - y) > 1) continue;
+          if (foreground[next] && !visited[next]) {
+            visited[next] = 1;
+            queue[tail++] = next;
+          }
+        }
+      }
+
+      if (tail > largestSize) {
+        largestSize = tail;
+        largestComponent.fill(0);
+        for (let i = 0; i < tail; i++) largestComponent[queue[i]] = 1;
+      }
+    }
+
+    if (largestSize === 0) return { data: new Uint8Array(size), minX: 0, minY: 0, maxX: -1, maxY: -1 };
+
+    // 2) Flood-fill the OUTSIDE background from the image borders.
+    // Four-connected background plus eight-connected foreground prevents
+    // diagonal pixel contacts from opening artificial holes in the silhouette.
+    const outside = new Uint8Array(size);
+    let head = 0, tail = 0;
+    const pushOutside = (idx) => {
+      if (idx >= 0 && idx < size && !largestComponent[idx] && !outside[idx]) {
+        outside[idx] = 1;
+        queue[tail++] = idx;
+      }
+    };
+
+    for (let x = 0; x < width; x++) {
+      pushOutside(x);
+      if (height > 1) pushOutside((height - 1) * width + x);
+    }
+    for (let y = 1; y < height - 1; y++) {
+      pushOutside(y * width);
+      if (width > 1) pushOutside(y * width + width - 1);
+    }
+
+    while (head < tail) {
+      const idx = queue[head++];
+      const x = idx % width;
+      const y = (idx / width) | 0;
+      if (x > 0) pushOutside(idx - 1);
+      if (x + 1 < width) pushOutside(idx + 1);
+      if (y > 0) pushOutside(idx - width);
+      if (y + 1 < height) pushOutside(idx + width);
+    }
+
+    // 3) Everything not connected to the outside is inside the person's
+    // external contour. This fills internal BodyPix gaps and holes.
+    const filled = new Uint8Array(size);
+    let minX = width, minY = height, maxX = -1, maxY = -1;
+    for (let y = 0; y < height; y++) {
+      const row = y * width;
+      for (let x = 0; x < width; x++) {
+        const idx = row + x;
+        if (largestComponent[idx] || !outside[idx]) {
+          filled[idx] = 1;
+          if (x < minX) minX = x;
+          if (x > maxX) maxX = x;
+          if (y < minY) minY = y;
+          if (y > maxY) maxY = y;
+        }
+      }
+    }
+    return { data: filled, minX, minY, maxX, maxY };
+  }
+
   async function detectSinglePerson(){
     if(!uploadedPhoto||detectingPerson)return; detectingPerson=true; detectPersonBtn.disabled=true;
-    photoStatus.textContent="Загрузка модели сегментации и выделение силуэта…";
+    photoStatus.textContent="Загрузка модели сегментации и выделение внешнего контура…";
     try{
       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);}
+      const maskW=seg.width, maskH=seg.height;
+      // Keep BodyPix segmentation untouched; create a separate filled mask only
+      // for drawing, so interior holes/artifacts cannot interrupt the heat colors.
+      const silhouette=makeOuterContourMask(seg.data,maskW,maskH);
+      const {data:heatMask,minX,minY,maxX,maxY}=silhouette;
       if(maxX<0){personBox=null;personMask=null;photoStatus.textContent="Человек не выделен. Попробуйте фото с человеком крупнее и на контрастном фоне.";}
       else{
-        // 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+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="Силуэт человека выделен по пикселям. Нанесена условная анатомическая тепловая карта.";
+        personMask={data:heatMask,width:maskW,height:maskH};
+        photoStatus.textContent="Внешний контур человека выделен. Внутренние пробелы сегментации заполнены, тепловая карта наносится сплошным слоем.";
       }
     }catch(err){photoStatus.textContent=err.message||"Ошибка сегментации.";personBox=null;personMask=null;}
     detectingPerson=false;detectPersonBtn.disabled=false;scheduleRender();

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

@@ -111,7 +111,7 @@
           <output id="ambientOut">283 K</output>
         </label>
         <p class="hint">
-          При малом диапазоне слабые перепады температур становятся заметнее, но изображение чаще насыщается.
+          Малый ΔT усиливает контраст. Температура фона задаёт опорный уровень: при её повышении цветовая карта человека смещается к холодным тонам, а контраст с окружением уменьшается.
         </p>
       </fieldset>
     </section>

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

@@ -3,6 +3,14 @@
 - **Что изменено:**
 
 
+гораздо лучше, но в центре фигуры есть неокрашиваемые артефакты, скорее всего артефакты сегментации. Их надо убирать, и в окрашивании учитывать только внешний контур.
+v.0.2.0.8 [color_artefacts] ✅ DONE
+BodyPix находит человека, как и раньше.
+Из маски выделяется крупнейшая связная область — силуэт человека.
+Внешний фон отделяется от внутренней области.
+Все замкнутые пробелы внутри силуэта заполняются.
+Тепловая карта наносится на полученную область.
+
 ненаглядно, фон и человека надо приглушить сильнее, цвета тепловизора ярче, и сделать реакцию на ползунок "Температура фона"
 v.0.2.0.7 [color_more]