OpenCV Human Body Detection through a webcam - No detections visible - python

I am trying to detect the human body through OpenCV. The code throws no error. The camera also starts but it is unable to detect anything.
import cv2
classifier = cv2.CascadeClassifier(r'C:\Users\dhruv\Desktop\DataScience\haarcascade_fullbody.xml')
video_captured = cv2.VideoCapture(0)
while (True):
ret, frame = video_captured.read()
frame = cv2.resize(frame,(640,360))
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# pass the frame to the classifier
persons_detected = classifier.detectMultiScale(gray_frame)
# check if people were detected on the frame
for (x, y, w, h) in persons_detected:
cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow('Video footage', frame)
if (cv2.waitKey(1) & 0xFF == ord('q')):
break
#cv2.VideoCapture(0).release()

I highly suspect its an indentation error. The camera does start, but your code to draw the bounding boxes of the faces are outside of the loop. Just indent that code. In addition, you'll need to free the camera resource properly or the next time you run the code, the camera will not be able to capture frames properly. I've changed the release call so that it releases the grabbed resource.
import cv2
classifier = cv2.CascadeClassifier(r'C:\Users\dhruv\Desktop\DataScience\haarcascade_fullbody.xml')
video_captured = cv2.VideoCapture(0)
while True:
ret, frame = video_captured.read()
frame = cv2.resize(frame,(640,360))
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# pass the frame to the classifier
persons_detected = classifier.detectMultiScale(gray_frame)
# check if people were detected on the frame
for (x, y, w, h) in persons_detected:
cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow('Video footage', frame)
if (cv2.waitKey(1) & 0xFF == ord('q')):
break
video_captured.release() # Changed so that you're releasing the grabbed resource

Related

why does the haarcascades does not work on opencv

