Project showcase
Friends and Enemies Detection for a WatchDog

Friends and Enemies Detection for a WatchDog

Detect friends and enemies by a camera. It can later be used in a watchdog robot.

  • 612 views
  • 1 comment
  • 12 respects

Components and supplies

About this project

This project was built as the final deliverable for our Embedded System course.

Our project is generally about face detection. We designed this project based on the behavior of a guard dog. When the robot guard dog begins to work, the person recognized as its owner gets stored in the Database. And in the databases, there are photos of loved ones. When they see them, they play a special sound. And with this facial recognition, if this person is in the database, their name appears under the rectangle:

Our project is generally about face detection. And since he does not know this person, he does not consider him a nominee:

In the case of a Facebook location, to make it easier to recognize the face, we use gray:

He relays to his owner that this person is a stranger, like a real guard dog. Of course, all that is said in the settings section, which are adjustable like adding new admins or registering an enemy as a friend:

When it comes to faces, he recognizes the owner was among them. Another use of this robot is when the guardian or guard dog is upgraded, we could use the robot telegram for up-to-the-minute updates letting us know where people are going. Project conceptual design:

Code

mainwindowPython
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QDialog
from createadmin import Ui_Dialog as ca_ui
from devels import Ui_Dialog as dev_ui
from settings import Ui_Form as set_ui
from person import Person

