system suddenly closed when found the similar face - python

i'm doing my first face recognition project
i have the face image data which will be encoded, so this is my directory
./Desktop/dataset/amber_heard/image.jpg
./Desktop/dataset/jokowi/image.jpg
and this is my code:
import face_recognition
import cv2
import numpy as np
import os
import glob
video_capture = cv2.VideoCapture(0)
known_face_encodings = []
known_face_names = []
os.chdir("./dataset")
for file in glob.glob("**/*.jpg"):
images = face_recognition.load_image_file(file)
images_encoding = face_recognition.face_encodings(images)[0]
known_face_encodings.append(images_encoding)
print(images_encoding)
dir_list = next(os.walk('.'))[1]
known_face_names.append(dir_list)
i'm using the code from link, i just change comparison code to:
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index] and matches[best_match_index] < 0.3:
name = known_face_names[best_match_index]
face_names.append(name)
process_this_frame = not process_this_frame
i use os.walk() to get my subdirectory from directory dataset, if the system detect similar faces from my dataset, the system will show the name based on my subdirectory name.
but my problem is, when my webcam detect the similar face. my system suddenly closed. is there anything wrong with my code? i really need the solution. Thanks in advance ! and pardon my english.

Related

Problem with Python Script that converts images to video after creating EXE with pyinstaller

I wanted to make a script that will convert images stored in a folder to video.
Here's the code:
import cv2
import numpy as np
import os
import pyautogui
import msvcrt
imageFolder = input('Please enter images folder path: ').replace(chr(34),"")
outputPath = imageFolder+'\Video.avi'
try:
images = [img for img in os.listdir(imageFolder) if img.endswith(".jpg")]
while len(images)==0:
imageFolder = input('There are no images in the directory ! Please enter images folder path: ').replace(chr(34),"")
images = [img for img in os.listdir(imageFolder) if img.endswith(".jpg")]
print('Creating recording...')
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
frame = cv2.imread(os.path.join(imageFolder, images[0]))
height, width, layers = frame.shape
frameRate = 2
video = cv2.VideoWriter(outputPath, fourcc, frameRate, (width,height))
for image in images:
print(f'{int((images.index(image)/len(images))*100)} %', end="\r")
video.write(cv2.imread(os.path.join(imageFolder, image)))
cv2.destroyAllWindows()
video.release()
decision = input('Recording has been created successfully ! Do you want to open it? [Y/N]: ')
if decision.lower() == 'y':
print('Opening file...')
os.startfile(outputPath)
except:
print(f'There was a problem with creating a recording. Check images path: {imageFolder}')
The code works fine when I'm launching that from command line, but after converting that to EXE with pyinstalller (pyinstaller -F ConvertToRecording.py) I'm getting an error like this:
[ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (3
92) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:
OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cp
p:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the n
ame of file): C:\Users\MyUser\Documents\Test\20191018_12_45\Video.avi in function
'cv::icvExtractPattern'
Any help appreciated !
I met the same problem. Just go to your OpenCV folder (if you don't have, go here: https://opencv.org/releases/) and find the opencv_videoio_ffmpeg420_64.dll ( I am using 4.20) file. copy it and paste it to your exe direction (same folder).
Then it will work.
Use the os.path module to with paths instead of concatenating strings. This ensures a better cross-platform compatibility. See the manual for a more elaborate explanation of the module.

OpenCV can't get a haarcascade

I'm writing a Python Script using OpenCV library. The code works flawlessly, except one bit. I'm going to build the script with pyinstaller so I need to reference the haarcascade.
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
This works, but this:
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
face_cascade = cv2.CascadeClassifier(resource_path('haarcascade_frontalface_alt.xml'))
doesn't. Need help with solving this problem
Here is the problem: the haarcascade won't load and the "detectMultiScale" will fail.
The same solution worked for my another project
Here's the eror I'm getting:
I tried using "face_cascade.load()" And it works like this:
face_cascade.load('haarcascade_frontalface_alt.xml')
But again doesn't work with "resource_path" function
Doing this
import os.path
print(os.path.isfile(resource_path('haarcascade_frontalface_alt.xml')))
Prints "True" in the console
Also I tried deleting all the code related to detecting faces, and I found that OpenCV successfully captures my webcam
Here is all the code: if someone's interested
import numpy as np
import cv2, os
cap = cv2.VideoCapture(0)
xe = 0
ye = 0
we = 0
he = 0
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
import os.path
print(os.path.isfile(resource_path('haarcascade_frontalface_alt.xml')))
face_cascade = cv2.CascadeClassifier(resource_path('haarcascade_frontalface_alt.xml'))
face_cascade.load(resource_path('haarcascade_frontalface_alt.xml'))
while 1:
ret = cap.set(3,640);
ret = cap.set(4,480);
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.2, 5)
dst = img
for (x,y,w,h) in faces:
dst = img
rows,cols,channels = img.shape
xe = x
ye = y
we = w
he = h
rows,cols,channels = img.shape
pts1 = np.float32([[xe-100,ye-100],[xe+2*we+200,ye-100],[xe-100,ye+2*he+200],[xe+2*we+200,ye+2*he+200]])
pts2 = np.float32([[0,0],[cols,0],[0,rows],[cols,rows]])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(300,300))
dst = cv2.resize(dst,(cols, rows), interpolation = cv2.INTER_CUBIC)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
Edit:
I found the reason for the error: the pass to haarcascade contained cyrillic symbols that's why OpenCV had difficulties with loading the file
Is the haarcascade file actually in the place you expect it to be?
In your resource_path function you could check whether the file actually exists at the full path that is created to be sure.
Get rid of all cyrillic symbols in the path to haarcascade if you get this problem
Okay so even I was facing the same problem. the thing is you have to externally provide the directory link of haarcascade to the classifier function.
for me using anaconda it was at this directory :
C:\Users\lhari\anaconda3\pkgs\libopencv-3.4.2-h20b85fd_0\Library\etc\haarcascades
Then you can join your paths and put it like below as it worked for me!!
path = os.path.join(r"<Your directory to the opencv package>", r"haarcascade_frontalface_default.xml")
face_classifier = cv2.CascadeClassifier(path)
What I can understand is that you need to pass the facecascade file while building the exe.
TRY THIS:
pyinstaller <filename> --add-data="<location of cascade>:.>"
by running this the application will have the cascade file.
more details can be found here

