OpenCV (Python) face detection program not terminating - python

I have been writing a face detection program in python using OpenCV. It is working fine, but the program is not terminating after closing the window in which faces are detected.
I have tried cv2.destroyAllWindows() and sys.exit(0) also, but nothing is working. I can't find any solution in the internet.
I am using python 3.8 and openCV 4.2.0.
Below is my code
import cv2
import sys
# Get user supplied values
imagePath = "../training_images/1/bla.jpg"
cascPath = "../HaarCascade/haarcascade_frontalface_alt.xml"
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.CASCADE_SCALE_IMAGE
)
print("Found {0} faces!".format(len(faces)))
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Faces found", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
sys.exit(0)
Please help me.

Related

it is possible to create a real time face recognition with openCV and Face-recognition library?

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

Packing bottle orientation with Python OpenCV

I'm trying to detect the bottle orientation in a packing line, for this I'm using haar cascade with python opencv but I getting false positive detections.
This is the image that the system should detect as a positive:
But the problem is that the system will detect as a positive the following image:
Do you know is there is something better than haar cascade that I could use for this or how I could solve the issue with the false positive detection?
This is the complete code:
import cv2
import sys
cascPath = "cascadeedgedbottle.xml"
bottleCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
contrast =2
brightness = 5
bottle = bottleCascade.detectMultiScale(
gray,
scaleFactor=1.05,
minNeighbors=10,
minSize=(125, 125),
flags = cv2.CASCADE_SCALE_IMAGE
#flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
print("Found {0} bottles!".format(len(faces)))
# Draw a rectangle around the bottle
for (x, y, w, h) in bottle:
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
video_capture.release()
cv2.destroyAllWindows()

Syntax Error: "faces = faceCascade.detectMultiScale( ^ SyntaxError: invalid syntax "

I'm trying to detect faces from images using Haar Cascades in opencv and getting Syntax Error while running the below snippet.
import cv2
import os
imagePath = os.path.abspath("C:\\Users\\rohit\\Desktop\\Project\\1.jpg")
cascPath = os.path.abspath("C:\\Users\\rohit\\Desktop\\Project\\haarcascade_frontalface_default.xml")
faceCascade = cv2.CascadeClassifier(cascPath)
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
)
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
filename = 'myconvertedimage.jpg'
cv2.imwrite(filename, image)
u missed the closing bracket in linegray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY

Pycharm does not show image preview on macOS "Big Sur" using OpenCV and Python3.9

I'm trying to code a face recognition app using OpenCV and python on macOS 'Big Sur' and Pycharm, but unfortunately it does not show the image window/preview and it does not show any errors in console , below you can check code:
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread('news.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face = face_cascade.detectMultiScale(gray_img,
scaleFactor=1.05, minNeighbors=5)
for x, y, w, h in face:
img = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 3)
resized = cv2.resize(img, (int(img.shape[1]/3), int(img.shape[0]/3)))
# cv2.startWindowThread()
# cv2.namedWindow("preview")
cv2.imshow('preview', img)
cv2.waitKey(0)
cv2.destroyWindow('preview')
I have tried adding cv2.startWindowThread(), cv2.namedWindow("preview") and even installed headless by "pip3 install opencv-python-headless" but it does not work.
Replace the line face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
with face_cascade = cv2.CascadeClassifier(cv2.data.haarcascade + 'haarcascade_frontalface_default.xml')
and then it should work fine
Here's the final code :
import cv2
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascade + 'haarcascade_frontalface_default.xml')
img = cv2.imread('news.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face = face_cascade.detectMultiScale(gray_img,
scaleFactor=1.05, minNeighbors=5)
for x, y, w, h in face:
img = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 3)
resized = cv2.resize(img, (int(img.shape[1]/3), int(img.shape[0]/3)))
# cv2.startWindowThread()
# cv2.namedWindow("preview")
cv2.imshow('preview', img)
cv2.waitKey(0)
cv2.destroyWindow('preview')
Its seems the problem is related to macOS "Big Sur" framing system,
The problem can be solve by:
1- deleting the python env which I created for this particular project
2- deleting the "home brew" completely
3- created a new python3-env with python-3.9, OpenCV and "pip3 install opencv-python-headless" and it worked.

How to print a message in window using open cv

I am working on a face detection use case and want to print a message when the face is not detected in the frame, and draw the bounding box when the face is detected. I am using open-cv for the same
Here is my code so far, please let me know what changes need to be made.
import cv2
cascPath = 'haarcascade_frontalface_dataset.xml'
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True :
_, frame = video_capture.read(0)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# cv2.imshow("face detection", frame)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
if w == 0:
cv2.putText(frame,'No face',(0,130), font, 1, (200,255,155))
else:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Display the resulting frame in browser
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
I figured out the solution, go through it if you want to have a look , just add this if statement before for loop, it writes no face in the window if no face is detected
if len(faces) == 0:
cv2.putText(frame,'No face',(0,130), 4,1, (200,255,155))
This guide in geeksforgeeks can help you. Also you can follow link on tproger, so I recommend to use google transltator.
https://www.geeksforgeeks.org/python-opencv-cv2-puttext-method/
https://tproger.ru/translations/opencv-python-guide/#text

Categories

Resources