HOME_DIR = '/home/pi/.watchdog/'
TMP_DIR=HOME_DIR+'tmp/'


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(543, 343)

        self.centralWidget = QtWidgets.QWidget(MainWindow)
        self.centralWidget.setObjectName("centralWidget")

        self.label = QtWidgets.QLabel(self.centralWidget)
        self.label.setGeometry(QtCore.QRect(100, 80, 131, 31))
        self.label.setObjectName("label")

        self.label_2 = QtWidgets.QLabel(self.centralWidget)
        self.label_2.setGeometry(QtCore.QRect(130, 120, 71, 31))
        self.label_2.setObjectName("label_2")

        self.verticalLayoutWidget = QtWidgets.QWidget(self.centralWidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(330, 30, 160, 211))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")

        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(11, 11, 11, 11)
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setObjectName("verticalLayout")

        self.start_btn = QtWidgets.QPushButton(self.verticalLayoutWidget)
        self.start_btn.setObjectName("start")
        self.start_btn.clicked.connect(self.start)
        self.verticalLayout.addWidget(self.start_btn)

        self.settings_btn = QtWidgets.QPushButton(self.verticalLayoutWidget)
        self.settings_btn.setObjectName("settings")
        self.settings_btn.clicked.connect(self.settings)
        self.verticalLayout.addWidget(self.settings_btn)

        self.developers_btn = QtWidgets.QPushButton(self.verticalLayoutWidget)
        self.developers_btn.setObjectName("developers")
        self.developers_btn.clicked.connect(self.devel)
        self.verticalLayout.addWidget(self.developers_btn)

        self.exit_btn = QtWidgets.QPushButton(self.verticalLayoutWidget)
        self.exit_btn.setObjectName("exit")
        self.exit_btn.clicked.connect(self.exit)
        self.verticalLayout.addWidget(self.exit_btn)

        self.label_3 = QtWidgets.QLabel(self.centralWidget)
        self.label_3.setGeometry(QtCore.QRect(123, 170, 81, 20))
        self.label_3.setObjectName("label_3")
        MainWindow.setCentralWidget(self.centralWidget)
        self.menuBar = QtWidgets.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 543, 22))
        self.menuBar.setObjectName("menuBar")
        MainWindow.setMenuBar(self.menuBar)
        self.mainToolBar = QtWidgets.QToolBar(MainWindow)
        self.mainToolBar.setObjectName("mainToolBar")
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
        self.statusBar = QtWidgets.QStatusBar(MainWindow)
        self.statusBar.setObjectName("statusBar")
        MainWindow.setStatusBar(self.statusBar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "Welcome to watchdog "))
        self.label_2.setText(_translate("MainWindow", "version: 0.1"))
        self.start_btn.setText(_translate("MainWindow", "Start"))
        self.settings_btn.setText(_translate("MainWindow", "Settings"))
        self.developers_btn.setText(_translate("MainWindow", "Developers"))
        self.exit_btn.setText(_translate("MainWindow", "Exit"))
        self.label_3.setText(_translate("MainWindow", "Click on Start"))

    def exit(self):
        import sys
        sys.exit(0)
    
    def start(self):
        persons = self.getpersons()
        if len(persons) > 0:
            start_window = CreateAdmin()
            start_window.show()
            start_window.exec_()
        else:
            self.face_recognition()
    def face_recognition():
        global HOME_DIR    
        global TMP_DIR
        import face_recognition
        import cv2
        import glob
        import MySQLdb            
            
        cap = cv2.VideoCapture(0)
        known_persons = []
        all_faces = glob.glob(HOME_DIR+'*.jpg')
            
        known_faces = []
        known_faces_encodings = []                                     
        for face in all_faces:
            f = face_recognition.load_image_file(face)
            known_faces.append(f)
            e = face_recognition.face_encodings(f)[0]
            known_faces_encodings.append(e)

        db = MySQLdb.connect(host="localhost",db="watchdog",user="watchdog",passwd="23111374" )
        cursor = db.cursor()
    
        cursor.execute('SELECT * FROM persons')
        persons = cursor.fetchall()
        for person in persons:
            p = Person(person['id'], person['fullname'], person['picname'], person['type'])
            known_persons.append(p)	
        db.close()
        
        friend_faces = []
        friend_faces_encodings = []
        friends = []
        friends_type = []
        for person in known_persons:
            if person.type == 'Admin' or person.type == 'Friend':
                friends.append(person)
                friends_type.append(person.type)                
                f = face_recognition.load_image_file(HOME_DIR+person.picname)
                friend_faces.append(f)
                e = face_recognition.face_encodings(f)[0]
                friend_faces_encodings.append(e)
        
        face_locations = []
        face_encodings = []
        face_names = []
        process_this_frame = True

        while True:

            ret, frame = cap.read()
            smal_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 = []
            found_friend = False
            ptype = 'Enemy'
            for face_encoding in friend_faces_encodings:
                matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
                if True in matches:
                    first_match_index = matches.index(True)
                    found_friend = True
                    ptype = friends_type[first_match_index]
                    break
           
            for face_encoding in known_faces_encodings:
                matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
                name = "Unknown"
                if True in matches:
                    first_match_index = matches.index(True)
                    name = friends[first_match_index].full_name + ' - ' + friends[first_match_index].type
                    face_names.append(name)
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
                cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
                font = cv2.FONT_HERSHEY_DUPLEX
                cv2.putText(frame, face_names, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

            import threading
            t = threading.Thread(target=self.playsound,args=(ptype,))            
            t.start()
                        
            cv2.imwrite(TMP_DIR+'faces.jpg', frame)
            image = cv2.imread(TMP_DIR+'faces.jpg')
            faces = detect_faces(image)
            if len(faces) == 1 and not found_friend:
                db = MySQLdb.connect(host="localhost",db="watchdog",user="watchdog",passwd="23111374" )
                cursor = db.cursor()
                cursor.execut('SELCET max(id) as id FROM persons')
                res = cursor.fetchall()                
                max_id = res['id']
                max_id += 1
                import os
                os.rename(TMP_DIR+'faces.jpg',HOME+max_id+'.jpg')
                try:
                    cursor.execute("INSERT INTO persons (id, full_name, picname, type) VALUES (%d, %s, %s, %s)", (max_id, 'Unknown', HOME+max_id+'.jpg', type))
                    db.commit()
                except:
                    db.rollback()
                db.close()
            cv2.imshow('Video', frame)
                        
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        cap.release()
        cv2.destroyAllWindows()
 
    def detect_faces(image):
        haar_faces = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
        detected = haar_faces.detectMultiScale(image, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
    
        return detected                    

    def playsound(type='Enemy'):
        import os
        global HOME_DIR
	
        if type == 'Friend' or type == 'Admin':
            os.system('mpg123 -q ' + HOME_DIR + 'friend.mp3')
        else:
            os.system('mpg123 -q ' + HOME_DIR + 'enemy.mp3')

    def devel(self):
        start_window = Devel()
        start_window.show()
        start_window.exec_()

    
    def settings(self):
        start_window = Settings()
        start_window.show()
        start_window.exec_()



    def getpersons(self):
        import MySQLdb
        db = MySQLdb.connect(host="localhost",db="watchdog",user="watchdog",passwd="23111374" )
        cursor = db.cursor()
        cursor.execute("""
			CREATE TABLE IF NOT EXISTS 'persons' (
				'id' int(11) NOT NULL auto_increment,   
				'fullname' varchar(100) NOT NULL,
				'picname' varchar(250)  NOT NULL ,     
				'type' varchar(20) NOT NULL
			);
		""")
        cursor.execute('SELECT * FROM persons')
        resaults = cursor.fetchall()
        db.close()
        persons = []
        for result in resultes:
            pid = results['id']
            fullname = result['fullname']
            picname = result['picname']
            ptype = result['type']
            
            person = Person()
            person.id = pid
            person.full_name= fullname
            person.picname = picname
            person.type = ptype 
            persons.append(person)
                   
        return persons        
          
        
class CreateAdmin(QDialog, ca_ui):
    def __init__(self):
        #super(CreateAdmin, self).__init__()
        QDialog.__init__(self)        
        self.setupUi(self)

class Devel(QDialog, dev_ui):
    def __init__(self):
        #super(Devel, self).__init__()
        QDialog.__init__(self)        
        self.setupUi(self)

class Settings(QDialog, set_ui):
    def __init__(self):
        #super(Settings, self).__init__()
        QDialog.__init__(self)        
        self.setupUi(self)
settingPython
Settings such as admin override and so on
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'settings.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon, QPixmap
from person import Person

HOME_DIR = '/home/pi/.watchdog/'
PERSONS = []
index = 0
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 516)
        self.fn_lbl = QtWidgets.QLabel(Form)
        self.fn_lbl.setGeometry(QtCore.QRect(110, 10, 161, 20))
        self.fn_lbl.setObjectName("fn_lbl")

        self.horizontalLayoutWidget = QtWidgets.QWidget(Form)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(90, 471, 212, 31))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setSpacing(50)
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.cancel_btn = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.cancel_btn.setObjectName("cancel_btn")
        self.cancel_btn.clicked.connect(self.close)

        self.horizontalLayout.addWidget(self.cancel_btn)

        self.save_btn = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.save_btn.setObjectName("save_btn")        
        self.save_btn.clicked.connect(self.save)

        self.horizontalLayout.addWidget(self.save_btn)

        self.img = QtWidgets.QLabel(Form)
        self.img.setGeometry(QtCore.QRect(23, 60, 351, 251))
        self.img.setText("")
        self.img.setObjectName("img")

        self.horizontalLayoutWidget_2 = QtWidgets.QWidget(Form)
        self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(110, 420, 172, 31))
        self.horizontalLayoutWidget_2.setObjectName("horizontalLayoutWidget_2")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_2)
        self.horizontalLayout_2.setSpacing(10)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")

        self.pervious_btn = QtWidgets.QPushButton(self.horizontalLayoutWidget_2)
        self.pervious_btn.setObjectName("pervious_btn")        
        self.pervious_btn.clicked.connect(self.pervious)
        self.horizontalLayout_2.addWidget(self.pervious_btn)

        self.next_btn = QtWidgets.QPushButton(self.horizontalLayoutWidget_2)
        self.next_btn.setObjectName("next_btn")       
        self.next_btn.clicked.connect(self.next)

        self.horizontalLayout_2.addWidget(self.next_btn)

        self.person_type_lbl = QtWidgets.QLabel(Form)
        self.person_type_lbl.setGeometry(QtCore.QRect(20, 340, 81, 17))
        self.person_type_lbl.setObjectName("person_type_lbl")

        self.horizontalLayoutWidget_3 = QtWidgets.QWidget(Form)
        self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(20, 370, 361, 31))
        self.horizontalLayoutWidget_3.setObjectName("horizontalLayoutWidget_3")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_3)
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")

        self.admin_rb = QtWidgets.QRadioButton(self.horizontalLayoutWidget_3)
        self.admin_rb.setObjectName("admin_rb")
        self.horizontalLayout_3.addWidget(self.admin_rb)

        self.friend_rb = QtWidgets.QRadioButton(self.horizontalLayoutWidget_3)
        self.friend_rb.setObjectName("friend_rb")
        self.horizontalLayout_3.addWidget(self.friend_rb)

        self.enemy_rb = QtWidgets.QRadioButton(self.horizontalLayoutWidget_3)
        self.enemy_rb.setObjectName("enemy_rb")
        self.horizontalLayout_3.addWidget(self.enemy_rb)

        self.fn_edit = QtWidgets.QLineEdit(Form)
        self.fn_edit.setGeometry(QtCore.QRect(120, 10, 251, 25))
        self.fn_edit.setObjectName("fn_edit")

        self.retranslateUi(Form)
        self.setup()
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Settings"))
        self.fn_lbl.setText(_translate("Form", "Person Name"))
        self.cancel_btn.setText(_translate("Form", "Cancel"))
        self.save_btn.setText(_translate("Form", "Save"))
        self.pervious_btn.setText(_translate("Form", "Pervious"))
        self.next_btn.setText(_translate("Form", "Next"))
        self.person_type_lbl.setText(_translate("Form", "Person Type:"))
        self.admin_rb.setText(_translate("Form", "Admin"))
        self.friend_rb.setText(_translate("Form", "Friend"))
        self.enemy_rb.setText(_translate("Form", "Enemy"))
    def setup(self):
        global HOME_DIR    
        global PERSONS
        global index        
        import glob
        import MySQLdb

        db = MySQLdb.connect(host="localhost",db="watchdog",user="watchdog",passwd="23111374" )
		cursor = db.cursor()
		cursor.execute('SELECT * FROM persons')
		persons = cursor.fetchall()
        db.close()
        for person in persons:
	    	p = Person(person['id'], person['fullname'], person['picname'], person['type'])
            PERSONS.append(p)
        self..setText(PERSONS[index].full_name)
        self.person_type_lbl.setText(PERSONS[index].type)
        if PERSONS[index].type == 'Admin':
            self.admin_rb.setChecked(True)
        elif PERSONS[index].type == 'Friend':
            self.friend_rb.setChecked(True)
        else: 
            self.enemy_rb.setChecked(True)
        pixmap = QPixmap(HOME_DIR+PERSONS[index].picname)
        img.setPixmap(pixmap)

    def next(self):
        global index
        index += 1
                
        self.fn_edit.setText(PERSONS[index].full_name)
        self.person_type_lbl.setText(PERSONS[index].type)
        if PERSONS[index].type == 'Admin':
            self.admin_rb.setChecked(True)
        elif PERSONS[index].type == 'Friend':
            self.friend_rb.setChecked(True)
        else: 
            self.enemy_rb.setChecked(True)
        pixmap = QPixmap(HOME_DIR+PERSONS[index].picname)
        img.setPixmap(pixmap)
                
        
    def pervious(slef):
        global index
        index -= 1
                
        self.fn_edit.setText(PERSONS[index].full_name)
        self.person_type_lbl.setText(PERSONS[index].type)
        if PERSONS[index].type == 'Admin':
            self.admin_rb.setChecked(True)
        elif PERSONS[index].type == 'Friend':
            self.friend_rb.setChecked(True)
        else: 
            self.enemy_rb.setChecked(True)
        pixmap = QPixmap(HOME_DIR+PERSONS[index].picname)
        img.setPixmap(pixmap)

    def close(self):
        self.close()

    def save(self):
        global HOME_DIR
        global index
        
        fullname = fn_edit.text()
        pid = PERSONS[index].id       
        picname = PERSONS[index].picname
        ptype = ''        
        if admin_rb.isChecked():
            ptype = 'Admin'
        elif friend_rb.isChecked():
            ptype = 'Friend'
        else:
            ptype = 'Enemy'
        import MySQLdb
        
        db = MySQLdb.connect(host="localhost",db="watchdog",user="watchdog",passwd="23111374" )
		cursor = db.cursor()        
        try:
            cursor.execute ("UPDATE persons SET fullname='%s',picname='%s',ptype='%s' WHERE id=%d",(fullname, picname, ptype, pid))
            db.commit()
        except:
            db.rollback()
        db.close()
