程序1:
import numpy as np
import cv2
face_detect = cv2.CascadeClassifier("lbpcascade_frontalface_improved.xml")
img = cv2.imread("photo.bmp")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_detect.detectMultiScale(gray, 1.1, 5, cv2.CASCADE_SCALE_IMAGE, (50, 50), (100, 100))
if len(faces) > 0:
for faceRect in faces:
x, y, w, h = faceRect
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2, 8, 0)
roi_gray = gray[y:y + h, x:x + w]
roi_color = img[y:y + h, x:x + w]
cv2.imshow("img", img)
cv2.waitKey(0)
运行结果:
程序2:
#coding:utf-8
import cv2 as cv
# 读取原始图像
img= cv.imread('photo.bmp')
#face_detect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
face_detect = cv.CascadeClassifier("lbpcascade_frontalface_improved.xml")
# 检测⼈人脸
# 灰度处理
gray = cv.cvtColor(img, code=cv.COLOR_BGR2GRAY)
# 检查⼈人脸 按照1.1倍放到 周围最⼩小像素为5
#face_zone = face_detect.detectMultiScale(gray, scaleFactor = 2, minNeighbors = 2) # maxSize =(55,55)
face_zone = face_detect.detectMultiScale(gray, 1.1, 5, cv2.CASCADE_SCALE_IMAGE, (50, 50), (100, 100)) # maxSize =(55,55)
print ('识别⼈人脸的信息:\n',face_zone)
# 绘制矩形和圆形检测⼈人脸
for x, y, w, h in face_zone:
# 绘制矩形人脸区域
cv.rectangle(img, pt1 = (x, y), pt2 = (x+w, y+h), color = [0,0,255], thickness=2)
# 绘制圆形⼈人脸区域 radius表示半径
cv.circle(img, center = (x + w//2, y + h//2), radius = w//2, color = [0,255,0], thickness = 2)
# 设置图⽚片可以⼿手动调节⼤大⼩小
cv.namedWindow("Easmount", 0)
# 显示图⽚片
cv.imshow("Easmount", img)
# 等待显示 设置任意键退出程序
cv.waitKey(0)
cv.destroyAllWindows()
运行结果: