Face Detection using opencv and python - python

I'm working on Face Detection in OpenCV(2.4.6) and python(2.7). I have a very simple code, but its not giving me the desired output.
This is my code:
import numpy as np
import cv2
cam = cv2.VideoCapture(0)
name = 'detect'
face_cascade = cv2.CascadeClassifier('C:\opencv\data\haarcascades\haarcascade_frontalface_default.xml')
cv2.namedWindow(name, cv2.WINDOW_AUTOSIZE)
while True:
s, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(img, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(gray,(x,y),(x+w,y+h),(255,0,0),2)
cv2.imshow(name, img)
k = cv2.waitKey(0)
if k == 27:
cv2.destroyWindow(name)
break
When I run this code, my webcam will start and it will give me a blank window like this
Then the webcam will turn off, and in the editor I will get an error as follows:
%run "D:/6th sem/1.OpenCV + Python/det.py"
---------------------------------------------------------------------------
error Traceback (most recent call last)
C:\Users\HP\AppData\Local\Enthought\Canopy32\App\appdata\canopy-1.3.0.1715.win-x86\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
195 else:
196 filename = fname
--> 197 exec compile(scripttext, filename, 'exec') in glob, loc
198 else:
199 def execfile(fname, *where):
D:\6th sem\1.OpenCV + Python\det.py in <module>()
7 while True:
8 s, img = cam.read()
----> 9 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
10 faces = face_cascade.detectMultiScale(img, 1.3, 5)
11 #print s
error: ..\..\..\src\opencv\modules\imgproc\src\color.cpp:3402: error: (-215) scn == 3 || scn == 4
Any suggestions are welcome. Thanks in advance.

some webcams need a warmup time, and deliver empty frames on startup. you want to check for that.
also, who said , that cv2.rectangle returns anything ? where did you get that idea ? from SO ?
while cap.isOpened():
s, img = cam.read()
if s == None:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5) #hmm, 5 required neighbours is actually a lot.
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) # if you want colors, don't paint into a grayscale...
cv2.imshow(name, img)
k = cv2.waitKey(0)
if k == 27:
cv2.destroyWindow(name)
break

Related

src.empty() in function 'cv::cvtColor' & Cap.read()' is not reading the video frame

Python 3.8, Opencv 4.4.0
I have loaded correctly video file it's running, I think Cap.read() is not reading the video frame. I'm working on mask detection project and want to test in pre-recorded wearing mask Video.
Full Code
# import packages
import cv2
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import numpy as np
model = load_model('model_02.h5')
img_width, img_hight = 200, 200
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture('wearingmask.mp4') # for video
img_count_full = 0
#parameters for text
font = cv2.FONT_HERSHEY_SIMPLEX
org = (1, 1)
class_lable=' '
fontScale = 1
# Blue color in BGR
color = (255, 0, 0)
thickness = 2 #1
while True:
img_count_full += 1
response, color_img = cap.read()
if response == False:
break
gray_img = cv2.cvtColor(color_img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_img, 1.1, 6)
FULL ERROR
error Traceback (most recent call last)
<ipython-input-8-d7656fcb48d9> in <module>
39 break
40
---> 41 gray_img = cv2.cvtColor(color_img, cv2.COLOR_BGR2GRAY)
42 faces = face_cascade.detectMultiScale(gray_img, 1.1, 6)
error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-9d_dfo3_\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
It's pretty self explanatory. Your code's core logic is basically loop through images in the video until there are no more images, and then apply cvtColor on the last image.
Your while loop breaks when response is False, that is, you've reached the end of your video file. However, when response is False, the corresponding color_img is actually None. To actually get the last valid image, you need to do something like:
while True:
img_count_full += 1
response, frame = cap.read()
if response == False:
break
color_img = frame
gray_img = cv2.cvtColor(color_img, cv2.COLOR_BGR2GRAY)

OpenCv imread error while trying it in real-time