image viewPython
Save photos in databases
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'image-vu.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.img = QtWidgets.QLabel(Form)
        self.img.setGeometry(QtCore.QRect(10, 10, 241, 271))
        self.img.setText("")
        self.img.setObjectName("img")
        self.fn_txt = QtWidgets.QPlainTextEdit(Form)
        self.fn_txt.setGeometry(QtCore.QRect(270, 90, 111, 21))
        self.fn_txt.setObjectName("fn_txt")
        self.fnlb = QtWidgets.QLabel(Form)
        self.fnlb.setGeometry(QtCore.QRect(283, 60, 71, 20))
        self.fnlb.setObjectName("fnlb")
        self.verticalLayoutWidget = QtWidgets.QWidget(Form)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(270, 120, 111, 131))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.Friend = QtWidgets.QPushButton(self.verticalLayoutWidget)
        self.Friend.setObjectName("Friend")
        self.verticalLayout.addWidget(self.Friend)
        self.enemy = QtWidgets.QPushButton(self.verticalLayoutWidget)
        self.enemy.setObjectName("enemy")
        self.verticalLayout.addWidget(self.enemy)
        self.delete_btn = QtWidgets.QPushButton(self.verticalLayoutWidget)
        self.delete_btn.setObjectName("delete_btn")
        self.verticalLayout.addWidget(self.delete_btn)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.fnlb.setText(_translate("Form", "Full Name"))
        self.Friend.setText(_translate("Form", "Friend"))
        self.enemy.setText(_translate("Form", "Enemy"))
        self.delete_btn.setText(_translate("Form", "Delete"))
