Sashaank
Sashaank

Reputation: 964

Passing video feed from Javascript to OpenCV in Python

I am trying to create a web application that takes detects faces in a live video feed. I have written the webcam feed code with Javascript as I would like to later host the application.

Code for getting the feed with Javascript

var video = document.querySelector("#videoElement");

if (navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({video: true}).then(function(stream) {
      video.srcObject = stream;
  }).catch(function(err0r) {
      console.log("Something went wrong!");
  });
}

And my Python code for opening the camera and detecting faces is as follows

import cv2

cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')

cam = cv2.VideoCapture(0)


while True:
    ret, frame = cam.read()
    frame = cv2.flip(frame, 1)

    if ret:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        faces = cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=3)

        for (x, y, w, h) in faces:
            cropped = cv2.resize(frame[y:y+h, x:x+w], (198,198))
            cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
            cv2.destroyAllWindows()

        cv2.imshow('Stream', frame)

My question is instead of opening the webcam in Python can I somehow pass the feed from Javascript to Python. I guess I will have to change this line to include the code from Javascript

cam = cv2.VideoCapture(0)

Any help is appreciated. Thank you in advance

Upvotes: 4

Views: 6548

Answers (1)

Raghav Kukreti
Raghav Kukreti

Reputation: 590

You can check out this tutorial in the OpenCV documentation. The syntax is not really that different.

If you do want to use Python you will need to send an AJAX request for the video feed. Stream it someplace and use it as a source for your <video>.

Upvotes: 1

Related Questions