python-2.7 - 如果使用 python 和 opencv 在两个目录之间检测到公共(public)面孔,如何通知用户

标签 python-2.7 opencv push-notification face-detection

首先,如果标题很长,我很抱歉。我正在使用 python 进行人脸检测。我正在尝试编写一个脚本,当在两个目录/文件夹之间检测到相同的图片或几乎相同的图片/面孔时,它将通知用户。
以下是我到目前为止编写的脚本。

import cv2
import glob, requests

def detect1():
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')

    for img in glob.glob('/Users/Ling/Pythonfiles/Faces/*.jpg'):
        cv_img = cv2.imread(img)
        gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)
        faces1 = face_cascade.detectMultiScale(gray, 1.3, 5)

        for (x,y,w,h) in faces1:
            cv2.rectangle(cv_img,(x,y),(x+w,y+h),(255,0,0),2)


def detect2():
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')

    for image in glob.glob('/Users/Ling/Pythonfiles/testfolder/*.jpg'):
        cv_image = cv2.imread(image)
        gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
        faces2 = face_cascade.detectMultiScale(gray, 1.3, 5)

        for (x,y,w,h) in faces2:
            cv2.rectangle(cv_image,(x,y),(x+w,y+h),(255,0,0),2)

def notify():
    if detect2 == detect1:
        key = "<yourkey>"
        sandbox = "<yoursandbox>.mailgun.org"
        recipient = "<recipient's email>"

        request_url = 'https://api.mailgun.net/v2/{0}/messages'.format(sandbox)
        request = requests.post(request_url, auth=('api', key),
            data={
            'from': '<sender's email',
            'to': recipient,
            'subject': 'face detect',
            'text': 'common face detected'
        })
        print 'Status: {0}'.format(request.status_code)
        print 'Body:   {0}'.format(request.text)

没有错误,但也没有通知。我有一个包含 10 张随机面孔图片的文件夹,我从 Google Image 下载了它(仅用于学习目的),另一个文件夹包含 2 张人脸图片,他们的脸与上一个文件夹中的某些图片相同。同一张脸的照片在不同的角度。

我引用 https://pythonprogramming.net/haar-cascade-face-eye-detection-python-opencv-tutorial/ 中的教程编写了脚本
如果程序从两个文件夹中检测到同一张脸,则添加一些行以发送通知。

我的问题是如果检测到相同的面孔,我如何准确地通知用户。我相信这段代码是不完整的,希望有人能给我建议添加/编辑什么或者我不应该在这个脚本中写什么。

先感谢您。

最佳答案

我不知道我是否正确理解你,但我认为你寻找人脸识别不仅仅是人脸检测。

Haar 基于特征的级联分类器非常笼统地学习了“一张脸应该是什么样子”。它检测给定输入图像中学习对象/形状的位置并返回边界框。

因此,如果您想知道检测到的人脸是否与已知人脸匹配,则需要训练识别器。 OpenCV 有 3 个内置的人脸识别器:EigenFaceRecognizer , FisherfaceRecognizer , LBPHFaceRecognizer (局部二进制模式直方图人脸识别器)。

将它们与例如recognizer = cv2.createLBPHFaceRecognizer()
您需要为您的用户提供训练集。也许您的培训文件夹可能如下所示:

1_001.jpg, 1_002.jpg, 1_003.jpg, 2_001.jpg 2_002.jpg, ..., n_xyz.jpg

其中 n 是标签(用户 id -> 每个用户唯一), xyz 可能是描述或序列号。

更新:

我用了Faces94 benchmark dataset供测试用。因此我将它们打包到文件夹 trainingSamples 中。并将其中两个(同一个人但不同面孔)放入文件夹testFaces相对于我的 python 脚本。

要重命名与上述模式匹配的文件夹中的所有图像,我使用了 bash 命令 rename
例如。 asamma.[1-20].jpg 到 001_[1-20].jpg
rename 's/^asamma./001_/' *

import cv2
import numpy as np
import os

class FaceRecognizer:
    def __init__(self):
        self.cascadeClassifier = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
        self.faceRecognizer = cv2.face.createLBPHFaceRecognizer()

        if os.path.isfile('faceRecognizer.xml'):
            self.faceRecognizer.load('faceRecognizer.xml')
        else:
            images = []
            labels = []
            for file in os.listdir('trainingSamples/'):
                image = cv2.imread('trainingSamples/'+file, 0)
                images.append(image)
                labels.append(int(file.split('_')[0]))
                ## if you don't have pre-cropped profile pictures you need to detect the face first
                # faces = self.cascadeClassifier.detectMultiScale(image)
                # for (x, y, w, h) in faces
                #     images.append(image[y:y+h, x:x+w])
                #     labels.append(int(file.split('_')[0]))

            self.faceRecognizer.train(images, np.array(labels))
            self.faceRecognizer.save('faceRecognizer.xml')

    def predict(self, image, filename):
        user, confidence = self.faceRecognizer.predict(image)
        if confidence < 100.0:
            print('found user with id {} in picture {} with a confidence of {}'.format(user, filename, confidence))

        ## if you don't have pre-cropped profile pictures you need to detect the face first
        # faces = self.cascadeClassifier.detectMultiScale(image)
        # for (x, y, w, h) in faces
        #     user, confidence = self.faceRecognizer.predict(image[y:y+h, x:x+w]) 
        #     # confidence of 0.0 means perfect recognition (same images)
        #     if confidence < 100.0:
        #         print('found user with id {} in picture {} with a confidence of {}'.format(user, filename, confidence))

faceRecognizer = FaceRecognizer()
for file in os.listdir('testFaces/'):
    image = cv2.imread('testFaces/'+file, 0)
    faceRecognizer.predict(image, file)

代码产生输出:
found user with id 4 in picture 004_20.jpg with a confidence of 27.836526552656732
found user with id 1 in picture 001_6.jpg with a confidence of 22.473253497606876`

所以它正确识别用户 4 和用户 1。

该代码使用 Python 3.4.3 和 Python 2.7.9 在 Ubuntu 15.10 上使用 OpenCV 3.1-dev 进行了测试。

关于python-2.7 - 如果使用 python 和 opencv 在两个目录之间检测到公共(public)面孔,如何通知用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39052818/

相关文章:

python - 为什么这种基于条件的列表理解不起作用?

c++ - Cv 正态贝叶斯分类器

ios - Instagram 如何在不振动(新点赞)和振动(回复)的情况下向 iOS 设备发送推送通知?

ios - 应用程序在某些设备上崩溃

python - 比较运算符之间没有隐含关系

python - 如何以干净整洁的方式打印数据

Python:如何在对象列表上链接方法?

c++ - 生成文件错误 3

python - 如何找到这些有时重叠的圆的中心

azure - Windows 手机 8.1 : Send notification to specified user