セキュリティシステム

このプロジェクトでは、シンプルなセキュリティシステムを作成しました。PIRセンサーが人の動きを検出すると、カメラが起動します。顔が検出されると、写真を撮り、同時に警告メッセージを発信します。

_images/camera.jpg

手順

  1. 顔検出のための vilib ライブラリをインストールします。

    cd ~/
    git clone -b picamera2 https://github.com/sunfounder/vilib.git
    cd vilib
    sudo python3 install.py
    
  2. 以下のコードをRaspberry Piに保存し、例えば security.ty という名前を付けます。

    import os
    from time import sleep, time, strftime, localtime
    from vilib import Vilib
    from robot_hat import Pin, TTS
    
    
    # Initialize the TTS class
    tts = TTS(lang='en-US')
    
    # Display all supported languages
    print(tts.supported_lang())
    
    # Initialize the PIR sensor
    pir = Pin('D0')
    
    def camera_start():
        Vilib.camera_start()
        Vilib.display()
        Vilib.face_detect_switch(True)
    
    def take_photo():
        _time = strftime('%Y-%m-%d-%H-%M-%S', localtime(time()))
        name = f'photo_{_time}'
        username = os.getlogin()
        path = f"/home/{username}/Pictures/"
        Vilib.take_photo(name, path)
        print(f'Photo saved as {path}{name}.jpg')
    
    def main():
        motion_detected = False
        while True:
            # Check for motion
            if pir.value() == 1:
                if not motion_detected:
                    print("Motion detected! Initializing camera...")
                    camera_start()
                    motion_detected = True
                    sleep(2)  # Stabilization delay to confirm motion
    
                # Check for human face and take a photo
                if Vilib.detect_obj_parameter['human_n'] != 0:
                    take_photo()
                    # Read the text
                    tts.say("Security alert: Unrecognized Individual detected. Please verify identity")
                    sleep(2)  # Delay after taking a photo
    
            # If no motion is detected, turn off the camera
            elif motion_detected:
                print("No motion detected. Finalizing camera...")
                Vilib.camera_close()
                motion_detected = False
                sleep(2)  # Delay before re-enabling motion detection
    
            sleep(0.1)  # Short delay to prevent CPU overuse
    
    def destroy():
        Vilib.camera_close()
        print("Camera and face detection stopped.")
    
    if __name__ == '__main__':
        try:
            main()
        except KeyboardInterrupt:
            destroy()
    
  3. このコードを実行するには、 sudo python3 security.py コマンドを使用します。
  4. ウェブブラウザを開いて http://rpi_ip:9000/mjpg にアクセスし、キャプチャされた映像を視聴できます。さらに、キャプチャされた顔の画像は /home/{username}/Pictures/ で見つけることができます。

    _images/browser_camera.jpg