728x90

Tensorflow(모델 : Coco SSD 활용)를 이용해서

선택한 이미지 내 사물 인식 하도록  해보자.

HTML 소스

<!-- Load TensorFlow.js. This is required to use coco-ssd model. -->
<!-- Load the coco-ssd model. -->
<input type="file" onchange="fileSelect(this)" accept="image/*">
<canvas id="myCanvas" width="1000" height="800"></canvas>
<script>
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext("2d");
 
  function fileSelect(evt) {
    var tgt = evt.target || window.event.srcElement,
        files = tgt.files;
   
    // FileReader support
    if (FileReader && files && files.length) {
        var fr = new FileReader();
        fr.onload = function () {
          fileLoad(fr.result);
        }
        fr.readAsDataURL(files[0]);
    }
    function fileLoad(img) {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      const img2 = new Image();
      img2.onload = () => imgLoad(img2);
      img2.src = img;
    }
    function imgLoad(img2) {
      canvas.height =img2.height;
      canvas.width = img2.width;
      ctx.font = "20px serif";
      ctx.strokeStyle = "#FF0500";
      ctx.drawImage(img2, 0, 0);

      cocoSsd.load().then(model => {
        // detect objects in the image.
        model.detect(img2).then(predictions => {
          for(let p of predictions)
          {
            ctx.strokeRect(p.bbox[0],p.bbox[1],p.bbox[2],p.bbox[3]);
            ctx.strokeText(p.class, p.bbox[0],p.bbox[1]);
            console.log('Predictions: ', p );
          }
      });
    });
  }
}
</script>
728x90
반응형

+ Recent posts