人臉識別檢測專案實戰

專注的阿熊發表於2023-01-03

import cv2

import numpy as np

import os

# coding=utf-8

import urllib

import urllib.request

import hashlib

# 載入訓練資料集檔案

recogizer=cv2.face.LBPHFaceRecognizer_create()

recogizer.read('trainer/trainer.yml')

names=[]

warningtime = 0

def md5(str):

     import hashlib

     m = hashlib.md5()

     m.update(str.encode("utf8"))

     return m.hexdigest()

statusStr = {

     '0': ' 簡訊傳送成功 ',

     '-1': ' 引數不全 ',

     '-2': ' 伺服器空間不支援 , 請確認支援 curl 或者 fsocket, 聯絡您的空間商解決或者更換空間 ',

     '30': ' 密碼錯誤 ',

     '40': ' 賬號不存在 ',

     '41': ' 餘額不足 ',

     '42': ' 賬戶已過期 ',

     '43': 'IP 地址限制 ',

     '50': ' 內容含有敏感詞 '

}

def warning():

     smsapi = "

     # 簡訊平臺賬號

     user = '13******10'

     # 簡訊平臺密碼

     password = md5('*******')

     # 要傳送的簡訊內容

     content = ' 【報警】 \n 原因:檢測到未知人員 \n 地點: xxx'

     # 要傳送簡訊的手機號碼

     phone = '*******'

     data = urllib.parse.urlencode({'u': user, 'p': password, 'm': phone, 'c': content})

     send_url = smsapi + 'sms?' + data

     response = urllib.request.urlopen(send_url)

     the_page = response.read().decode('utf-8')

     print(statusStr[the_page])

# 準備識別的圖片

def face_detect_demo(img):

     gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)# 轉換為灰度

face_detector=cv2.CascadeClassifier('D:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')

face=face_detector.detectMultiScale(gray,1.1,5,cv2.CASCADE_SCALE_IMAGE,(100,100),(300,300))

     #face=face_detector.detectMultiScale(gray)

     for x,y,w,h in face:

         cv2.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)

         cv2.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,255,0),thickness=1)

         # 人臉識別

         ids, confidence = recogizer.predict(gray[y:y + h, x:x + w])

         #print(' 標籤 id:',ids,' 置信評分: ', confidence)

         if confidence > 80:

             global warningtime

             warningtime += 1

             if warningtime > 100:

                warning()

                warningtime = 0

             cv2.putText(img, 'unkonw', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)

         else:

             cv2.putText(img,str(names[ids-1]), (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)

     cv2.imshow('result',img)

     #print('bug:',ids)

def name():

     path = './data/jm/'

     #names = []

     imagePaths=[os.path.join(path,f) for f in os.listdir(path)]

     for imagePath in imagePaths:

        name =跟單網gendan5.com str(os.path.split(imagePath)[1].split('.',2)[1])

        names.append(name)

cap=cv2.VideoCapture('1.mp4')

name()

while True:

     flag,frame=cap.read()

     if not flag:

         break

     face_detect_demo(frame)

     if ord(' ') == cv2.waitKey(10):

         break

cv2.destroyAllWindows()

cap.release()

#print(names)


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2930620/,如需轉載,請註明出處,否則將追究法律責任。

相關文章