首先定义绘制图像的函数,注意,opencv中的图像为BGR格式,与平时的RGB格式不符,所以需要在jupyternotebook中绘制的时候需要先转化。
def cv_imshow(image):
img_to_plot = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(img_to_plot)
人脸检测模块
利用opencv定义的api进行人脸识别任务
%%time
from matplotlib import pyplot as plt
#图片人脸检测
import cv2
import sys
# Get user supplied values
imagePath = './test.jpg'
# Create the haar cascade
faceCascade = cv2.CascadeClassifier('./haarcascade_frontalface_alt2.xml')
# Read the image
image = cv2.imread(imagePath)#2
plt.imshow(image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)#3
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.15,
minNeighbors=5,
minSize=(5,5),
flags = cv2.CASCADE_SCALE_IMAGE
) #4
print ('Found {} faces!'.format(len(faces)))#5
for i in faces:
x = i[0]
y = i[1]
w = i[2]
h = i[3]
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) #6
cv_imshow(image)
%%time魔法函数可以计算该代码块运行时间