File size: 1,558 Bytes
fddab62
 
 
 
 
6215321
fddab62
 
09a7c47
 
fddab62
09a7c47
fddab62
 
 
 
 
 
 
09a7c47
fddab62
 
 
09a7c47
fddab62
 
09a7c47
fddab62
 
09a7c47
 
 
 
fddab62
 
 
09a7c47
fddab62
09a7c47
fddab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09a7c47
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { MPMask } from "@mediapipe/tasks-vision";

interface DrawSegmentationOptions {
  mask?: MPMask;
  canvas?: HTMLCanvasElement;
  backgroundImage?: HTMLVideoElement | HTMLImageElement;
  fillStyle?: string;
}

/**
 * Draw segmentation result with enhancements.
 */
export function drawSegmentation(options: DrawSegmentationOptions): HTMLCanvasElement {
  const {
    mask,
    canvas,
    backgroundImage,
    fillStyle = "rgba(255, 255, 255, 1.0)"
  } = options;

  if (!canvas) {
    throw new Error("drawSegmentation failed: cannot access the canvas");
  }

  const width = mask?.width || 0;
  const height = mask?.height || 0;

  canvas.width = width || canvas.width;
  canvas.height = height || canvas.height;

  console.log("drawSegmentation: drawing..")

  const ctx = canvas.getContext("2d")
  if (!ctx) {
    throw new Error("drawSegmentation failed: cannot access the 2D context")
  }

  ctx.fillStyle = "#00000000"; // Maintain transparent background if no image provided
  ctx.fillRect(0, 0, width, height);

  // Draw the background image if provided, otherwise default to transparent background.
  if (backgroundImage) {
    ctx.drawImage(backgroundImage, 0, 0, width, height);
  }

  if (mask) {
  
    ctx.fillStyle = fillStyle;
    const maskData = mask.getAsFloat32Array();

    maskData.forEach((category: number, index: number) => {
      if (Math.round(category * 255.0) === 0) {
        const x = index % width;
        const y = Math.floor(index / width);
        ctx.fillRect(x, y, 1, 1);
      }
    });
  }

  return canvas;
}