github地址
https://github.com/ipazc/mtcnn
本机环境
python 3.7
Keras 2.2.0
opencv-python 4.5.1.48
tensorflow 1.13.1
检测函数及实例
import cv2
from mtcnn import MTCNN
detector = MTCNN()
def detec_face(imgFileName):
image = cv2.cvtColor(cv2.imread(imgFileName), cv2.COLOR_BGR2RGB)
result = detector.detect_faces(image)
if len(result) == 0:
print("图片 "+imgFileName+" 没有检测到人脸。")
print("---------------------------")
else:
count = len(result)
for item in result:
bounding_box = item["box"]
cv2.rectangle(image,
(bounding_box[0], bounding_box[1]),
(bounding_box[0] + bounding_box[2], bounding_box[1] + bounding_box[3]),
(0, 155, 255),
2)
cv2.imwrite(imgFileName.split(".")[0]+"_result."+imgFileName.split(".")[1], cv2.cvtColor(image, cv2.COLOR_RGB2BGR))
print("图片 "+imgFileName+" 检测到{}张人脸,如下:".format(count))
for i in range(count):
print("人脸{}:{}".format(i+1,result[i]))
print("---------------------------")
detec_face("image/single_face.jpg")
detec_face("image/more_face.jpg")
detec_face("image/no_face.jpg")
运行结果
程序输出:
左侧原图,右侧运行结果
no_face.jpg为不含人脸的风景图片,不做列出