develsPython
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'devels.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(230, 170)
        self.ok = QtWidgets.QPushButton(Dialog)
        self.ok.setGeometry(QtCore.QRect(70, 130, 80, 25))
        self.ok.setObjectName("ok")
        self.verticalLayoutWidget = QtWidgets.QWidget(Dialog)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(20, 20, 196, 88))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.label.setObjectName("label")
        self.verticalLayout.addWidget(self.label)
        self.label_2 = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.label_2.setObjectName("label_2")
        self.verticalLayout.addWidget(self.label_2)
        self.label_3 = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.label_3.setObjectName("label_3")
        self.verticalLayout.addWidget(self.label_3)
        self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.label_4.setObjectName("label_4")
        self.verticalLayout.addWidget(self.label_4)

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.ok.setText(_translate("Dialog", "OK"))
        self.label.setText(_translate("Dialog", "WatchDog"))
        self.label_2.setText(_translate("Dialog", "Version: 0.1"))
        self.label_3.setText(_translate("Dialog", "Developed By:"))
        self.label_4.setText(_translate("Dialog", "Saeed Heydari & Hamid Torkaman"))
programPython
import sys
from PyQt5 import QtGui
from mainwindow import Ui_MainWindow
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)



def main():
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main ()
personPython
class Person():
	def __init__(self, id, full_name, picname, ptype):
		self.id=id
		self.full_name=full_name
		self.picname=picname
		self.type=ptype  
