Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 292
Sashaank Avatar asked May 02 '26 09:05

Sashaank


1 Answers

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>.

like image 117
Raghav Kukreti Avatar answered May 04 '26 22:05

Raghav Kukreti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!