I am trying to detect faces in opencv,but I'm running in some issues:
1-When I put the following syntax:gray = cv2.cvtColor(frames,cv2.COLOR_BGR2GRAY),it shows up in red and does not work.
2-The haarcascade also shows up in red:faces = face_cascade.detectMultiScale( gray,scaleFactor=1.1,minNeighbors=5,minSize=(30, 30),flags = cv2.CV_HAAR_SCALE_IMAGE).I tried to do like in some tutorials but it does not work.Would you have any idea?
Here is my code:
#importing packages
import cv2
import numpy as np
#variables
webcam = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
w_size = (700,500)
#turn the webcam on
while (True):
#reading camera and turing into frames
ret,frames = webcam.read()
frames = cv2.resize(frames,w_size)
#detection
gray = cv2.cvtColor(frames,cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale( gray,scaleFactor=1.1,minNeighbors=5,minSize=(30, 30),flags = cv2.CV_HAAR_SCALE_IMAGE)
for (x, y, w, h) in faces:
cv2.rectangle(frames, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow('face_recognition',frames)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#running script
webcam.release()
cv2.destroyAllWindows()
i simply:
added cv2.data.haarcascades as prefix of the type CascadeClassifier
deleted cv2.CV_HAAR_SCALE_IMAGE (parameter not used anymore)
Code:
import cv2
import numpy as np
import cv2.data
#variables
webcam = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_frontalface_default.xml')
w_size = (700,500)
#turn the webcam on
while (True):
#reading camera and turing into frames
ret,frames = webcam.read()
frames = cv2.resize(frames,w_size)
#detection
gray = cv2.cvtColor(frames,cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale( gray,scaleFactor=1.1,minNeighbors=5,minSize=(30, 30))
for (x, y, w, h) in faces:
cv2.rectangle(frames, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow('face_recognition',frames)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#running script
webcam.release()
cv2.destroyAllWindows()

How can I add "a human face was found" if a face is detected?

this is the code I wrote, I want to be able to show on the terminal how many faces was found, I tried some methods (if face_coordinates: cv2.imshow("a human was found", webcam) and others but nothing is working
import cv2
# load some pre-trained data on front faces (haarcascade algorithm)
trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# to capture video from webcam
webcam = cv2.VideoCapture(1)
# iterate forever over frames
while True:
successful_frame_read, frame = webcam.read()
#flip the video (mirror)
flipped_frame = cv2.flip(frame, 1)
# convert to grayscale
grayscaled_img = cv2.cvtColor(flipped_frame, cv2.COLOR_BGR2GRAY)
# detect faces
face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)
# show rectangles around the face
for (x, y, w, h) in face_coordinates:
cv2.rectangle(flipped_frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# show the webcam
cv2.imshow("Fadi's face detector system", flipped_frame)
key = cv2.waitKey(1)
# exit app if Q or q are pressed
if key==81 or key==113:
break
if face_coordinates: # python types can be coerced to boolean
cv2.imshow("Human was found!", webcam)
continue
else:
cv2.imshow("no human was found...", webcam)
continue
webcam.release()
In order to print the number of faces detected in the terminal i tried counting different faces detected and based on that you can print the number of humans found in the terminal while detecting. I have made some small changes in your code as below.
import cv2
# load some pre-trained data on front faces (haarcascade algorithm)
trained_face_data = cv2.CascadeClassifier(cv2.data.haarcascades +'haarcascade_frontalface_default.xml')
# to capture video from webcam
webcam = cv2.VideoCapture(0)
# iterate forever over frames
while True:
successful_frame_read, frame = webcam.read()
#flip the video (mirror)
flipped_frame = cv2.flip(frame, 1)
# convert to grayscale
grayscaled_img = cv2.cvtColor(flipped_frame, cv2.COLOR_BGR2GRAY)
# detect faces
face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)
count=0
# show rectangles around the face
for (x, y, w, h) in face_coordinates:
count=count+1
cv2.rectangle(flipped_frame, (x, y), (x+w, y+h), (0, 255, 0), 3)
# show the webcam
cv2.imshow("Fadi's face detector system", flipped_frame)
key = cv2.waitKey(1)
# exit app if Q or q are pressed
if key==81 or key==113:
break
# python types can be coerced to boolean
if count==1:
print(count," human found")
elif count>0:
print(count," humans found")
else:
print("No human was found")
webcam.release()

OpenCV - Function to paint text to the Canvas

I am detecting a face from the camera and draw a rectangle around it.
Code below:
face_cascade = cv2.CascadeClassifier('face_classifier.xml')
def detect(gray, frame):
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in stops: # For each detected face:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
return frame
video_capture = cv2.VideoCapture(0)
while True:
_, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
canvas = detect(gray, frame)
cv2.imshow('Video', canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
Are there any functions in OpenCV that can print text?
When it detects a face on the screen say "Hi"?
Thank you for your time.
Should have done this first before asking the question but after some Googling and trying out a few things, here is the solution:
face_cascade = cv2.CascadeClassifier('face_classifier.xml')
def detect(gray, frame):
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in stops: # For each detected face:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
font = cv2.FONT_HERSHEY_COMPLEX_SMALL
cv2.putText(frame,'Hello There!',(x+w, h),font, 0.8,(255,0,0),2,cv2.LINE_AA)
return frame
video_capture = cv2.VideoCapture(0)
while True:
_, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
canvas = detect(gray, frame)
cv2.imshow('Video', canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
This will add "Hello There!" to the top right corner of the detection frame rectangle.

Haar- Cascade face detection OpenCv

I used the following code to detect a face using Haar cascade classifiers provided by OpenCv Python. But the faces are not detected and the square around the face is not drawn. How to solve this?
import cv2
index=raw_input("Enter the index No. : ")
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
cap = cv2.VideoCapture(0)
cont=0
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=10,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)
for (x, y, w, h) in faces:
#cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('frame',frame)
inpt=cv2.waitKey(1)
if inpt & 0xFF == ord('q'):
break
elif inpt & 0xFF == ord('s') :
#name='G:\XCODRA\Integrated_v_01\EigenFaceRecognizer\img2'+index+"."+(str(cont))+".png"
name='IC_image\\'+index+"."+(str(cont))+".png"
resized = cv2.resize(gray,None,fx=200, fy=200, interpolation = cv2.INTER_AREA)
img=cv2.equalizeHist(resized)
cv2.imwrite(name,img)
print cont
cont+=1
Use the full path for the classifier.

Webcam face detection in python using Opencv- dimensions of single frames

I have been trying to run a face detection feature from my webcam using code from realpython.com and suggestions I saw on this site.
import cv2
import sys
import os
cascPath = "{base_path}/folder_with_your_xml/haarcascade_frontalface_default.xml".format(
base_path=os.path.abspath(os.path.dirname(__file__)))
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
This is the error I get when I run the code:
File "videocam.py", line 16, in <module>
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor
From what I've gathered, it's because frame is not 3-dimensional and a NoneType object. I am only just starting with OpenCV and face recognition, so I'm not entirely sure how to fix this.

Categories