import numpy as np
import cv2 as cv
path = 'haarcascade_frontalface_default.xml'
face_cascade = cv.CascadeClassifier(path)
path = 'haarcascade_eye.xml'
eye_cascade = cv.CascadeClassifier(path)
# 静态图像人脸检测
img = cv.imread('test.jpg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv.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:
cv.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv.imshow('img',img)
cv.waitKey(0)
cv.destroyAllWindows()
# 摄像头动态人脸检测 及 视频保存
import numpy as np
import cv2 as cv
path = 'haarcascade_frontalface_default.xml'
face_cascade = cv.CascadeClassifier(path)
path = 'haarcascade_eye.xml'
eye_cascade = cv.CascadeClassifier(path)
#1.来自视频图像
# cap = cv.VideoCapture('/Users/admin/opencv-4.0.0/samples/data/vtest.avi')
#2. 来自摄像头
cap = cv.VideoCapture(0)
print(cap.isOpened())
count = 0
# 视频保存的参数设置
sz = (int(cap.get(cv.CAP_PROP_FRAME_WIDTH)),
int(cap.get(cv.CAP_PROP_FRAME_HEIGHT)))
fps = 5
#fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
#fourcc = cv2.VideoWriter_fourcc('m', 'p', 'e', 'g')
fourcc = cv.VideoWriter_fourcc(*'mpeg')
## open and set props
vout = cv.VideoWriter()
vout.open('output2.mp4',fourcc,fps,sz,True)
while(True):
count += 1
ret, img = cap.read()
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# cv.imshow('FRAME', gray)
# cv.imwrite('FRAME_%d.png'%count, gray)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv.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:
cv.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,255),2)
cv.imshow('img',img)
vout.write(img)
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
vout.release()
cv.destroyAllWindows()