def face_detect(path,file_name):
#????
img = cv2.imread(path)
#????????
cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
#????????
rects = cascade.detectMultiScale(img, 1.3, 4, cv2.cv.CV_HAAR_SCALE_IMAGE, (20,20))
if len(rects) == 0:
return False
rects[:, 2:] += rects[:, :2]
# highlight the faces in the image
#????
python类CascadeClassifier()的实例源码
def _cascade_detect(self, raw_image):
''' use opencv cascades to recognize objects on the incomming images '''
cascade = cv2.CascadeClassifier(self._cascade)
image = np.asarray(bytearray(raw_image), dtype="uint8")
gray_image = cv2.imdecode(image, cv2.IMREAD_GRAYSCALE)
color_image = cv2.imdecode(image, cv2.IMREAD_ANYCOLOR)
coordinates = cascade.detectMultiScale(
gray_image,
scaleFactor=1.15,
minNeighbors=5,
minSize=(30, 30)
)
for (x, y, w, h) in coordinates:
cv2.rectangle(color_image, (x, y), (x + w, y + h), (0, 255, 0), 2)
self._logger.debug("face recognized at: x: {}, y: {}, w: {}, h: {}".format(x, y, w, h))
return color_image, self._tojson(coordinates)
def __init__(self,
face_classifier_filepath=None,
eye_classifier_filepath=None,
parent=None):
super().__init__(parent)
if face_classifier_filepath is None:
face_classifier_filepath = get_haarcascade_filepath()
if eye_classifier_filepath is None:
eye_classifier_filepath = get_haarcascade_filepath('eyes')
self.fisher_faces = cv2.faces.createFisherFaceRecognizer()
# Need an integer as the key, and image as the
self._images = {}
self._eye_classifier = cv2.CascadeClassifier(eye_classifier_filepath)
# TODO: decide if I want to do this here, or just faces in.
# self._face_classifier = cv2.CascadeClassifier(face_classifier_filepath)
def detectByClf(image_name, clf):
img = cv2.imread(image_name)
smiles_cascade = cv2.CascadeClassifier(clf)
#??img???3???????????????gray?????3??2????????
if img.ndim == 3:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
else:
gray = img
print "start detecting..."
zones = smiles_cascade.detectMultiScale(gray, 1.3, 5)
result = []
for (x, y, width, height) in zones:
result.append((x, y, x+width, y+height))
print "end detecting."
return result
#??????????outpath???
def face_recognize(self):
cap = cv2.VideoCapture(self.index)
face_cascade = cv2.CascadeClassifier(self.cascade)
'''
face_cascade: cascade is entered here for further use.
'''
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
'''
Converts coloured video to black and white(Grayscale).
'''
if np.any(face_cascade.detectMultiScale(gray, 1.3, 5)):
print("Cascade found")
self.dispatch('on_match')
cv2.destroyAllWindows()
for i in range(1, 5):
cv2.waitKey(1)
break
else:
print("Not recognized")
cv2.imshow('frame', frame)
#Comment the above statement not to show the camera screen
if cv2.waitKey(1) & 0xFF == ord('q'):
print("Forcefully Closed")
cv2.destroyAllWindows()
for i in range(1, 5):
cv2.waitKey(1)
break
cap.release()
def __init__(self, matric_num):
WHITE = [255, 255, 255]
face_cascade = cv2.CascadeClassifier('Haar/haarcascade_frontalcatface.xml')
eye_cascade = cv2.CascadeClassifier('Haar/haarcascade_eye.xml')
ID = NameFind.AddName(matric_num)
Count = 0
cap = cv2.VideoCapture(0) # Camera object
self.__trainer__ = None
if not os.path.exists('dataSet'):
os.makedirs('dataSet')
while True:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert the Camera to grayScale
faces = face_cascade.detectMultiScale(gray, 1.3, 5) # Detect the faces and store the positions
for (x, y, w, h) in faces: # Frames LOCATION X, Y WIDTH, HEIGHT
FaceImage = gray[y - int(h / 2): y + int(h * 1.5),
x - int(x / 2): x + int(w * 1.5)] # The Face is isolated and cropped
Img = (NameFind.DetectEyes(FaceImage))
cv2.putText(gray, "FACE DETECTED", (x + (w / 2), y - 5), cv2.FONT_HERSHEY_DUPLEX, .4, WHITE)
if Img is not None:
frame = Img # Show the detected faces
else:
frame = gray[y: y + h, x: x + w]
cv2.imwrite("dataSet/" + matric_num.replace('/', '') + "." + str(ID) + "." + str(Count) + ".jpg", frame)
Count = Count + 1
# cv2.waitKey(300)
cv2.imshow("CAPTURED PHOTO", frame) # show the captured image
cv2.imshow('Face Recognition System Capture Faces', gray) # Show the video
if Count == 150:
Trainer()
break
if cv2.waitKey(1) & 0xFF == ord('q'):
break
print 'FACE CAPTURE FOR THE SUBJECT IS COMPLETE'
cap.release()
cv2.destroyAllWindows()
def __init__(self):
face_cascade = cv2.CascadeClassifier('Haar/haarcascade_frontalcatface.xml')
eye_cascade = cv2.CascadeClassifier('Haar/haarcascade_eye.xml')
recognise = cv2.face.createEigenFaceRecognizer(15, 4000) # creating EIGEN FACE RECOGNISER
recognise.load("Recogniser/trainingDataEigan.xml") # Load the training data
# ------------------------- START THE VIDEO FEED ------------------------------------------
cap = cv2.VideoCapture(0) # Camera object
# cap = cv2.VideoCapture('TestVid.wmv') # Video object
ID = 0
while True:
ret, img = cap.read() # Read the camera object
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert the Camera to gray
faces = face_cascade.detectMultiScale(gray, 1.3, 5) # Detect the faces and store the positions
for (x, y, w, h) in faces: # Frames LOCATION X, Y WIDTH, HEIGHT
# ------------ BY CONFIRMING THE EYES ARE INSIDE THE FACE BETTER FACE RECOGNITION IS GAINED ------------------
gray_face = cv2.resize((gray[y: y + h, x: x + w]), (110, 110)) # The Face is isolated and cropped
eyes = eye_cascade.detectMultiScale(gray_face)
for (ex, ey, ew, eh) in eyes:
ID, conf = recognise.predict(gray_face) # Determine the ID of the photo
NAME = NameFind.ID2Name(ID, conf)
NameFind.DispID(x, y, w, h, NAME, gray)
cv2.imshow('EigenFace Face Recognition System', gray) # Show the video
if cv2.waitKey(1) & 0xFF == ord('q'): # Quit if the key is Q
break
cap.release()
cv2.destroyAllWindows()
def detect_face(image):
faceCascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.3,
minNeighbors=3,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)
return faces if len(faces) else None
def update(self):
# keep looping infinitely until the thread is stopped
for f in self.stream:
# grab the frame from the stream and clear the stream in
# preparation for the next frame
self.frame = f.array
self.rawCapture.truncate(0)
# convert the image to grayscale, load the face cascade detector,
# and detect faces in the image
# Using data trained from here:
# http://www.pyimagesearch.com/2015/05/11/creating-a-face-detection-api-with-python-and-opencv-in-just-5-minutes/
image = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
detector = cv2.CascadeClassifier(FACE_DETECTOR_PATH)
rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,minSize=(30, 30), flags=cv2.cv.CV_HAAR_SCALE_IMAGE)
# construct a list of bounding boxes from the detection
self.rects = [(int(x), int(y), int(x + w), int(y + h)) for (x, y, w, h) in rects]
# if the thread indicator variable is set, stop the thread
# and resource camera resources
if self.stopped:
self.stream.close()
self.rawCapture.close()
self.camera.close()
return
def findfaces(image):
thisdirectory = os.path.dirname(os.path.realpath(__file__))
haarcascadeFolder = os.path.join(thisdirectory,"haarcascades")
cascPath = os.path.join(haarcascadeFolder, "haarcascade_frontalface_default.xml")
#cascPath = os.path.join(haarcascadeFolder, "haarcascade_upperbody.xml")
#cascPath = os.path.join(haarcascadeFolder, "haarcascade_fullbody.xml")
#cascPath = os.path.join(haarcascadeFolder, "haarcascade_russian_plate_number.xml")
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
# Read the image
height, width, depth = image.shape
scale = 1
if (width > 1024):
scale = 1024.0/width
image = cv2.resize(image, None, fx=scale, fy=scale)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.05,
minNeighbors=5,
minSize=(30, 30),
)
return [scale_rect(face, 1/scale) for face in faces]
def face_detect():
image = cv2.imread(face_filename)
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cascade_f = cv2.CascadeClassifier(path.join(cascades_dir, 'haarcascade_frontalface_alt2.xml'))
cascade_e = cv2.CascadeClassifier(path.join(cascades_dir, 'haarcascade_eye.xml'))
facerect = cascade_f.detectMultiScale(image_gray, scaleFactor=1.08, minNeighbors=1, minSize=(200, 200))
# print("face rectangle")
# print(facerect)
image_face = []
if len(facerect) > 0:
# filename numbering
numb = 0
tmp_size = 0
for rect in facerect:
x, y, w, h = rect
# eyes in face?
roi = image_gray[y: y + h, x: x + w]
eyes = cascade_e.detectMultiScale(roi, scaleFactor=1.05, minSize=(20,20))
if len(eyes) > 1:
if h > tmp_size:
tmp_size = h
image_face = image[y:y+h, x:x+h]
return image_face
apply_face_detection.py 文件源码
项目:facial-emotion-detection-dl
作者: dllatas
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def main(argv=None): # pylint: disable=unused-argument
face_cascade = cv2.CascadeClassifier("/home/neo/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_default.xml")
#image_path = "/home/neo/projects/deepLearning/data/image_exp2/"
#image_path = "/home/neo/projects/deepLearning/data/ck_image_seq_10"
image_path = "/home/neo/projects/deepLearning/data/amfed/happy"
#dest_path = "/home/neo/projects/deepLearning/data/crop_faces_seq_10/"
dest_path = "/home/neo/projects/deepLearning/data/amfed_faces"
faces_to_detect = 1
get_images(image_path, face_cascade, dest_path, faces_to_detect)
opencv_functions.py 文件源码
项目:RealtimeFacialEmotionRecognition
作者: sushant3095
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def load_cascades():
# Load Haar cascade files containing features
cascPaths = ['models/haarcascades/haarcascade_frontalface_default.xml',
'models/haarcascades/haarcascade_frontalface_alt.xml',
'models/haarcascades/haarcascade_frontalface_alt2.xml',
'models/haarcascades/haarcascade_frontalface_alt_tree.xml'
'models/lbpcascades/lbpcascade_frontalface.xml']
faceCascades = []
for casc in cascPaths:
faceCascades.append(cv.CascadeClassifier(casc))
return faceCascades
def __init__(self, hat_path=os.path.join(os.curdir, 'hat.png'),
cascade_path=os.path.join(
OPENCV_CASCADE_PATH, 'haarcascades',
'haarcascade_frontalface_default.xml'),
w_offset=1.3, x_offset=-20, y_offset=80, draw_box=False):
# pragma pylint: disable=line-too-long
"""Initializes a `DrawHat` instance.
Args:
hat_path: The path to the hat file. Defaults to ./hat.png .
cascade_path: The path to the face cascade file.
Defaults to
`cvloop.OPENCV_CASCADE_PATH/haarcascades/haarcascade_frontalface_default.xml`
w_offset: Hat width additional scaling.
x_offset: Number of pixels right to move hat.
y_offset: Number of pixels down to move hat.
draw_box: If True, draws boxes around detected faces.
"""
# pragma pylint: enable=line-too-long
self.w_offset = w_offset
self.x_offset = x_offset
self.y_offset = y_offset
self.draw_box = draw_box
self.cascade = cv2.CascadeClassifier(cascade_path)
self.hat = self.load_hat(hat_path)
def main(FLAG):
Model = SimpleModel(FLAG.input_dim, FLAG.hidden_dim, FLAG.output_dim, optimizer=tf.train.RMSPropOptimizer(FLAG.learning_rate), using_gpu=False)
image_path = sys.argv[1]
cascPath = "./haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
image = cv2.imread(image_path)
src_height, src_width, src_channels = image.shape
gray = cv2.cvtColor(image, 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:
print("faceLocation : ({},{}), width={}, height={}".format(x,y,w,h))
cropped_image = gray[x:x+w, y:y+h]
resized_image = imresize(cropped_image, (FLAG.Width, FLAG.Height))
resized_image = resized_image.flatten() / 255
pred_feature = Model.predict(resized_image).flatten()
pred_feature[::2] = pred_feature[::2] * w + x
pred_feature[1::2] = pred_feature[1::2] * h + y
result_img = draw_features_point_on_image(image, [pred_feature], src_width, src_height)
print(pred_feature)
for (x, y, w, h) in faces:
cv2.rectangle(result_img, (x, y), (x+w, y+h), (0, 255, 0), 1)
cv2.imshow('Result', result_img)
cv2.imwrite("./result_img.png", result_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def detect():
stream = io.BytesIO()
#Get the picture (low resolution, so it should be quite fast)
#Here you can also specify other parameters (e.g.:rotate the image)
with picamera.PiCamera() as camera:
camera.resolution = (700, 525)
camera.capture(stream, format='jpeg')
buff = np.fromstring(stream.getvalue(), dtype=np.uint8)
#Now creates an OpenCV image
img = cv2.imdecode(buff, 1)
#img = cv2.imread('coffee.jpg')
face_cascade = cv2.CascadeClassifier('/home/pi/Documents/OpenCV_Projects/XML_Files/coffeePot.xml')
eye_cascade = cv2.CascadeClassifier('/home/pi/Documents/OpenCV_Projects/XML_Files/liquid.xml')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.2, 500, minSize=(80,100))
for (x,y,w,h) in faces:
img = 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, 1.2, 10, minSize=(70,50))
return houghlines(roi_color,h)
def detect():
stream = io.BytesIO()
#Get the picture (low resolution, so it should be quite fast)
#Here you can also specify other parameters (e.g.:rotate the image)
with picamera.PiCamera() as camera:
camera.resolution = (700, 525)
camera.capture(stream, format='jpeg')
buff = np.fromstring(stream.getvalue(), dtype=np.uint8)
#Now creates an OpenCV image
img = cv2.imdecode(buff, 1)
#img = cv2.imread('coffee.jpg')
face_cascade = cv2.CascadeClassifier('/home/pi/Documents/OpenCV_Projects/XML_Files/coffeePot.xml')
eye_cascade = cv2.CascadeClassifier('/home/pi/Documents/OpenCV_Projects/XML_Files/liquid.xml')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.2, 500, minSize=(80,100))
for (x,y,w,h) in faces:
img = 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, 1.2, 10, minSize=(70,50))
return houghlines(roi_color,x,y,w,h)
def __init__(self, paths, classifier_path, input_resize=None, output_resize=None, root='.', margin_ratio=0.3):
"""
:param paths: image files :see: https://github.com/pfnet/chainer/blob/master/chainer/datasets/image_dataset.py
:param classifier_path: XML of pre-trained face detector.
You can find it from https://github.com/opencv/opencv/tree/master/data/haarcascades
:param input_resize: set it if you want to resize image **before** running face detector
:param output_resize: target size of output image
"""
super().__init__(paths=paths, resize=input_resize, root=root)
self.classifier = cv2.CascadeClassifier(classifier_path)
self.margin_ratio = margin_ratio
self.output_resize = output_resize
def load_detection_model(model_path='/usr/local/opt/opencv3/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml'):
if not os.path.exists(model_path):
# Try alternative file path
local_cascade_path = 'face.xml'
if not os.path.exists(local_cascade_path):
raise NameError('File not found:', local_cascade_path)
model_path = local_cascade_path
detection_model = cv2.CascadeClassifier(model_path)
return detection_model
def __init__(self,option_type,path):
self.face_cascade = cv2.CascadeClassifier("cascade/haarcascade_frontalface_default.xml")
self.eye_cascade = cv2.CascadeClassifier("cascade/haarcascade_eye.xml")
self.smile_cascade = cv2.CascadeClassifier("cascade/haarcascade_smile.xml")
self.shape_predictor = "cascade/shape_predictor_68_face_landmarks.dat"
self.facedetect = False
self.functioncall = option_type
self.sourcepath = path
self.image_path = None
self.video_path = None
self.webcam_path = None
self.main_function()