python中用人脸分类器识别图片中人的脸,眼睛等

360影视 2024-12-09 20:44 4

摘要:import cv2# 加载 Haar 级联分类器face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')eye_ca

import cv2# 加载 Haar 级联分类器face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')# 读取图像image_path = "d:/2.jpg" # 替换为你的图片路径image = cv2.imread(image_path)gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# 检测人脸faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))# 绘制人脸区域和检测眼睛for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = image[y:y + h, x:x + w] # 检测眼睛 eyes = eye_cascade.detectMultiScale(roi_gray) for (ex, ey, ew, eh) in eyes: cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)# 显示结果cv2.imshow('Detected Faces and Eyes', image)cv2.waitKey(0)cv2.destroyAllWindows

不少新手朋友说找不到 haarcascade_frontalface_default.xml等文件,其实python安装了opencv库之后,相关的分类器也自带了的,以下是一个虚拟环境中opencv目录下的分类器。

也可以通过Everything搜索

来源:新手村养牛

相关推荐