I'm using Python 2.7 and OpenCV 3.2 I work on Windows 64 bit.
I'm working on a face recognition code and I want to use the OpenCV FaceRecognizer
recognizer = cv2.face.createFisherFaceRecognizer()
but when i run the code i get this error,
AttributeError: 'module' object has no attribute 'createFisherFaceRecognizer'
I tried also to write it like this
recognizer = cv2.createFisherFaceRecognizer()
but still getting the same error
This is the code, the code is part of a kivy code
def FaceRecognizer():
recognizer = cv2.face.createFisherFaceRecognizer()
recognizer.load('Trainer/Trainer.yml')
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cam = cv2.VideoCapture(0)
font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1)
while (True):
retval,image = cam.read() # reading image from cam
print np.shape(image)
gray_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # converting image to gray image
faces = face_detector.detectMultiScale(gray_image,1.3,5)
''' detectMultiScale, detects objects of different sizes in the input image.
the detected objects are returned as a list of rectangles
'''
for (x,y,w,h) in faces:
cv2.rectangle(image, (x,y), (x+w, y+h), (255,0,0), 2)
Id, conf = recognizer.predict(gray[y:y+h,x:x+w])
if(conf<50):
Id="Aladdin Hammodi"
else:
Id= "Unknown"
cv2.cv.PutText(cv2.cv.fromarray(im),str(Id), (x,y+h),font, 255)
cv2.imshow('frame',image)
if cv2.waitKey(100) & 0xFF == ord('q'):
break
cam.release()
cv2.destroyAllWindows()
output = "Recognition is done"
return output
Related
I am trying to build a face recognition in Python
at first I build a face detection with openCV and using documentation example in Face-Recognition library I did that
and right now im trying to merge those two library and I get an error
heres are my example code im trying build
import cv2
import pathlib
import face_recognition
casface = pathlib.Path(cv2.__file__).parent.absolute() / "data/haarcascade_frontalface_default.xml"
clf = cv2.CascadeClassifier(str(casface))
video = cv2.VideoCapture(0)
picture_of_me = face_recognition.load_image_file("images/art.jpg") # my image location
my_face_encoding = face_recognition.face_encodings(picture_of_me)[0]
while True:
suc, img = video.read()
frame = cv2.flip(img, 1) # Flip camera vertically
vds_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
small_frame = cv2.resize(img,(0,0), fx=0.25,fy=0.25)
# smalller_fram = small_frame[:,:,::-1]
face_detect = clf.detectMultiScale(
vds_gray,
scaleFactor=1.2,
minNeighbors=1,
minSize=(30,30),
)
# the faces detected on my webcam and encode it on facerecognition
face_locas = face_recognition.face_locations(small_frame)
face_ecnod = face_recognition.face_encodings(face_locas)[0]
try:
# comparing my image and webcam
results = face_recognition.compare_faces([my_face_encoding], face_ecnod)
if results[0]:
for (x,y,w,h) in face_detect:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0,255,0), 1)
cv2.putText(
frame,
'it is me!',
(x,y+h + 30),
cv2.FONT_HERSHEY_PLAIN,
2,
(0,255,0),
2,
cv2.LINE_AA
)
else:
print("It's not a picture of me!")
for (x,y,w,h) in face_detect:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0,255,0), 1)
cv2.putText(
frame,
'hindi',
(x,y+h + 30),
cv2.FONT_HERSHEY_PLAIN,
2,
(0,255,0),
2,
cv2.LINE_AA
)
except IndexError as e:
print(e)
cv2.imshow('frame',frame)
k = cv2.waitKey(30) & 0xff
if k == 27: # press 'ESC' to quit
break
video.release()
cv2.destroyAllWindows()
im beginner and 4th year college student is there any recommendation such as library i use ? i mean there is no training data
I tried to look up
Pytorch
tensorFlow
keras
packages but it kind of hard for me to understand , any recommendation or website/articles for begginer to understand the facial recognition
I was trying to run a face detection code I copy pasted from https://www.thepythoncode.com/article/detect-faces-opencv-python on PyCharm IDE. I got an error saying:
"C:\Users\NH\PycharmProjects\Hello_World\venv\Scripts\python.exe"
"C:/Users/NH/Desktop/WELCOME!/Docs/PycharmProjects/pythonProject/FACEDETECT.py"
Traceback (most recent call last): File "C:/Users/NH/Desktop/WELCOME!/Docs/PycharmProjects/pythonProject/FACEDETECT.py",
> line 5, in
_, image = cap.read() AttributeError: 'VideoCapture' object has no attribute 'read'
Here's the code:
import cv2
cap = cv2.VideoCapture()
face_cascade = cv2.CascadeClassifier("haarcascade_fontalface_default.xml")
while True:
_, image = cap.read()
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(image_gray, 1.3, 5)
for x, y, width, height in faces:
cv2.rectangle(image, (x, y), (x + width, y + height), color=(255, 0, 0), thickness=2)
cv2.imshow("image", image)
if cv2.waitKey(1) == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
I tried the debugger on line 5 but I can't seem to figure out the problem.
I am trying to run this OpenCV code to detect faces with my video camera. It's giving me this error whenever I run my code. The light on my video camera blinks but then shuts down with this error in the console box along with this one cv2.error: OpenCV(4.5.1) error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
Here's the code
# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# To capture video from webcam.
cap = cv2.VideoCapture(0)
# To use a video file as input
# cap = cv2.VideoCapture('filename.mp4')
while True:
# Read the frame
_, img = cap.read()
# Convert to grayscale
#THIS IS THE ERROR AREA
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect the faces
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
# Draw the rectangle around each face
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
# Display
cv2.imshow('img', img)
# Stop if escape key is pressed
k = cv2.waitKey(30) & 0xff
if k == 27:
break
# Release the VideoCapture object
cap.release()
It seems your script is not able to find the haarcascade_frontalface_default.xml file properly because of relative path. Try to give an absolute path and check.
Im using opencv to detect faces in my webcam and whenever a face is detected I want to crop the ROI of face and save its image locally on my system. But when I run the code it doesnt do anything at all.
My webcam is working in opencv(which Ive already tested). But this specific code isnt working, for unknown reasons.
import os
import cv2
ctr=0
# import face detection cascade
face_cascade = cv2.CascadeClassifier('/home/opi/opencv-3.3.0/data/haarcascades/haarcascade_frontalface_default.xml')
# create capture object
cap = cv2.VideoCapture(0)
while(True):
# capture frame-by-frame
ret, img = cap.read()
# convert image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(img, 1.3, 5)
# for each face draw a rectangle around and copy the face
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_color = img[y:y+h, x:x+w]
roi_gray = gray[y:y+h, x:x+w]
#SAVE THE DETECTED FACES LOCALLY
roi_gray=cv2.resize(roi_gray,(100,100))
cv2.imwrite('faces'+'/'+str(ctr)+'.jpg',roi_gray)
ctr+=1
# display the resulting frame
cv2.imshow('frame',img)
# when everything done, release the capture
cap.release()
cv2.destroyAllWindows()
When I kill the code pressing Ctrl+C, I can see this error which also doesnt make much sense :-
opi#admin:~$ python input.py
^CTraceback (most recent call last):
File "input.py", line 18, in <module>
faces = face_cascade.detectMultiScale(img, 1.3, 5)
KeyboardInterrupt
You have forgotten to add cv2.waitKey(1) and that is why your code crashes while it is in an infinite loop ( while True: ... ). We can also say that there is no time for showing(refreshing) frames ...
Add this block of code:
# display the resulting frame
cv2.imshow('frame',img)
key = cv2.waitKey(1)
if key == 32: # if the space key is pressed
break
The final code :
import os
import cv2
ctr=0
# import face detection cascade
face_cascade = cv2.CascadeClassifier('/home/opi/opencv-3.3.0/data/haarcascades/haarcascade_frontalface_default.xml')
# create capture object
cap = cv2.VideoCapture(0)
while True:
# capture frame-by-frame
ret, img = cap.read()
# convert image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(img, 1.3, 5)
# for each face draw a rectangle around and copy the face
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_color = img[y:y+h, x:x+w]
roi_gray = gray[y:y+h, x:x+w]
#SAVE THE DETECTED FACES LOCALLY
roi_gray=cv2.resize(roi_gray,(100,100))
cv2.imwrite('faces'+'/'+str(ctr)+'.jpg',roi_gray)
ctr+=1
# display the resulting frame
cv2.imshow('frame',img)
key = cv2.waitKey(1)
if key == 32: # if space key is pressed
break
# when everything done, release the capture
cap.release()
cv2.destroyAllWindows()
I have following code:
import numpy as np
import cv2
import pickle
import rtsp
import PIL as Image
face_cascade = cv2.CascadeClassifier('cascades\data\haarcascade_frontalface_alt2.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("trainner.yml")
labels = {"person_name": 1}
with open("labels.pickle", 'rb') as f:
og_labels = pickle.load(f)
labels = {v:k for k,v in og_labels.items()}
url = 'rtsp://user:pass#xxx.xxx.x.xxx:YYYY/stream0/mobotix.mjpeg'
with rtsp.Client(url) as client:
client.preview()
while True:
frame = client.read(raw=True)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
for (x,y,w,h) in faces:
print(x,y,w,h)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
#recognize?
id_, conf = recognizer.predict(roi_gray)
if conf>=45: # and conf <=85:
print(id_)
print(labels[id_])
font = cv2.FONT_HERSHEY_SIMPLEX
name = labels[id_]
color = (0,0,255)
stroke = 2
cv2.putText(frame, name, (x,y), font, 1, color, stroke, cv2.LINE_AA)
#img_item = "my-image.png"
#cv2.imwrite(img_item, roi_gray)
color = (0, 0, 255)
stroke = 2
end_cord_x = x + w
end_cord_y = y + h
cv2.rectangle(frame, (x,y), (end_cord_x, end_cord_y), color, stroke)
cv2.imshow('IP cam',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
Everything is working fine, I'm running my code and first it's opening the Cam view of "client.preview", face detection is not working at this time. When I close this one, the IPcam windows opens and everything is working. (I'm still getting a lot of missed frames by the RTSP stream but no direct issue).
If I leave the code "client.preview" out of it, I'm getting an error from opencv because of src_empty.
If I try to change the code to "client.read()" idem an error occurs from opencv because of src_empty.
How should I fix this?
Ok I understand that the RTSP protocol is first sending empty frames and building up the buffer.
with rtsp.Client(url) as client:
while True:
frame = client.read(raw=True)
if not frame:
time.sleep(.30)
else:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
for (x,y,w,h) in faces:
cv2.imshow('IP cam',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
I deleted the line : client.preview() because of a double function.
The code is starting and after period I receive following error:
if not frame:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Before the rtsp client has received its first frame, the read call on the rtsp client will return None. When you call "client.preview" the time taken for the window to open gives the rtsp client enough time to receive the first frame from the stream before the first read is called. All calls to read beyond this will always return a frame, which is why everything works when it is included in the code. The solution to your problem would be check the result from read function of the rtsp client to ensure that you have received a frame before processing it.
import numpy as np
import cv2
import pickle
import rtsp
import PIL as Image
import time
face_cascade = cv2.CascadeClassifier('cascades\data\haarcascade_frontalface_alt2.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("trainner.yml")
labels = {"person_name": 1}
with open("labels.pickle", 'rb') as f:
og_labels = pickle.load(f)
labels = {v:k for k,v in og_labels.items()}
url = 'rtsp://user:pass#xxx.xxx.x.xxx:YYYY/stream0/mobotix.mjpeg'
with rtsp.Client(url) as client:
client.preview()
while True:
frame = client.read(raw=True)
if frame is not None:
time.sleep(.10)
else:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
for (x,y,w,h) in faces:
print(x,y,w,h)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
#recognize?
id_, conf = recognizer.predict(roi_gray)
if conf>=45: # and conf <=85:
print(id_)
print(labels[id_])
font = cv2.FONT_HERSHEY_SIMPLEX
name = labels[id_]
color = (0,0,255)
stroke = 2
cv2.putText(frame, name, (x,y), font, 1, color, stroke, cv2.LINE_AA)
#img_item = "my-image.png"
#cv2.imwrite(img_item, roi_gray)
color = (0, 0, 255)
stroke = 2
end_cord_x = x + w
end_cord_y = y + h
cv2.rectangle(frame, (x,y), (end_cord_x, end_cord_y), color, stroke)
cv2.imshow('IP cam',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()