Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Yolov5 cannot detection a video (tfjs) #7416

Closed
2 tasks done
gshoanganh opened this issue Apr 14, 2022 · 4 comments
Closed
2 tasks done

Yolov5 cannot detection a video (tfjs) #7416

gshoanganh opened this issue Apr 14, 2022 · 4 comments
Labels
bug Something isn't working Stale Stale and schedule for closing soon

Comments

@gshoanganh
Copy link

Search before asking

  • I have searched the YOLOv5 issues and found no similar bug report.

YOLOv5 Component

No response

Bug

i feel that yolov5 cannot detect a video (or a camera live).
I tried running my log, but it didn't detect it. but it can detect still image.


import React from "react";
import ReactDOM from "react-dom";
import * as tf from '@tensorflow/tfjs';
import { loadGraphModel } from '@tensorflow/tfjs-converter';
import "./style-cam.css";
tf.setBackend('webgl');

const weights = '/web_model/model.json';
const threshold = 0.75;


class App extends React.Component {
  videoRef = React.createRef();
  canvasRef = React.createRef();
  
  load_model = async () => {  
    const model = await loadGraphModel(weights);   
    return model;
  }

  componentDidMount() {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      const webCamPromise = navigator.mediaDevices
        .getUserMedia({
          audio: false,
          video: {
            facingMode: "user"
          }
        })
        .then(stream => {
          window.stream = stream;
          this.videoRef.current.srcObject = stream;
          return new Promise((resolve, reject) => {
            this.videoRef.current.onloadedmetadata = () => {
              resolve();
            };
          });
        });

        this.beginDetect(webCamPromise)
    }
  }

  beginDetect = async (webCamPromise)=>{
    const modelPromise = await this.load_model();
    console.log('modelPromise: ', modelPromise)

    Promise.all([modelPromise, webCamPromise])
      .then(values => {
        this.detectFrame(this.videoRef.current, values[0]);
      })
      .catch(error => {
        console.error(error);
      });
  }

  detectFrame = (video, model) => {
    tf.engine().startScope();
    model.executeAsync(this.process_input(video)).then(predictions => {
      this.renderPredictions(predictions, video);
      requestAnimationFrame(() => {
        this.detectFrame(video, model);
      });
      tf.engine().endScope();
    });
  };

  process_input(video_frame) {
    const input = tf.tidy(() => {
      return tf.image.resizeBilinear(tf.browser.fromPixels(video_frame), [640, 640])
        .div(255.0).expandDims(0);
    });

    this.preview = input
    console.log('input: ', this.preview)
    this.setState({ loading: false })
    return input
  };

  buildDetectedObjects(scores, threshold, boxes, classes, classesDir) {
    const detectionObjects = []
    var video_frame = document.getElementById('frame');

    scores[0].forEach((score, i) => {
      if (score > threshold) {
        const bbox = [];
        const minY = boxes[0][i][0] * video_frame.offsetHeight;
        const minX = boxes[0][i][1] * video_frame.offsetWidth;
        const maxY = boxes[0][i][2] * video_frame.offsetHeight;
        const maxX = boxes[0][i][3] * video_frame.offsetWidth;
        bbox[0] = minX;
        bbox[1] = minY;
        bbox[2] = maxX - minX;
        bbox[3] = maxY - minY;
        detectionObjects.push({
          class: classes[i],
          label: classesDir[classes[i]].name,
          score: score.toFixed(4),
          bbox: bbox
        })
      }
    })
    return detectionObjects
  }

  renderPredictions = predictions => {
    const ctx = this.canvasRef.current.getContext("2d");
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    // Font options.
    const font = "16px sans-serif";
    ctx.font = font;
    ctx.textBaseline = "top";

    const [boxes, scores, classes, valid_detections] = predictions;
    const boxes_data = boxes.dataSync();
    const scores_data = scores.dataSync();
    const classes_data = classes.dataSync();
    const valid_detections_data = valid_detections.dataSync()[0];
    console.log('detect: ',scores_data, classes_data)

    //Getting predictions
    // const boxes = predictions[4].arraySync();
    // const scores = predictions[5].arraySync();
    // const classes = predictions[6].dataSync();

    // const detections = this.buildDetectedObjects(scores, threshold,
    //   boxes, classes, classesDir);

    // detections.forEach(item => {
    //   const x = item['bbox'][0];
    //   const y = item['bbox'][1];
    //   const width = item['bbox'][2];
    //   const height = item['bbox'][3];

    //   // Draw the bounding box.
    //   ctx.strokeStyle = "#00FFFF";
    //   ctx.lineWidth = 4;
    //   ctx.strokeRect(x, y, width, height);

    //   // Draw the label background.
    //   ctx.fillStyle = "#00FFFF";
    //   const textWidth = ctx.measureText(item["label"] + " " + (100 * item["score"]).toFixed(2) + "%").width;
    //   const textHeight = parseInt(font, 10); // base 10
    //   ctx.fillRect(x, y, textWidth + 4, textHeight + 4);
    // });

    // detections.forEach(item => {
    //   const x = item['bbox'][0];
    //   const y = item['bbox'][1];

    //   // Draw the text last to ensure it's on top.
    //   ctx.fillStyle = "#000000";
    //   ctx.fillText(item["label"] + " " + (100 * item["score"]).toFixed(2) + "%", x, y);
    // });
  };

  render() {
    return (
      <div> 
        <h3>Yolo - V5</h3>
        <video
          style={{ height: '600px', width: "500px" }}
          className="size"
          autoPlay
          playsInline
          muted
          ref={this.videoRef}
          width="600"
          height="500"
          id="frame"
        />
        <canvas
          className="size"
          ref={this.canvasRef}
          width="600"
          height="500"
        />
      </div>
    );
  }
}

