06人脸截取
人脸截取是指,在图像上用矩形标记出人脸后,将矩形区域保存为另一个文件。若图像中有标记出多张人脸,则将每张人脸保存为一个文件。
import cv2 # 导入opencv库
def face_intercept_demo(img):
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
face_detect=cv2.CascadeClassifier("./venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml")
faces=face_detect.detectMultiScale(gray,1.1,5)
if len(faces)>0: # 大于0则检测到人脸
cropped=[] # 空列表,存储每张人脸的坐标
for face in faces:
x,y,w,h=face
cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2) # 框出人脸
cropped.append(img[y:y+h,x:x+w]) # 截取的坐标范围为[y0:y1, x0:x1]
cv2.imshow("result", img)
for i in range(len(faces)):
cv2.imshow("InterceptFace" + str(i + 1), cropped[i]) # 显示需截取的人脸
if cv2.waitKey(0) == ord("s"): # 等待按下小写字母s键,执行保存截取的人脸图像
for i in range(len(faces)):
cv2.imwrite("./faces"+str(i+1)+".png", cropped[i])
img = cv2.imread("./images/DSC04753.jpg")
face_intercept_demo(img)
cv2.destroyAllWindows() # 释放内存
其中用函数face_intercept_demo(img)来实现人脸截取(含保存)的功能。
if len(faces)>0: # 大于0则检测到人脸
cropped=[] # 空列表,存储每张人脸的坐标
for face in faces:
x,y,w,h=face
cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2) # 框出人脸
cropped.append(img[y:y+h,x:x+w]) # 截取的坐标范围为[y0:y1, x0:x1]
以上这段代码的大致含义是:当检测到的人脸数大于0时(即图像中有人脸),设置一个空列表 cropped 来存储每张人脸的坐标范围。
之后的遍历每张人脸和之前的代码一致,这里就不再赘述了。
重点强调一下,人脸截取的坐标范围为[y:y+h,x:x+w],一定是[y0:y1,x0:x1],y坐标在前,x坐标在后。