pip install opencv-python
(只需要主要模块),也可以输入命令pip install opencv-contrib-python
(如果需要main模块和contrib模块)import cv2
cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
#-*- coding: utf-8 -*-
# import openCV的库
import cv2
import os, math, operator
from PIL import Image
from functools import reduce
###调用电脑摄像头检测人脸并截图
def CatchPICFromVideo(window_name, path_name):
cv2.namedWindow(window_name)
#电脑摄像头
cap = cv2.VideoCapture(0)
#告诉OpenCV使用人脸识别分类器
classfier = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
#检测人脸后要画的边框的颜色
color = (0, 255, 0)
while cap.isOpened():
ok, frame = cap.read() #读取一帧数据
if not ok:
break
grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #将当前桢图像转换成灰度图像
#人脸检测,1.2和2分别为图片缩放比例和需要检测的有效点数
faceRects = classfier.detectMultiScale(grey, scaleFactor = 1.2, minNeighbors = 3, minSize = (32, 32))
if len(faceRects) > 0: #大于0则检测到人脸
for faceRect in faceRects: #单独框出每一张人脸
x, y, w, h = faceRect
#画出矩形框
cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)
k = cv2.waitKey(100) #每0.1秒读一次键盘
if k == ord("z") or k == ord("Z"): #如果输入z
#将当前帧保存为图片
img_name = path_name
print(img_name)
image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
cv2.imwrite(img_name, image,[int(cv2.IMWRITE_PNG_COMPRESSION), 9])
break
#显示图像
cv2.imshow(window_name, frame)
#退出摄像头界面
c = cv2.waitKey(100)
if c == ord("q") or c == ord("Q"):
break
#释放摄像头并销毁所有窗口
cap.release()
cv2.destroyAllWindows()
os.system("cls") #清屏
recogname = "recogface.jpg" #预存的人脸文件
CatchPICFromVideo("get face",recogname)
虽然能框住人脸,但是效率还不是很高。
按Z或z可以将框住的人脸截取保存