createadmin.pyPython
Determine the admin
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'create-admin.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon, QPixmap
from person import Person

HOME_DIR = '/home/pi/.watchdog/'
TMP_DIR=HOME_DIR+'tmp/'

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(415, 427)
        self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(120, 380, 171, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(90, 30, 61, 17))
        self.label.setObjectName("label")

        self.fn_txt = QtWidgets.QLineEdit(Dialog)
        self.fn_txt.setGeometry(QtCore.QRect(240, 30, 104, 21))
        self.fn_txt.setMinimumSize(QtCore.QSize(104, 0))
        self.fn_txt.setObjectName("fn_txt")

        self.img = QtWidgets.QGraphicsView(Dialog)
        self.img.setGeometry(QtCore.QRect(90, 70, 256, 192))
        self.img.setObjectName("img")

        self.pushButton = QtWidgets.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(180, 290, 80, 25))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.takepic)
        
        self.retranslateUi(Dialog)
        self.buttonBox.accepted.connect(self.ok)
        self.buttonBox.rejected.connect(Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label.setText(_translate("Dialog", "Full Name:"))
        self.pushButton.setText(_translate("Dialog", "Take Picture"))


    def takepic(self):
        global HOME_DIR
        global TMP_DIR
        
        import cv2
        
        cam = cv2.VideoCapture(0)
        
        found_face = False
        while not found_face:
                
            ret, frame = cam.read()
            cv2.imwrite(TMP_DIR+'face.jpg')
            image = cv2.imread(TMP_DIR+'face.jpg')        
            faces = self.detect_faces(image)
            if len(faces) == 1:
                face_found = True
    			picname = '1.jpg'                
                os.rename(TMP_DIR+'face.jpg',HOME_DIR+picname)
                type = 'Admin'
			import MySQLdb
			db = MySQLdb.connect(host="localhost",db="watchdog",user="watchdog",passwd="23111374" )
			cursor = db.cursor()
			try:
				cursor.execute("INSERT INTO persons (full_name, picname, type) VALUES (%s,%s,%s)", (full_name, picname, type))
				db.commit()
                
                for (x,y,w,h) in faces:
	    			cv2.rectangle(image, (x, y), (x+w, y+h), 255)
                cv2.imwrite(TMP_DIR+'face.jpg')
                pixmap = QPixmap(TMP_DIR+'face.jpg')
                self.label.setPixmap(pixmap)
                self.label.resize(pixmap.width(), pixmap.height())                    

            except:
				db.rollback()
				face_found = False
			db.close()
            cam.release()    
                                         
    def detect_faces(image):
    	haar_faces = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
        faces = haar_faces.detectMultiScale(image, scaleFactor=1.3, 
                minNeighbors=4, 
                minSize=(30, 30), 
                flags=cv2.CASCADE_SCALE_IMAGE)
    
        return faces                    

    def ok(self):
        global TMP_DIR
        
        import os
        
        if not self.fn_txt.text() == '' or not self.fn_txt.text() == null:
            pid = 
            fullname = self.fx_txt.text()
            picname = '1.jpg'
            ptype = 'Admin'

            person = Person()
            person.id = pid
            person.full_name = fullname
            person.picname = picname
            person.type = ptype
            self.addtodb(person)
            
            if os.exists(TMP_DIR+'face.jpg'):
                os.remove(TMP_DIR+'face.jpg')

    def addtodb(person):
        import MySQLdb
		db = MySQLdb.connect(host="localhost",db="watchdog",user="watchdog",passwd="23111374" )
		cursor = db.cursor()
		try:
			cursor.execute("INSERT INTO persons (id, full_name, picname, type) VALUES (%s,%s,%s)", (person.id,person.full_name, person.picname, person.type))
			db.commit()            
            except:
				db.rollback()
			db.close()

Comments

Similar projects you might like

Farmaid: Plant Disease Detection Robot

by Teamato

  • 19,656 views
  • 13 comments
  • 83 respects

Where's my stuff?? - Find your misplaced things with Alexa!

Project in progress by Crakers

  • 2,858 views
  • 0 comments
  • 8 respects

Alcohol Detection Project

Project tutorial by ScottC

  • 5,642 views
  • 0 comments
  • 8 respects

Android Things Andy Robot Rasberry Pi3 And Arduino

Project showcase by Dwayne Hoang

  • 2,739 views
  • 0 comments
  • 8 respects

Ball Tracking Robot

Project showcase by Rohan Juneja

  • 51,372 views
  • 41 comments
  • 102 respects
Add projectSign up / Login