Ajay Rawat
Published © GPL3+

LDR activated IoT based Face recognition security system

Secure your house with future technology - Face Recognition Security system. Finally tomorrow is here.

IntermediateFull instructions provided5 hours2,551

Things used in this project

Hardware components

Bolt WiFi Module
Bolt IoT Bolt WiFi Module
×1
LDR, 5 Mohm
LDR, 5 Mohm
×1
USB-A to Mini-USB Cable
USB-A to Mini-USB Cable
×1
Buzzer
Buzzer
×1
LED (generic)
LED (generic)
×1
Breadboard (generic)
Breadboard (generic)
×1

Software apps and online services

Bolt Cloud
Bolt IoT Bolt Cloud
OpenCV
OpenCV
Visual Studio 2017
Microsoft Visual Studio 2017

Hand tools and fabrication machines

Servo Motor, Premium Male/Male Jumper Wires
Servo Motor, Premium Male/Male Jumper Wires
Premium Female/Male Extension Jumper Wires, 40 x 6" (150mm)
Premium Female/Male Extension Jumper Wires, 40 x 6" (150mm)

Story

Read more

Schematics

Bread board connections

Connections between various devices and the breadboard we are using in this project.

Code

conf.py

Python
This file contains device information of the bolt IoT module we will be using in this project.
api_dev="Enter your own device api id"
dev_id="Enter your own device name"
telegram_chat_id="@Your telegram channel id"
telegram_bot_id="botYour telegram bot tokken"

embedding.py

Python
This file is used for creating encodings for authorized persons and create a pickle file for this data to be used for face-recognition.
import cv2 
import face_recognition
import pickle
name=input("enter name")
ref_id=input("enter id")
try:
    f=open("ref_name.pkl","rb")
    ref_dictt=pickle.load(f)
    f.close()
except:
    ref_dictt={}
ref_dictt[ref_id]=name
f=open("ref_name.pkl","wb")
pickle.dump(ref_dictt,f)
f.close()
try:
    f=open("ref_embed.pkl","rb")
    embed_dictt=pickle.load(f)
    f.close()
except:
    embed_dictt={}

for i in range(5):
    key = cv2. waitKey(1)
    webcam = cv2.VideoCapture(0)
    while True:
       
        check, frame = webcam.read()

        cv2.imshow("Capturing", frame)
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        rgb_small_frame = small_frame[:, :, ::-1]
  
        key = cv2.waitKey(1)

        if key == ord('s') : 
            face_locations = face_recognition.face_locations(rgb_small_frame)
            if face_locations != []:
                face_encoding = face_recognition.face_encodings(frame)[0]
                if ref_id in embed_dictt:
                    embed_dictt[ref_id]+=[face_encoding]
                else:
                    embed_dictt[ref_id]=[face_encoding]
                webcam.release()
                cv2.waitKey(1)
                cv2.destroyAllWindows()     
                break
        elif key == ord('q'):
            print("Turning off camera.")
            webcam.release()
            print("Camera off.")
            print("Program ended.")
            cv2.destroyAllWindows()
            break

f=open("ref_embed.pkl","wb")
pickle.dump(embed_dictt,f)
f.close()

recognition.py

Python
This file is the main file consisting the program to detect the faces for authorized function. And this is the main file which will contain IoT implementation to add functions through our Bolt IoT device.
import face_recognition
import cv2
import numpy as np
import glob
import pickle
import requests
import time,json,conf
from boltiot import Bolt
from datetime import datetime
f=open("ref_name.pkl","rb")
ref_dictt=pickle.load(f)        
f.close()

f=open("ref_embed.pkl","rb")
embed_dictt=pickle.load(f)      
f.close()

known_face_encodings = []  
known_face_names = []

for ref_id , embed_list in embed_dictt.items():
    for my_embed in embed_list:
        known_face_encodings +=[my_embed]
        known_face_names += [ref_id]

mydev=Bolt(conf.api_dev,conf.dev_id)
def read():
        print("Reading LDR value")
        input=mydev.analogRead('A0')
        data=json.loads(input)
        print("LDR value is: "+str(data['value']))
        return data
def buzzon():
        output=mydev.digitalWrite('0','HIGH')
        print(output)
def buzzoff():
        output=mydev.digitalWrite('0','LOW')
        print(output)
def motoron():
        output=mydev.digitalWrite('1','HIGH')
        print(output)
def motoroff():
        output=mydev.digitalWrite('1','LOW')
        print(output)
def send_telegram_message(message):
    """Sends message via Telegram"""
    url = "https://api.telegram.org/" + conf.telegram_bot_id + "/sendMessage"
    data = {
        "chat_id": conf.telegram_chat_id,
        "text": message
    }
    try:
        response = requests.request(
            "POST",
            url,
            params=data
        )
        """print("This is the Telegram URL")
        print(url)
        print("This is the Telegram response")
        print(response.text)"""
        telegram_data = json.loads(response.text)
        return telegram_data["ok"]
    except Exception as e:
        print("An error occurred in sending the alert message via Telegram")
        print(e)
        return False
data1=read()
val1=int(data1['value'])
Found=False
Unknown=False
while True:
        time.sleep(5)
        data2=read()
        val2=int(data2['value'])
        val1=val1+40
        if val2<val1:
                video_capture = cv2.VideoCapture(0)
                face_locations = []
                face_encodings = []
                face_names = []
                process_this_frame = True
                while True:
                        ret, frame = video_capture.read()
                        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
                        rgb_small_frame = small_frame[:, :, ::-1]
                        if process_this_frame:
                                face_locations = face_recognition.face_locations(rgb_small_frame)
                                face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
                                face_names = []
                                for face_encoding in face_encodings:
                                        matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
                                        name = "Unknown"
                                        face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
                                        best_match_index = np.argmin(face_distances)
                                        now = datetime.now()
                                        current_time = now.strftime("%H:%M:%S")
                                        if matches[best_match_index]:
                                                print("Face is found")
                                                name = known_face_names[best_match_index]
                                                message=ref_dictt[name]+", is granted access at :"+current_time
                                                send_telegram_message(message)
                                                print("Welcome",ref_dictt[name])
                                                motoron()
                                                time.sleep(2)
                                                motoroff()
                                                Unknown=False
                                                Found=True
                                        elif name=="Unknown":
                                                print("face didn't matched!!!!!")
                                                message="Intruder Alert!!!!! Intruder tried to break in at : "+current_time
                                                send_telegram_message(message)
                                                motoroff()
                                                buzzon()
                                                time.sleep(2)
                                                buzzoff()
                                                Unknown=True
                                                Found=False
                                        face_names.append(name)
                                        video_capture.release()
                                        cv2.destroyAllWindows()
                                        if Unknown or Found:
                                                break
                                if Unknown or Found:
                                        break        
                if Unknown or Found:
                        break

Credits

Ajay Rawat

Ajay Rawat

3 projects • 7 followers
Electrical Engineering student with a passion for programming. Seek knowledge. Money is just a by-product of our journey toward success.

Comments