Reputation: 13
I try to display live stream webcam on webpage using Django with OpenCV eye detection.
from imutils.video import VideoStream
import imutils
import cv2,os,urllib.request
import numpy as np
from django.conf import settings
eyes_detection = cv2.CascadeClassifier('haar/haarcascade_eye.xml')
class VideoCamera(object):
def __init__(self):
self.video = cv2.VideoCapture(0)
def __del__(self):
self.video.release()
def get_frame(self):
success, image = self.video.read()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
eyes_detected = eyes_detection.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
for (x, y, w, h) in eyes_detected:
cv2.rectangle(image, pt1=(x, y), pt2=(x + w, y + h), color=(0,255,0), thickness=2)
frame_flip = cv2.flip(image,1)
ret, jpeg = cv2.imencode('.jpg', frame_flip)
return jpeg.tobytes()
The video stream will not be displayed with the code above, however, the video can be displayed if I remove line 20-23(gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY). How can I display the video stream with eye detection on the webpage?
Below is my views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.http.response import StreamingHttpResponse
from main.tryhaar import VideoCamera
import cv2
def gen(tryhaar):
while True:
frame = tryhaar.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
def video_feed(request):
return StreamingHttpResponse(gen(VideoCamera()),
content_type='multipart/x-mixed-replace; boundary=frame')
Upvotes: 0
Views: 157
Reputation: 142834
All problem can make file .xml
. You need correct path to this file.
There is special variable with path to folder with all files .xml
- cv2.data.haarcascades
- and you can use it with filename (without haar/
) to create correct path.
eyes_detection = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
or using os.path.join
eyes_detection = cv2.CascadeClassifier(os.path.join(cv2.data.haarcascades, 'haarcascade_eye.xml'))
Upvotes: 1