code:
import face_recognition as fr
import os
import cv2
import face_recognition
import numpy as np
from time import sleep
def get_encoded_faces():
encoded = {}
for dirpath, dnames, fname in os.walk("./faces"):
for f in fname:
if f.endswith(".jpg") or f.endswith(".png"):
face = fr.load_image_file("faces/" + f)
encoding = fr.face_encodings(face)[0]
encoded[f.split(".")[0]] = encoding
return encoded, fname
def unknown_image_encoded(img):
face = fr.load_image_file("faces/" + img)
encoding = fr.face_encodings(face)[0]
return encoding
def classify_face(im):
faces, fname = get_encoded_faces()
faces_encoded = list(faces.values())
known_face_names = list(faces.keys())
img = cv2.imread(im, 1)
face_locations = face_recognition.face_locations(img)
unknown_face_encodings = face_recognition.face_encodings(img, face_locations)
face_names = []
for face_encoding in unknown_face_encodings:
matches = face_recognition.compare_faces(faces_encoded, face_encoding)
name = "Unknown"
face_distances = face_recognition.face_distance(faces_encoded, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_face_names[best_match_index]
face_names.append(name)
for (top, right, bottom, left), name in zip(face_locations, face_names):
cv2.rectangle(img, (left-20, top-20), (right+20, bottom+20), (255, 0, 0), 2)
cv2.rectangle(img, (left-20, bottom -15), (right+20, bottom+20), (255, 0, 0), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(img, name, (left -20, bottom + 15), font, 1.0, (255, 255, 255), 2)
return face_names, fname
cap = cv2.VideoCapture(0)
while True:
ret, image = cap.read()
recog, fname = classify_face(image)
print(recog)
cv2.imshow(fname, image)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
video.release()
cv2.destroyAllWindows()
Error:
Traceback (most recent call last):
File "face.py", line 70, in <module>
recog, fname = classify_face(image)
File "face.py", line 37, in classify_face
img = cv2.imread(im, 1)
SystemError: <built-in function imread> returned NULL without setting an error
[ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wbmte9m7\opencv\modules\videoio\src\cap_msmf.cpp (435) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
The code works properly while using an image but now when I tried using it with video/real-time its throwing this error
I guess it requires the path instead of the image that is passed on to it, is there any other work around
I am trying to recognize faces in real time and the major issue with it was detecting unknown faces so when I started coding for real time I got this error.
The code and the error message don't agree. Are you running an older version of the code?
Error message:
File "face.py", line 37, in classify_face
img = cv2.imread(im, 1)
Code:
img = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
For debugging it may be helpful to display the received frame from the camera with code like the following:
ret, image = cap.read()
grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', grey)
cv2.waitKey()
cv2.imread(im, 1) requires im to be the filename (datatype: string) of the image that you want to read.
Using cap = cv2.VideoCapture(0), you don't need to read images from files anymore, since the image that you want to classify is returned as an array from cap.read().
To fix your code for using cv2.VideoCapture, remove img = cv2.imread(im, 1) from your classify_face method and change the method definition to
def classify_face(img):
instead of
def classify_face(im):
Note, that the 0 option of cv2.VideoCapture refers to reading the live video stream from a camera with index 0.

Getting this error "ValueError: not enough values to unpack (expected 3, got 2)" while compiling opencv contours

I'm going to run an openCV people counting tutorial code. tutorials are available here. https://fedemejia.com/?p=68
but while i'm running the following code by cmd. I'm getting this error
File "VideoCapture.py", line 25, in
_, contours0, hierarchy = cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
ValueError: not enough values to unpack (expected 3, got 2)
my python version is 3.6.8
opencv 4.0.0
import numpy as np
import cv2
cap = cv2.VideoCapture('peopleCounter.avi') #Open video file
fgbg = cv2.createBackgroundSubtractorMOG2(detectShadows = True) #Create the background substractor
kernelOp = np.ones((3,3),np.uint8)
kernelCl = np.ones((11,11),np.uint8)
areaTH = 500
while(cap.isOpened()):
ret, frame = cap.read() #read a frame
fgmask = fgbg.apply(frame) #Use the substractor
try:
ret,imBin= cv2.threshold(fgmask,200,255,cv2.THRESH_BINARY)
#Opening (erode->dilate) para quitar ruido.
mask = cv2.morphologyEx(imBin, cv2.MORPH_OPEN, kernelOp)
#Closing (dilate -> erode) para juntar regiones blancas.
mask = cv2.morphologyEx(mask , cv2.MORPH_CLOSE, kernelCl)
except:
#if there are no more frames to show...
print('EOF')
break
_, contours0, hierarchy = cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for cnt in contours0:
cv2.drawContours(frame, cnt, -1, (0,255,0), 3, 8)
area = cv2.contourArea(cnt)
print area
if area > areaTH:
#################
# TRACKING #
#################
M = cv2.moments(cnt)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
x,y,w,h = cv2.boundingRect(cnt)
cv2.circle(frame,(cx,cy), 5, (0,0,255), -1)
img = cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imshow('Frame',frame)
#Abort and exit with 'Q' or ESC
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release() #release video file
cv2.destroyAllWindows() #close all openCV windows
It was supposed to give the result describe in the tutorial.
In OpenCV 4.0, cv2.findContour() returns only 2 values. So it should be contours0, hierarchy = cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE). See here https://docs.opencv.org/master/df/d0d/tutorial_find_contours.html

error: C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:11111: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor

i have followed a tutorial on creating a training set to recognize a face
here is the code
import cv2
import numpy as np
# Load HAAR face classifier
face_classifier = cv2.CascadeClassifier('Haarcascades/haarcascade_frontalface_default.xml')
# Load functions
def face_extractor(img):
# Function detects faces and returns the cropped face
# If no face detected, it returns the input image
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = face_classifier.detectMultiScale(gray, 1.3, 5)
if faces is ():
return None
# Crop all faces found
for (x,y,w,h) in faces:
cropped_face = img[y:y+h, x:x+w]
return cropped_face
# Initialize Webcam
cap = cv2.VideoCapture(0)
count = 0
# Collect 100 samples of your face from webcam input
while True:
ret, frame = cap.read()
if face_extractor(frame) is not None:
count += 1
face = cv2.resize(face_extractor(frame), (200, 200))
face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
# Save file in specified directory with unique name
file_name_path = r'C:\Users\madhumani\path\\' + str(count) + '.jpg'
cv2.imwrite(file_name_path, face)
# Put count on images and display live count
cv2.putText(face, str(count), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
cv2.imshow('Face Cropper', face)
else:
print("Face not found")
pass
if cv2.waitKey(1) == 13 or count == 100: #13 is the Enter Key
break
cap.release()
cv2.destroyAllWindows()
print("Collecting Samples Complete")
and whenever i tried to run this code in my jupyter notebook i have got this error
error: C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:11111: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor
and tried to figure out the issue by searching this over stackoverflow and all other sites even after searching i couldnt understand the reason behind this issue
here is the commplete traceback of the error
error
Traceback (most recent call last)
<ipython-input-13-6aa561124bc3> in <module>()
30
31 ret, frame = cap.read()
---> 32 if face_extractor(frame) is not None:
33 count += 1
34 face = cv2.resize(face_extractor(frame), (200, 200))
<ipython-input-13-6aa561124bc3> in face_extractor(img)
11
12 gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
---> 13 faces = face_classifier.detectMultiScale(gray, 1.3, 5)
14
15 if faces is ():
and i have tried adding 2.4.13 v dll files in the python root directory as well as added them to the environment variable but still its of no use

ValueError: too many values to unpack opencv-python

working with opencv-python for a tracking project. i get this error when calling the estiamte single marker..any idea?
cv2 version 3.2.0-dev
python version 2.7.12
Traceback (most recent call last):
File "test_aruco_detect.py", line 53, in <module>
rvecs , tvecs = aruco.estimatePoseSingleMarkers(corners, 0.1765, cameraMatrix, distCoeffs)
ValueError: too many values to unpack
the code:
import numpy as np
import cv2
import cv2.aruco as aruco
with np.load('/home/odroid/camera_calibration/testfile.npz') as X:
cameraMatrix,distCoeffs = [X[i] for i in ('arr_0','arr_1')]
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
#print(frame.shape) #480x640
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)
parameters = aruco.DetectorParameters_create()
#lists of ids and the corners beloning to each id
corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters)
if ids != None: #if atleast one id is detected
gray = aruco.drawDetectedMarkers(gray, corners,ids)
rvecs , tvecs = aruco.estimatePoseSingleMarkers(corners, 0.1765, cameraMatrix, distCoeffs)
aruco.drawAxis(gray, cameraMatrix, distCoeffs, rvecs, tvecs)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
rvecs , tvecs, _objPoints = aruco.estimatePoseSingleMarkers(...)
edit:
according to the documentation (http://docs.opencv.org/trunk/d9/d6a/group__aruco.html#ga84dd2e88f3e8c3255eb78e0f79571bd1) i was missing the _objPoints

Categories

Resources