如何提取numpy数组中dlib人脸检测框内的图像区域?
提取dlib检测到的人脸区域内容
要获取检测框内的图像内容,直接利用OpenCV图像的numpy数组特性做数组切片就行,dlib返回的检测结果已经给出了矩形的四个边界坐标,直接拿来用:
det.top():人脸框的顶部y坐标det.bottom():人脸框的底部y坐标det.left():人脸框的左侧x坐标det.right():人脸框的右侧x坐标
因为numpy数组的索引是[行范围, 列范围],对应图像的[y轴范围, x轴范围],所以提取区域的代码是:
face_region = img[det.top():det.bottom(), det.left():det.right()]
把这段代码加到检测循环里,再用cv2.imshow()单独显示人脸区域。修改后的完整代码如下:
import sys import dlib import cv2 detector = dlib.get_frontal_face_detector() cam = cv2.VideoCapture(1) color_green = (0,255,0) line_width = 3 while True: ret_val, img = cam.read() if not ret_val: break # 读取帧失败时退出 rgb_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) dets = detector(rgb_image) for idx, det in enumerate(dets): # 绘制人脸框 cv2.rectangle(img,(det.left(), det.top()), (det.right(), det.bottom()), color_green, line_width) # 提取并显示人脸区域,多脸时用不同窗口区分 face_region = img[det.top():det.bottom(), det.left():det.right()] cv2.imshow(f'Detected Face {idx+1}', face_region) cv2.imshow('my webcam', img) if cv2.waitKey(1) == 27: break # esc退出 cv2.destroyAllWindows()
如果检测到多个人脸,上面的代码会给每个人脸分配单独的窗口,避免覆盖显示。
内容的提问来源于stack exchange,提问作者Captain C
相关产品推荐
相关产品推荐