export default App

Environment

  • Yolo: V5
  • Python: 3.8.7
  • Tensorflow 2

Minimal Reproducible Example

No response

Additional

No response

Are you willing to submit a PR?

  • Yes I'd like to help by submitting a PR!
@gshoanganh gshoanganh added the bug Something isn't working label Apr 14, 2022
@github-actions
Copy link
Contributor

github-actions bot commented Apr 14, 2022

👋 Hello @gshoanganh, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a 🐛 Bug Report, please provide screenshots and minimum viable code to reproduce your issue, otherwise we can not help you.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset images, training logs, screenshots, and a public link to online W&B logging if available.

For business inquiries or professional support requests please visit https://ultralytics.com or email support@ultralytics.com.

Requirements

Python>=3.7.0 with all requirements.txt installed including PyTorch>=1.7. To get started:

git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

CI CPU testing

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training (train.py), validation (val.py), inference (detect.py) and export (export.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit.

@gshoanganh gshoanganh changed the title Yolov5 cannot detection a video Yolov5 cannot detection a video (tfjs) Apr 14, 2022
@github-actions
Copy link
Contributor

github-actions bot commented May 15, 2022

👋 Hello, this issue has been automatically marked as stale because it has not had recent activity. Please note it will be closed if no further activity occurs.

Access additional YOLOv5 🚀 resources:

Access additional Ultralytics ⚡ resources:

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLOv5 🚀 and Vision AI ⭐!

@github-actions github-actions bot added the Stale Stale and schedule for closing soon label May 15, 2022
@vancuonghoang
Copy link

Search before asking

  • I have searched the YOLOv5 issues and found no similar bug report.

YOLOv5 Component

No response

Bug

i feel that yolov5 cannot detect a video (or a camera live). I tried running my log, but it didn't detect it. but it can detect still image.


import React from "react";
import ReactDOM from "react-dom";
import * as tf from '@tensorflow/tfjs';
import { loadGraphModel } from '@tensorflow/tfjs-converter';
import "./style-cam.css";
tf.setBackend('webgl');

const weights = '/web_model/model.json';
const threshold = 0.75;


class App extends React.Component {
  videoRef = React.createRef();
  canvasRef = React.createRef();
  
  load_model = async () => {  
    const model = await loadGraphModel(weights);   
    return model;
  }

  componentDidMount() {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      const webCamPromise = navigator.mediaDevices
        .getUserMedia({
          audio: false,
          video: {
            facingMode: "user"
          }
        })
        .then(stream => {
          window.stream = stream;
          this.videoRef.current.srcObject = stream;
          return new Promise((resolve, reject) => {
            this.videoRef.current.onloadedmetadata = () => {
              resolve();
            };
          });
        });

        this.beginDetect(webCamPromise)
    }
  }

  beginDetect = async (webCamPromise)=>{
    const modelPromise = await this.load_model();
    console.log('modelPromise: ', modelPromise)

    Promise.all([modelPromise, webCamPromise])
      .then(values => {
        this.detectFrame(this.videoRef.current, values[0]);
      })
      .catch(error => {
        console.error(error);
      });
  }

  detectFrame = (video, model) => {
    tf.engine().startScope();
    model.executeAsync(this.process_input(video)).then(predictions => {
      this.renderPredictions(predictions, video);
      requestAnimationFrame(() => {
        this.detectFrame(video, model);
      });
      tf.engine().endScope();
    });
  };

  process_input(video_frame) {
    const input = tf.tidy(() => {
      return tf.image.resizeBilinear(tf.browser.fromPixels(video_frame), [640, 640])
        .div(255.0).expandDims(0);
    });

    this.preview = input
    console.log('input: ', this.preview)
    this.setState({ loading: false })
    return input
  };

  buildDetectedObjects(scores, threshold, boxes, classes, classesDir) {
    const detectionObjects = []
    var video_frame = document.getElementById('frame');

    scores[0].forEach((score, i) => {
      if (score > threshold) {
        const bbox = [];
        const minY = boxes[0][i][0] * video_frame.offsetHeight;
        const minX = boxes[0][i][1] * video_frame.offsetWidth;
        const maxY = boxes[0][i][2] * video_frame.offsetHeight;
        const maxX = boxes[0][i][3] * video_frame.offsetWidth;
        bbox[0] = minX;
        bbox[1] = minY;
        bbox[2] = maxX - minX;
        bbox[3] = maxY - minY;
        detectionObjects.push({
          class: classes[i],
          label: classesDir[classes[i]].name,
          score: score.toFixed(4),
          bbox: bbox
        })
      }
    })
    return detectionObjects
  }

  renderPredictions = predictions => {
    const ctx = this.canvasRef.current.getContext("2d");
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    // Font options.
    const font = "16px sans-serif";
    ctx.font = font;
    ctx.textBaseline = "top";

    const [boxes, scores, classes, valid_detections] = predictions;
    const boxes_data = boxes.dataSync();
    const scores_data = scores.dataSync();
    const classes_data = classes.dataSync();
    const valid_detections_data = valid_detections.dataSync()[0];
    console.log('detect: ',scores_data, classes_data)

    //Getting predictions
    // const boxes = predictions[4].arraySync();
    // const scores = predictions[5].arraySync();
    // const classes = predictions[6].dataSync();

    // const detections = this.buildDetectedObjects(scores, threshold,
    //   boxes, classes, classesDir);

    // detections.forEach(item => {
    //   const x = item['bbox'][0];
    //   const y = item['bbox'][1];
    //   const width = item['bbox'][2];
    //   const height = item['bbox'][3];

    //   // Draw the bounding box.
    //   ctx.strokeStyle = "#00FFFF";
    //   ctx.lineWidth = 4;
    //   ctx.strokeRect(x, y, width, height);

    //   // Draw the label background.
    //   ctx.fillStyle = "#00FFFF";
    //   const textWidth = ctx.measureText(item["label"] + " " + (100 * item["score"]).toFixed(2) + "%").width;
    //   const textHeight = parseInt(font, 10); // base 10
    //   ctx.fillRect(x, y, textWidth + 4, textHeight + 4);
    // });

    // detections.forEach(item => {
    //   const x = item['bbox'][0];
    //   const y = item['bbox'][1];

    //   // Draw the text last to ensure it's on top.
    //   ctx.fillStyle = "#000000";
    //   ctx.fillText(item["label"] + " " + (100 * item["score"]).toFixed(2) + "%", x, y);
    // });
  };

  render() {
    return (
      <div> 
        <h3>Yolo - V5</h3>
        <video
          style={{ height: '600px', width: "500px" }}
          className="size"
          autoPlay
          playsInline
          muted
          ref={this.videoRef}
          width="600"
          height="500"
          id="frame"
        />
        <canvas
          className="size"
          ref={this.canvasRef}
          width="600"
          height="500"
        />
      </div>
    );
  }
}

export default App

Environment

  • Yolo: V5
  • Python: 3.8.7
  • Tensorflow 2

Minimal Reproducible Example

No response

Additional

No response

Are you willing to submit a PR?

  • Yes I'd like to help by submitting a PR!

How can you fix this issue? I am dealing with this.
I have the object in the 10 frames, but I missed it in the first 4,

@glenn-jocher
Copy link
Member

glenn-jocher commented Nov 12, 2022

@vancuonghoang if YOLOv5 is working on some frames then it is working. If you would like to improve your inference results, make sure you are training and running inference at the same image size, and of course to improve your training results see Tips for best results in tutorials below.

Tutorials

Good luck 🍀 and let us know if you have any other questions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working Stale Stale and schedule for closing soon
Projects
None yet
Development

No branches or pull requests

3 participants