opencv find centre of face in facedetction - python

I need to find the centre of a rectangle that gets put around a face when it's detected in OpenCV. I am using Python in Visual Studio.
Here is the code I am running:
#!/usr/bin/env python
from cv2 import *
import sys
cascPath = sys.argv[1]
faceCascade = CascadeClassifier(cascPath)
video_capture = VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cvtColor(frame, COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=CASCADE_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
font = FONT_HERSHEY_SIMPLEX
# Draw text on the frame
putText(frame, 'Hayden' ,(10,100), font, 2,(255,255,255),2,LINE_AA)
# Display the resulting frame
imshow('Video', frame)
if waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
destroyAllWindows()
All I want to do is find the centre of the rectangle, any help will be greatly appreciated!

I'm really sorry but I don't know python. The code for this in C++ is:
Point center = Point(rectangle.x + rectangle.width)/2, (rectangle.y + rectangle.height)/2);
I'd be surprised if this didn't translate almost exactly to python

Related

OpenCV detecting hundreds of cars in footage with one car

I've written a very simple script for detecting cars when given footage:
cap = cv.VideoCapture(1)
car_cascade = cv.CascadeClassifier('assets/cars.xml')
while True:
ret, frame = cap.read()
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
cars = car_cascade.detectMultiScale(gray, 1.1, 1)
for (x, y, w, h) in cars:
cv.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
# Display the resulting frame
cv.imshow('frame', frame)
if cv.waitKey(1) == ord('q'):
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
I'm using the following file for my cars.xml: https://github.com/Aman-Preet-Singh-Gulati/Vehicle-count-detect/blob/main/Required%20Files/cars.xml. I've seen several projects that utilize this same Cascade file as well.
My problem is that when I spin up the video I see a screen like this, where hundreds of elements in the video are categorized as "cars" by the detectMultiScale function. I've been struggling to find anything on why this might be occuring.

Cropping video with OpenCV in Python (Mac)

As a whole I am hoping to access ip camera using OpenCV, crop and adjust their image properties (saturation, contrast, brightness) and then output the result as a new stream.
I have very little knowledge of python/opencv and am doing my best to piece this together from what I can find.
I have been able to access the mjpeg stream however every way of cropping I have found seems to fail. The code below seems the most promising but I am open to alternative methods.
I have achieved the result i'm after using Max MSP and Syphon however my hope is that using OpenCV i will be able to make this completely web based and accessible.
I am hoping to avoid splitting the stream into individual jpegs but if that is the only way to achieve what i'm after please let me know.
Any and all guidance is greatly appreciated.
import cv2
import numpy as np
cap = cv2.VideoCapture('http://89.29.108.38:80/mjpg/video.mjpg')
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 20)
roi = frame[y:y+h, x:x+w]
while True:
ret, frame = cap.read()
cv2.imshow('Video', frame)
if cv2.waitKey(1) == 27:
exit(0)
Traceback (most recent call last):
File "mjpeg-crop.py", line 6, in <module>
(x, y, w, h) = cv2.boundingRect(c)
NameError: name 'c' is not defined
Too much for a comment, but try this to get started:
import cv2
import numpy as np
cap = cv2.VideoCapture('http://89.29.108.38:80/mjpg/video.mjpg')
# (x, y, w, h) = cv2.boundingRect(c)
# cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 20)
# roi = frame[y:y+h, x:x+w]
while True:
ret, frame = cap.read()
# (height, width) = frame.shape[:2]
sky = frame[0:100, 0:200]
cv2.imshow('Video', sky)
if cv2.waitKey(1) == 27:
exit(0)

Getting specific image cross-section from opencv cascade with python

I'm hoping to be able to isolate a small rectangular section of the area that is returned by a haar cascade (the cascade I'm using detects faces, so for example I would like to be able to isolate just the forehead within a given face). I know that training it specifically to detect the area I want is an option, but I'm hoping that it is easy to specify an arbitrary area within the face (for example, the top 20% of the rectangle). I include the code I'm using below:
import cv2
import numpy as py
from matplotlib import pyplot as plt
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture("resources/video/EXAMPLE.mp4")
while True:
ret, img = cap.read()
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 9)
for (x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w, y+h), (255,0,0), 2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cap.destroyAllWindows()
Is there a way to manipulate/gain info about the pixels in "faces"? Any help/pointers would be hugely appreciated.
basicly you can divide h with 3 to getting forehead:
for (x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w, int(y+h/3)), (255,0,0), 2)
but if you want to getting optimized results you can use landmark detection

how to identify the position of detected face

I have to detect faces using openCV and python. Then identify the position of the detected face if it is in the right, the left or the middle of the screen.
I already succeed to detect faces using the code below and still to know the position of the faces could someone please help me ?
import cv2
import sys
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(1)
while True:
#capture frame by frame
ret,frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray,
scaleFactor=1.1,
minNeighbors= 5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_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)
cv2.imshow('video',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
You could get the centre of the rectangle:
centre_x = x + w/2
centre_y = y + y/2
Then compare it with the size of the image. Assuming you have the image shape information:
height, width, channels = frame.shape #it could be gray.shape too
You can understand for example if the face is detected on the left side of the image by checking centre_x<width.
You have all the information to divide the image into a grid and understand where the rectangle places itself.

Attribute error while using opencv for face recognition

I am teaching myself how to use openCV by writing a simple face recognition program I found on youtube. I have installed opencv version 2 as well as numpy 1.8.0. I am using python 2.7.
I copyed this code exactly how it was done in the video and article links below, yet I keep getting errors.
AttributeError: 'module' object has no attribute 'cv'
What am I doing wrong?
Here is the code I'm using.
import cv2
import sys
# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]
# 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.cv.CV_HAAR_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)
https://www.youtube.com/watch?v=IiMIKKOfjqE
https://realpython.com/blog/python/face-recognition-with-python/
The latest openCV no longer allows importing the legacy cv module. Furthermore the naming convention of the constants generally does away with the leading "CV_..." and several/many of the names have been altered somewhat. I think you are running into both problems.
Specifically, the error you are reporting is in regards to this expression in your code: cv2.cv.CV_HAAR_SCALE_IMAGE. This expression is trying to find the named constant CV_HAAR_SCALE_IMAGE within the cv submodule of the cv2 package you imported. But alas, there is no cv2.cv anymore.
In openCV 3, I believe this constant is now referenced as follows: cv2.CASCADE_SCALE_IMAGE
Also, you may find this link useful. It is to the facedetect.py sample script found in the OpenCV source code. You can see the usage of the new constant name in this example, and you may also inspect it for other changes from older sources/tutorials.
This code is working fine for me i'm using the opencv3 lib, please try it
import cv2
import sys
# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]
# 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
)
# 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)
Here is the updated code which works into jupyter notebook with OpenCV3:
[]
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
[]
# Get user supplied values
imagePath = "abba.png"
cascPath = "haarcascade_frontalface_default.xml"
[]
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
[]
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
[]
# Read the image
image = cv2.imread(imagePath)
[]
plt.imshow(image)
plt.show()
[]
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 #flags = cv2.cv.CV_HAAR_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)
[]
plt.imshow(image)
plt.show()
Appears that the haarcascades aren't downloaded.
https://github.com/opencv/opencv/tree/master/data/haarcascades
Download the haarcascades available in the above link, should work for Open CV 4.2.0
Please read the Licence Agreement mentioned in the xml
This code works well for me :
import cv2
imagePath = (
"path to image")
cascPath = ("..\haarcascade_frontalface_default.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.CV_HAAR_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)

Categories

Resources