顔認識警報システムとAWS自動化


皆さんこんにちは.
このブログでは、アラートシステムとAWSオートメーションプログラムを作成します.
アラートシステム:アラートシステムでは、画像の顔を検出するプログラムを作成し、すぐに画像を検出すると、それはそれをキャプチャし、管理者のメールアドレスにそのイメージを送信し、adminにWhatsAppメッセージを送信します.
AWSオートメーション:AWSオートメーションでは、ユーザーが顔を認識して、顔認識の正確さに基づいて、それは、ボリュームの5 GBと一緒にAWSのインスタンスを作成し、そのボリュームにインスタンスを添付するterraformコードを実行するプログラムを作成しました.
コードから始めましょう
必要条件:
  • Python
  • OpenCV
  • 警報システム


    ライブラリに含まれる

  • 
    import cv2
    from PIL import Image 
    from email.message import EmailMessage
    import smtplib, ssl
    from email.mime.text import MIMEText
    from email.mime.base import MIMEBase
    from email.mime.multipart import MIMEMultipart
    from email import encoders
    import imghdr 
    import os 
    import pywhatkit # for whatsapp 
    
    
    ここでPyWhatKitライブラリはWhatsAppのために使用され、それはプログラムのメッセージを送信するために使用されます.
    imghdrライブラリは、画像の型を見つけるために使用されます.
    PILは画像処理に使用されるPythonイメージライブラリの略です.
    メールとSMTlibライブラリはメールサービスを使用するために使用され、メールを送信するのに役立ちます.
  • モデルを読み込みます
  • model=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    
    
    ここではhaarカスケイドモデルを用いて画像中の顔を検出する.
  • 画像処理用のコードについて議論しましょう
  • while True:
        cap = cv2.VideoCapture(0)
        ret, photo = cap.read()
        faces = model.detectMultiScale(photo)
        if len(faces) == 0:
            pass
        else:
            x1=faces[0][0]
            y1=faces[0][1]
            x2=x1+faces[0][2]
            y2=y1+faces[0][3]
    
            aphoto = cv2.rectangle(photo, (x1,y1), (x2,y2), [0,255,0], 5)
            cv2.imshow("Image Capturing", aphoto)
            if cv2.waitKey(5)==13: #13 is the code for Enter Key
                break
    cv2.destroyAllWindows()
    cap.release()
    
    
    次のコードを実行すると、ウェブカメラが開き、顔を検出します.
    image = Image.fromarray(aphoto)
    image.save('Alert.png')
    image_show=Image.open(r"Alert.png")
    image_crop = image_show.crop((x1,y1,x2,y2))
    image_crop.show()
    image_crop.save('Alert_face_detected.png')
    print("Image Captured")
    
    次のコードイメージでトリミングし、システムに保存します.
  • 今、電子メール警報のためにコードしましょう
  • 
    email_id = os.environ['my_email']
    email_receiver = os.environ['receiver_email']
    password = os.environ['my_password']
    
    #Sender, Reciever, Body of Email
    sender = email_id
    receivers = email_receiver
    body_of_email = 'Alert intrucder has been detected'
    
    #added sender and reciver email addresses
    msg = MIMEMultipart()
    msg['Subject'] = 'Alert Intruder detected'
    msg['From'] = sender
    msg['To'] = receivers
    
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(open('Alert.png', 'rb').read())#Image attached
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename ="Alert.png"')
    msg.attach(part)
    
    #Connecting to Gmail SMTP Server
    s = smtplib.SMTP_SSL(host = 'smtp.gmail.com', port = 465)
    s.login(user = sender, password = password)
    
    s.sendmail(sender, receivers, msg.as_string())
    
    保存されたイメージは、SMTPプロトコルを使用して他のユーザーに郵送されます.
  • 今WhatsAppアラートのコードを聞かせて
  • number = os.environ['phone_number']
    
    import pywhatkit
    pywhatkit.sendwhatmsg(number, 'Alert Intruder Detected ',2,29)
    
    
    次のコードSendWhatMsgは、WhatsAppメッセージを送信するために使用されるPyWhatKitライブラリからの関数です.
    ここで警告された侵入者はメッセージです、そして、2 , 29はメッセージを送る時間です.
    コードが実行された後、WhatSapはブラウザで開き、メッセージが送信されます.

    そのようにすぐに顔が検出されたコードは、画像をキャプチャし、WhatsAppの警告メッセージと一緒に管理者の電子メールアドレスに送信される実行されます.

    顔認識を支援したTRARFORMを用いたAWS自動化


    顔認識プログラムを作成するには、まずデータセットを作成し、データセットを使用する必要があります.
  • 作成データセット
  • コードを次のコードを使用して作成するには、次のコードがユーザーイメージを100回キャプチャし、モデルで使用されるディレクトリに格納します.
    
    import cv2
    import numpy as np
    
    # Load HAAR face classifier
    face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    
    # Load functions
    def face_extractor(img):
        # Function detects faces and returns the cropped face
        # If no face detected, it returns the input image
    
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        faces = face_classifier.detectMultiScale(gray, 1.3, 5)
    
        if faces is ():
            return None
    
        # Crop all faces found
        for (x,y,w,h) in faces:
            cropped_face = img[y:y+h, x:x+w]
    
        return cropped_face
    
    # Initialize Webcam
    cap = cv2.VideoCapture(0)
    count = 0
    # Collect 100 samples of your face from webcam input
    while True:
    
        ret, frame = cap.read()
        if face_extractor(frame) is not None:
            count += 1
            face = cv2.resize(face_extractor(frame), (200, 200))
            face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
    
            # Save file in specified directory with unique name
            #path
            file_name_path = 'Path_of_dir/' + str(count) + '.jpg'
            cv2.imwrite(file_name_path, face)
    
            # Put count on images and display live count
            cv2.putText(face, str(count), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
            cv2.imshow('Face Cropper', face)
    
        else:
            print("Face not found")
            pass
    
        if cv2.waitKey(1) == 13 or count == 100: #13 is the Enter Key
            break
    
    cap.release()
    
    
    cv2.destroyAllWindows()
    
    
    ここでは、画像が100回キャプチャされることを意味*カウント= = 100 *を参照することができます一部の画像は、顔の部分だけがキャプチャされるようにcropedされます.

    このように100の画像がキャプチャされ、ディレクトリに格納されます.
  • は、242479182のモデルを訓練します
    モデルを訓練するには、下のコードを使用し、モデルのトレーニングに役立つコードでイメージデータセットのディレクトリを提供します.
    import cv2
    import numpy as np
    from os import listdir
    from os.path import isfile, join
    
    # Get the training data we previously made
    data_path_1 = 'path_of_image_dataset/'
    onlyfiles_1 = [f for f in listdir(data_path_1) if isfile(join(data_path_1, f))]
    
    
    # Create arrays for training data and labels
    Training_Data_1, Labels_1 = [], []
    # Create arrays for training data and labels
    
    # Create a numpy array for training dataset 1
    for i, files in enumerate(onlyfiles_1):
        image_path = data_path_1 + onlyfiles_1[i]
        images = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
        Training_Data_1.append(np.asarray(images, dtype=np.uint8))
        Labels_1.append(i)   
    
    
    Labels_1 = np.asarray(Labels_1, dtype=np.int32)
    
    
    Nitesh_model  = cv2.face_LBPHFaceRecognizer.create()
    Nitesh_model.train(np.asarray(Training_Data_1), np.asarray(Labels_1))
    print("Model trained sucessefully")
    
    現在、我々のモデルは訓練されます.
  • 作成顔認識プログラム
  • 顔認識プログラムを作成するには、下のコードを使用して、現在の顔認識と顔の認識精度のベースを認識し、それはEBSのボリュームの5 GBと一緒にAWSのインスタンスを作成し、インスタンスに添付されます実行されます.
    
    import cv2
    import numpy as np
    import os
    
    
    face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    
    def face_detector(img, size=0.5):
    
        # Convert image to grayscale
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        faces = face_classifier.detectMultiScale(gray, 1.3, 5)
        if faces is ():
            return img, []
    
    
        for (x,y,w,h) in faces:
            cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,255),2)
            roi = img[y:y+h, x:x+w]
            roi = cv2.resize(roi, (200, 200))
        return img, roi
    
    
    # Open Webcam
    cap = cv2.VideoCapture(0)
    
    while True:
    
        ret, frame = cap.read()
    
        image, face = face_detector(frame)
    
        try:
            face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
    
            # Pass face to prediction model
            # "results" comprises of a tuple containing the label and the confidence value
            results = Nitesh_model.predict(face)
    
            if results[1] < 500:
                confidence = int( 100 * (1 - (results[1])/400) )
                display_string = str(confidence) + '% Confident it is User'
    
            cv2.putText(image, display_string, (100, 120), cv2.FONT_HERSHEY_COMPLEX, 1, (255,120,150), 2)
    
            if confidence > 70:
                cv2.putText(image, "Hello Nitesh", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
                cv2.imshow('Face Recognitioned', image )
                if cv2.waitKey(1)==13:
                    cap.release()
                    cv2.destroyAllWindows()
                    !terraform init
                    !terraform apply --auto-approve
    
    
            else:
                cv2.putText(image, "Unrecognised Face", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)
                cv2.imshow('Face Recognition', image )
    
        except:
            cv2.putText(image, "Face Not Found", (220, 120) , cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)
            cv2.putText(image, "Searching for Face....", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)
            cv2.imshow('Face Recognition', image )
            pass
    
        if cv2.waitKey(1) == 13: #13 is the Enter Key
            break
    
    cap.release()
    cv2.destroyAllWindows()
    

    ここで92 %を参照することができます正確な精度よりもプログラムで言及されているため、それはterraformコードを実行します.
    デモを見る👇