console.time('template matching');

function loadImage(imageFile) {
  return new Promise((resolve) => {
    const image = new Image();
    image.src = imageFile;
    image.onload = () => resolve(image);
  });
}

function onOpenCvReady() {
  cv['onRuntimeInitialized'] = async () => {
    const [small, big] = await Promise.all([
      loadImage('./image_small.png'),
      loadImage('./image_big.png'),
    ]);

    document.getElementById('small').getContext('2d').drawImage(small, 0, 0);
    document.getElementById('big').getContext('2d').drawImage(big, 0, 0);

    const source = cv.imread('big');
    const template = cv.imread('small');
    const dst = new cv.Mat();
    const mask = new cv.Mat();

    cv.matchTemplate(source, template, dst, cv.TM_CCOEFF, mask);
    const { maxLoc: maxPoint } = cv.minMaxLoc(dst, mask);

    let color = new cv.Scalar(255, 0, 0, 255);
    let point = new cv.Point(
      maxPoint.x + template.cols,
      maxPoint.y + template.rows
    );
    cv.rectangle(source, maxPoint, point, color, 2, cv.LINE_8, 0);
    cv.imshow('big', source);
    console.timeEnd('template matching');
  };
}