How can I assignin filenames correctly while applying ImageFilters in Python

So I'm trying to use pillow to apply kernals to .jpg images in python and I'm trying to process an entire image set at once. I have a script here that will iterate through the training set, apply the edge finding filter, and save the result in a different folder. Whenever I try to do that using the .save command it throw an error telling me there is no such file as the one I'm saving it to. The thing is, I'm trying to create that file. It doesn't do this when I've got a definite file name, only when I'm trying to do it iterativly. Can anyone see what the problem here is?
import PIL
import os
from PIL import Image
from PIL import ImageFilter
from PIL.ImageFilter import (FIND_EDGES)
num = 1
path = "/home/<me>/Desktop/<my documents>/<my project>/Training Set Cars/"
dirs = os.listdir(path)
for filename in dirs:
print(filename)
im = Image.open(path + filename)
aString = str(num)
print("/home/<me>/Desktop/<my documents>/<my project>/Training Car Edges/%s.jpg" % aString)
ERROR HERE>>> im.filter(FIND_EDGES).save("/home/<me>/Desktop/<my documents>/<my project>/Training Car Edges/%s.jpg" % aString)
num += 1

OpenCV python error (-215) photo found 50% of time

Using Opencv 3.1.0-dev, python 2.7.3 running through OS X terminal
I am running images through a stitching program I made and it works great. I use argparse to make it so I only have to pass a folder location and it will use all the photos in that folder to stitch. I had two test images and it worked great and made some other examples in different folders and with different numbers of images and worked but I am now running into an issue where I get this error:
img1 = cv2.resize(cv2.imread(os.path.join(path,imagesToStitch[0]),1),imageSize)
cv2.error: /Users/chrisradford/opencv/modules/imgproc/src/imgwarp.cpp:3490: error: (-215) ssize.width > 0 && ssize.height > 0 in function resize.
Here is my code:
import os
import cv2
import argparse
from StitchingMaster import Stitcher
#initalize objects
stitcher = Stitcher()
ap = argparse.ArgumentParser()
ap.add_argument("-1", "--first", required=True)
args = vars(ap.parse_args())
#Define variables
imageSize = (1800,1200) #size of image to be passed to stitcher
showMatches = False #True if wish to see matches; False otherwise
keypoints = []
descriptors = []
resultImageSize = (1200,900) #Size of final image to be displated and saved
imagesToStitch = os.listdir(args["first"]) #list of images in folder
path = os.path.abspath(args["first"]) #Folder path
#----Base Case[0-1]----#
if len(imagesToStitch) < 2:
print "Not enough images to stitch"
quit()
#----Base Case[2]----#
else:
img1 = cv2.resize(cv2.imread(os.path.join(path,imagesToStitch[0]),1),imageSize)
img2 = cv2.resize(cv2.imread(os.path.join(path,imagesToStitch[1]),1),imageSize)
#result = stitched image
(result,keypoints,descriptors) = stitcher.stitch([img1,img2],showMatches,keypoints,descriptors)
The error appears right after the
else:
img1 = cv2.resize....
I made another program that both opened the image at that location and resized it and it worked fine. Could it be the naming convention of the folder that gets messed up when I use os.path.abspath() and os.listdir()?
Any help greatly appreciated.
Upon further analysis I was able to determine that the issues was with:
os.listdir(args["first"])
This function also picks up hidden files. Since I am running on OS X it also picked up the hidden file called:
.DS_Store
To solve I created a simple for loop checker that removes any such file that started with a "." from my list.
for files in fileList:
if not files.startswith('.'):
imagesToStitch.append(files)

