I am trying to create a program than can detect faces and predict its gender on the live stream. but I get this error message when running the program
Traceback (most recent call last):
File "text.py", line 54, in <module>
cus_ana.prediction()
File "text.py", line 31, in prediction
gender = gender_classifier()
TypeError: __call__() missing 1 required positional argument: 'inputs'
This is the code so far
class CusAnalytics():
def __init__(self, cascade, gender):
self.cascade = cascade
self.gender = gender
def gender_classifier(self):
classifier = self.gender
gender = classifier.predict(np.expand_dims(cv2.resize(cropped, (198, 198)), axis=0))
gender = np.where(gender.flatten() < 0.5, "Female", "Male")
def prediction(self):
cam = cv2.VideoCapture(0)
while True:
ret, frame = cam.read()
frame = cv2.flip(frame, 1)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = self.cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5, minSize=(150, 150))
for (x, y, w, h) in faces:
cropped = cv2.resize(frame[y:y+h, x:x+w], (198,198))
gender = gender_classifier()
if gender[0] == 'Male':
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.rectangle(frame, (x-1, y+h), (x+w+1, y+h+50), (255, 0, 0), -1)
cv2.rectangle(frame, (x-1, y), (x+w+1, y-50), (255, 0, 0), -1)
else:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv2.rectangle(frame, (x-1, y+h), (x+w+1, y+h+50), (0, 0, 255), -1)
cv2.rectangle(frame, (x-1, y), (x+w+1, y-50), (0, 0, 255), -1)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imshow('Stream', frame)
cascadePath = "../../../MODEL/TRAINED MODELS/FACE_DETECTION/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
gender_classifier_path = '../../../MODEL/TRAINED MODELS/GENDER_CLASSIFICATION/best_gender_classifier.h5'
gender_classifier = load_model(gender_classifier_path)
cus_ana = CusAnalytics(faceCascade, gender_classifier)
cus_ana.prediction()
The code works fine without the implementation of OOPS. I am new to object oriented programming and am trying to learn with this project.
Thank you in advance
Related
I have tried to use cv2.putText and it appears to show the position based on the the top right of the window and not the actual center of the image. It will probably be an obvious fix since I just started using opencv
import os
import numpy as np
font = cv2.FONT_HERSHEY_SIMPLEX
org = (50, 50)
fontScale = 1
color = (255, 0, 0)
radius = 3
thickness = 2
cascPath=os.path.dirname(cv2.__file__)+"/data/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while (True):
ret, frames = video_capture.read()
gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
for (x, y, w, h) in faces:
cv2.rectangle(frames, (x, y), (x+w, y+h), (0, 255, 0), 2)
text = (x+w//2), (y+h//2)
cv2.circle(frames, (cx, cy), radius, (255, 0, 0), -1)
cv2.putText(frames, str(text), org, font, fontScale, color, thickness)
cv2.imshow('Video', frames)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
With the cv2.getTextSize() function, you can calculate the pixel size of the text you will put and subtract it from the text's position. In this way, the text will be right on the center.
text = (x+w//2), (y+h//2)
text_size,t = cv2.getTextSize(text=str(text), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, thickness=1)
text_size_x,text_size_y = text_size
text_pos = (x+w//2)-(text_size_x//2), (y+h//2)+(text_size_y//2)
Here is a working code
import os
import numpy as np
import cv2
font = cv2.FONT_HERSHEY_SIMPLEX
org = (50, 50)
fontScale = 1
color = (255, 0, 0)
radius = 3
thickness = 2
cascPath=os.path.dirname(cv2.__file__)+"/data/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while (True):
ret, frames = video_capture.read()
gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
for (x, y, w, h) in faces:
cv2.rectangle(frames, (x, y), (x+w, y+h), (0, 255, 0), 2)
text = (x+w//2), (y+h//2)
text_size,t = cv2.getTextSize(text=str(text), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, thickness=1)
text_size_x,text_size_y = text_size
text_pos = (x+w//2)-(text_size_x//2), (y+h//2)+(text_size_y//2)
#cv2.circle(frames, (cx, cy), radius, (255, 0, 0), -1)
cv2.putText(frames, str(text), text_pos, font, fontScale, color, thickness)
cv2.imshow('Video', frames)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
As the Dan's suggestion, i tried to edit this post
Error occurred at setting up MOOSE tracker, I also don't know why this error happened because i installed the Opencv-contrib-python==4.5.1.48.However,aftering installing it,the error is still there. The only tracker is MIL,but i realized that the usage purpose of two trackers is different. I also tried to code tracker = cv2.legacy.TrackerMOSSE_create() like Spyke's suggestion but nothing changes.
This is my code:
import cv2
cap = cv2.VideoCapture(0)
tracker = cv2.TrackerMOSSE_create()
success, img = cap.read()
# select a bounding box ( ROI )
bbox = cv2.selectROI("Tracking", img, False)
tracker.init(img, bbox)
def drawBox(img, bbox):
x, y, w, h = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 3, 1)
cv2.putText(img, "Tracking", (75, 75), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
while True:
timer = cv2.getTickCount()
success, img = cap.read()
success, bbox = tracker.update(img)
if success:
drawBox(img, bbox)
else:
cv2.putText(img, "Loss", (75, 75), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)
cv2.putText(img, str(int(fps)), (75, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.imshow("Tracking", img)
if cv2.waitKey(1) & 0xff == ord('q'):
break
Actually the latest version of the opencv now has the "TrackerMOSSE_create" under the legacy class
So, instead of this
tracker = cv2.TrackerMOSSE_create()
use:
tracker = cv2.legacy.TrackerMOSSE_create()
TrackerMOSSE is indeed under the legacy class as stated by #Spyke. However, Instead of:
tracker = cv2.legacy.TrackerMOSSE_create()
I was able to run MOSSE Tracker in OpenCV 4.5.1 with another kind of syntax:
tracker = cv2.legacy_TrackerMOSSE.create()
I am working on a face detection script with OpenCV.
This is my code:
# 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)
if k%256 == 32:
# SPACE pressed
print(my_random_string(9)) # For example, D9E50C
img_name = "face_{}.png".format(img_counter)
cv2.imwrite(img_name, frame[[[(x, y), (x+w, y+h), (0, 255, 0), 2]]])
print("{} written!".format(img_name))
img_counter += 1
# Display the resulting frame
cv2.imshow('FaceDetection', frame)
But I'm getting the following error:
This is screenshot for the error
> c:\Users\Bakri\Desktop\FaceDetection-master\FaceDetection.py:39: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
cv2.imwrite(img_name, frame[[[(x, y), (x+w, y+h), (0, 255, 0), 2]]])
Traceback (most recent call last):
File "C:\Users\Bakri\AppData\Local\Programs\Python\Python36\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\Users\Bakri\Desktop\FaceDetection-master\FaceDetection.py", line 39, in <module>
cv2.imwrite(img_name, frame[[[(x, y), (x+w, y+h), (0, 255, 0), 2]]])
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
Press any key to continue . . .
I searched the Stack Overflow but I can't find any relevant questions/answers.
ok here is full code that save captured images from camera
It saves all camera window (face and all body)
I want it to save only face that covered with rectangle
import uuid
import cv2
import sys
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
video_capture = cv2.VideoCapture('http://192.168.43.1:8080/video')
img_counter = 0
def my_random_string(string_length=10):
"""Returns a random string of length string_length."""
random = str(uuid.uuid4()) # Convert UUID format to a Python string.
random = random.upper() # Make all characters uppercase.
random = random.replace("-","") # Remove the UUID '-'.
return random[0:string_length] # Return the random string.
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
k = cv2.waitKey(1)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.5,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_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)
if k%256 == 32:
# SPACE pressed
print(my_random_string(9)) # For example, D9E50C
img_name = "face_{}.png".format(img_counter)
#cv2.imwrite(img_name, frame)
cv2.imwrite(img_name, frame[[[(x, y), (x+w, y+h), (0, 255, 0), 2]]])
print("{} written!".format(img_name))
img_counter += 1
# Display the resulting frame
cv2.imshow('FaceDetection', frame)
if k%256 == 27: #ESC Pressed
break
elif k%256 == 32:
# SPACE pressed
print('')
#print(my_random_string(9)) # For example, D9E50C
#img_name = "facedetect_webcam_{}.png".format(img_counter)
#cv2.imwrite(img_name, frame)
#print("{} written!".format(img_name))
#img_counter += 1
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
this line save all image from camera:
cv2.imwrite(img_name, frame)
i try to save only rectangle image by this code:
cv2.imwrite(img_name, frame[[[(x, y), (x+w, y+h), (0, 255, 0), 2]]])
but am still getting that error
I am using opencv for face recognition and while executing the code i am getting error:
File "<ipython-input-2-b8cd1a5a0b77>", line 44, in <module>
canvas = detect(gray, frame)
File "<ipython-input-2-b8cd1a5a0b77>", line 23, in detect
id_, conf = recognizer.predict(roi_gray)
TypeError: 'int' object is not iterable
And then after that, Kernel dies.
please help
def detect(gray, frame):
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
id_, conf = recognizer.predict(roi_gray)
if conf>=45:
font = cv2.FONT_HERSHEY_COMPLEX
name = labels[id_]
color = (255, 255, 0)
cv2.putText(frame, name, (x,y), font, 1, color, 2, cv2.LINE_AA)
eyes = eye_cascade.detectMultiScale(roi_gray, 1.1, 3)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
return frame
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
if ret is True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
continue
canvas = detect(gray, frame)
cv2.imshow('Video', canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
I am trying to detect a face using OpenCV. I have a file recognizer.py as follows:
import cv2
faceDetect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cam = cv2.VideoCapture(0)
rec = cv2.face.createLBPHFaceRecognizer()
rec.load('recognizer/trainningData.yml')
id = 0
font = cv2.FONT_HERSHEY_SIMPLEX
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceDetect.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
id, conf = rec.predict(gray[y:y + h, x:x + w])
cv2.putText(img, str(id), (x, y + h), font, 255, (255, 0, 0))
cv2.imshow("Face", img)
if cv2.waitKey(1) == ord('q'):
break
cam.release()
cv2.destroyAllWindows()
When I am trying to run this code, the program is running successfully and opening a camera window.
But whenever, I am trying to show my face in front of the camera, the program is terminating with exit code 1 and showing the following error:
Traceback (most recent call last):
File "/home/prateek/recognizer.py", line 15, in <module>
id, conf = rec.predict(gray[y:y + h, x:x + w])
TypeError: 'int' object is not iterable
Process finished with exit code 1
Means, I am getting the error on line 15 which is as follows:
id, conf = rec.predict(gray[y:y + h, x:x + w])
I don't know how to resolve this problem. I am using Python3 and OpenCV3.3.
Finally, I have got the solution. The problem with was version of opencv. This code is for opencv2.4 and I was trying to run it on opencv3.
Well, The final code for opencv3 is as following:
import cv2
faceDetect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cam = cv2.VideoCapture(0)
rec = cv2.face.createLBPHFaceRecognizer()
rec.load('recognizer/trainningData.yml')
id = 0
font = cv2.FONT_HERSHEY_SIMPLEX
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceDetect.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
id= rec.predict(gray[y:y + h, x:x + w])
cv2.putText(img, str(id), (x, y + h), font, 255, (255, 0, 0))
cv2.imshow("Face", img)
if cv2.waitKey(1) == ord('q'):
break
cam.release()
cv2.destroyAllWindows()
There is no need to mention the variable conf.
rec.predict(gray[y:y + h, x:x + w]) is returning the id of the person from the database.