这是我之前回答中的代码的更新版本,它检测图像中的人脸并将检测到的人脸保存为单独的图像:
需要安装opencv-python
pip3 install opencv-python -i https://pypi.douban.com/sample/
还需要训练模型(人脸识别文件):
haarcascade_frontalface_default.xml人脸识别文件.rar_haarcascade_frontalface_default.xml下载-互联网文档类资源-CSDN下载
代码如下:
import cv2
# Load the cascade classifier
#face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
face_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
face_cascade.load('D:/python-project/haarcascade_frontalface_default.xml')
# Load the input image
img = cv2.imread("3.png")
# Convert the input image to grayscale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces in the grayscale image
faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.1, minNeighbors=5)
# Iterate over the detected faces and save each face as a separate image
face_num = 0
for (x, y, w, h) in faces:
face = img[y:y+h, x:x+w]
cv2.imwrite("face_{}.jpg".format(face_num), face)
face_num += 1
# Display the output image
#cv2.imshow("Faces", img)
# Draw rectangles around the faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv2.imshow("Faces", img)
cv2.waitKey()
结果:
有一张侧脸没有识别出来(后排右起第四个)
以上代码来自chatgpt回复。