前端使用canvas画出图片中的黑色框

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Chessboard Detection</title>
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script>
      const img = new Image();
      img.onload = function () {
        // 创建
        const tempCanvas = document.getElementById("canvas");
        const tempCtx = tempCanvas.getContext("2d");
        tempCanvas.width = img.width;
        tempCanvas.height = img.height;
        tempCtx.drawImage(img, 0, 0);
        // 获取像素数据
        const imageData = tempCtx.getImageData(
          0,
          0,
          tempCanvas.width,
          tempCanvas.height
        );
        const data = imageData.data;
        // 处理每个像素
        for (let i = 0; i < data.length; i += 4) {
          const r = data[i];
          const g = data[i + 1];
          const b = data[i + 2];
          if (r < 30 && g < 30 && b < 30) {
            // 黑色改为红色
            data[i] = 255; // R
            data[i + 1] = 0; // G
            data[i + 2] = 0; // B
            data[i + 3] = 255; // A (0.3 * 255 ≈ 76)
          } else if (r > 240 && g > 240 && b > 240) {
            // 白色透明
            data[i + 3] = 0;
          }
        }
        // 将处理后的像素数据放回临时 canvas
        tempCtx.putImageData(imageData, 0, 0);
        // 绘制边框;
        tempCtx.strokeStyle = "red";
        tempCtx.lineWidth = 1;
        tempCtx.strokeRect(0, 0, img.width, img.height);
      };
      img.src = "./1222.png";
    </script>
  </body>
</html>

原图:

 识别后:

 

posted @ 2025-07-16 17:31  yw3692582  阅读(13)  评论(0)    收藏  举报