error: (-215) !empty() in function detectMultiScale

I'm trying to learn cv2 in python 2.7, but when I run my code, in the specific part of it:
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('2015-05-27-191152.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
it returns this:
File "face_detection.py", line 11, in <module>
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
cv2.error: /home/arthurckl/Desktop/opencv-3.0.0-rc1/modules/objdetect/src/cascadedetect.cpp:1595: error: (-215) !empty() in function detectMultiScale
I tried to search the answer here but the best i could find is that I must be loading the face_cascade the wrong way... Any help?
I had the same issue.
I didn't need to download anything else to solve this. CV2 had everything I needed.
Instead of trying to figure out where the .xml files are and hard coding the values, I used a property given by cv2.
From OP
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
Becomes
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
The XML or file is missing or the path to it is incorrect or the create_capture path is incorrect.
The paths in the opencv sample look like this:
cascade_fn = args.get('--cascade', "../../data/haarcascades/haarcascade_frontalface_alt.xml")
nested_fn = args.get('--nested-cascade', "../../data/haarcascades/haarcascade_eye.xml")
cam = create_capture(video_src, fallback='synth:bg=../data/lena.jpg:noise=0.05')
I ran the same code. There are two things to note here.
1. Give the entire path of the .xml files.
2. Give a key press event instruction at the end.
Add this block of code at the end and run your file, worked for me:
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('messigray.png',img)
cv2.destroyAllWindows()
For example, my code looked like
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_eye.xml')
img = cv2.imread('lena.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
#faces = face_cascade.detectMultiScale(gray)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('messigray.png',img)
cv2.destroyAllWindows()
My output looked like this:
You just need to add proper path of the haarcascade_frontalface_default.xml file i.e. you only have to add prefix (cv2.data.haarcascades)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
The XML file is missing, you can get the file from the GitHub repository and place it in the same directory as your project. Link to the folder on GitHub is here. Just download the file named haarcascade_frontalface_default.xml.
Actually, the file exists on your system. Just go to the site-packages folder of your python installation folder and check the cv2/data folder for the file
Use the entire file path and use "\\" instead of "\" in the xml file path.
The file path should be as follows:
face_cascade = cv2.CascadeClassifier('C:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml')
instead of:
cascade_fn = args.get('--cascade', "..\..\data\haarcascades\haarcascade_frontalface_alt.xml")
no need to change the code
download that .xml file , then put the path of that file
it will solve the error (100%)
If you are using Anaconda you should add the Anaconda path.
new_path = 'C:/Users/.../Anaconda/Library/etc/haarcascades/'
face_cascade = cv2.CascadeClassifier(new_path + 'haarcascade_frontalface_default.xml')
This error means that the XML file could not be found. The library needs you to pass it the full path, even though you’re probably just using a file that came with the OpenCV library.
You can use the built-in pkg_resources module to automatically determine this for you. The following code looks up the full path to a file inside wherever the cv2 module was loaded from:
import pkg_resources
haar_xml = pkg_resources.resource_filename(
'cv2', 'data/haarcascade_frontalface_default.xml')
For me this was '/Users/andrew/.local/share/virtualenvs/foo-_b9W43ee/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml'; yours is guaranteed to be different. Just let python’s pkg_resources library figure it out.
classifier = cv2.CascadeClassifier(haar_xml)
faces = classifier.detectMultiScale(frame)
Success!
On OSX with a homebrew install the full path to the opencv folder should work:
face_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/haarcascade_eye.xml')
Take care of the version number in the path.
Probably the face_cascade is empty. You can check if the variable is empty or not by typing following command:
face_cascade.empty()
If it is empty you will get True and this means your file is not available in the path you mentioned.
Try to add complete path of xml file as follows:
r'D:\folder Name\haarcascade_frontalface_default.xml'
"\Anaconda3\Lib\site-packages\cv2\data\" I found the xml file in this path for Anaconda
You can solve this problem by placing XML in the same directory in which your main python file (from where you tried to include this file) was placed. Now the next step is to use full path. For example
This will not work
front_cascade = cv2.CascadeClassifier('./haarcascade_eye.xml')
Use full path, now it will work fine
front_cascade = cv2.CascadeClassifier('/Users/xyz/Documents/project/haarcascade_eye.xml')
I found this in some other answer but eventually worked for me when I added the two answers.
import cv2
from matplotlib import pyplot as plt
import numpy as np
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml")
img = cv2.imread('image1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
You may find such kind of errors when you did not define the complete path of your XML file.
Try this one if you are using opencv3.1.0 in raspberrypi 3:
faceCascade = cv2.CascadeClassifier('/home/pi/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_default.xml')
Your XML file was not found. Try using absolute paths like:
/path/to/my/file (Mac, Linux)
C:\\path\\to\\my\\file (Windows)
the error may be due to, the required xml files has not been loaded properly. Search for the file haarcascade_frontalface_default.xml by using the search engine of ur OS get the full path and put it as the argument to cv2.CascadeClassifier as string
Please do not copy paste the content of xml file, because once you paste it to notepad it will be saved a s text file. So directly download the file from the given source.
I ran into the same problem. but wrote the correct location.
face_cascade = cv2.CascadeClassifier('./model/haarcascade_frontalface_default.xml')
I figured out that i need to declare the full path to remove the error.
face_cascade = cv2.CascadeClassifier('C:/pythonScript/Facial-Emotion-Detection/model/haarcascade_frontalface_default.xml')
The error occurs due to missing of xml files or incorrect path of xml file.
Please try the following code,
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
I had the same problem with opencv-python and I used a virtual environment.
If it's your case, you should find the xml files at:
/home/username/virtual_environment/lib/python3.5/site-packages/cv2/data/haarcascade_frontalface_default.xml
/home/username/virtual_environment/lib/python3.5/site-packages/cv2/data/haarcascade_eye.xml
Please be sure that you're using the absolute path. Otherwise, it won't work.
The main idea of the solution as above mentioned: find the right path of the .xml file and use it to access the file correctly.
In my case, I installed the opencv in anoconda env, first direct to path of Anoconda, then
find the path of .xml file by using:
$ find . -name 'haarcascade_eye.xml' (for example search the haarcascade_eye.xml file in current dir (.))
Then use the return path:
eye_cascade = cv2.CascadeClassifier(path + 'haarcascade_eye.xml')
I faced a similar issue. It seems correcting the path to XML makes this error to go away.
It seems to be file path issue. I changed code like this and it worked.
haar_face_filename = "D:\Sandbox\Github\Faces\haar_face.xml"
haar_cascade = cv.CascadeClassifier(haar_face_filename)
I had the same issue and was trying to use open cv in a springboot application where my xml files and images are in resources folder.
Trying to give path starting from src or a absolute path like C:\a\b.xml did not work.
Creating the file path dynamically with project root path worked.
String classifierPath = System.getProperty("user.dir") + "/src/main/resources/haarcascades/haarcascade_frontalface.xml";
// similarly for image paths
Path needs to start with /, eg. /file.xml.

Categories

Resources