File size: 1,455 Bytes
3d4392e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import React from "react"
import { ImageSegmenterResult, ImageSource } from "@mediapipe/tasks-vision"

import { segmentFrame } from "./segmentFrame"

export async function getSegmentationCanvas({
  frame,
  timestamp,
  width,
  height
}: {
  frame: ImageSource;
  timestamp: number;
  width: number;
  height: number;
}): Promise<JSX.Element> {
   const results: ImageSegmenterResult = await segmentFrame(frame, timestamp);
  
   const canvas: HTMLCanvasElement | OffscreenCanvas | undefined = results.categoryMask?.canvas;
  
   // If there is a canvas, style it and return
   if (canvas) {
      const style = {
        width: `${width}px`,
        height: `${height}px`,
      };

      const CanvasComponent = () => (
        <canvas
          ref={(node) => {
            if (node) {
              node.width = width;
              node.height = height;
              const context = node.getContext('2d');
              if (context) {
                context.drawImage(canvas, 0, 0, width, height);
              }
            }
          }}
          style={style}
        />
      );
      return <CanvasComponent />;
   } else {
      // Return a blank canvas if no canvas is found in results
      return (
        <canvas
          width={width}
          height={height}
          style={{
            width: `${width}px`,
            height: `${height}px`,
            backgroundColor: 'transparent',
          }}
        />
      );
   }
}