Friday, September 25, 2020

Multiple Face Detection Using Machine Learning + Python

Multiple Face Detection

           

             Here We will learn about how to identify the multiple faces in on image using different different algorithms and compare which algorithm is giving good results. 

            And at the end will generate the graph to compare the results

  •     Here we need some components like,
    • Python
    • PyCharm
    • Visual Studio libraries
    • Panda library
    • Numpy
    • PyQT5 -- For designing UI
    • and basic knowledge of scripting   


  • Here first we need to develop the Login page for authentication purpose, Below is the code.
from PyQt5 import QtCore, QtGui, QtWidgets
from Code.Home_Page import Ui_MainWindow_Home


class Ui_MainWindow_Login(object):

    #message Box Properties
    def showMessageBox(self, title, message):
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        msgBox = QtWidgets.QMessageBox()
        msgBox.setIcon(QtWidgets.QMessageBox.Information)
        msgBox.setWindowTitle(title)
        msgBox.setText(message)
        msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)
        msgBox.setStyleSheet("QLabel{ color: red}")
        msgBox.setFont(font)
        msgBox.exec_()

    #Login validation Process
    def logincheck(self):
        unm = self.lineEdit.text().upper()
        pwd = self.lineEdit_2.text().upper()
        if unm == "" or unm == "null" or pwd == "" or pwd == "null":
            self.showMessageBox("Details empty ", "\"Username\" and \"Password\" should not be empty")
        else:
            if unm == "ADMIN" and pwd == "ADMIN":
                self.window_Home = QtWidgets.QMainWindow()
                self.ui = Ui_MainWindow_Home()
                #Calling Home Page
                self.ui.setupUi(self.window_Home)
                self.window_Home.show()
                MainWindow_Login.hide()
            else:
                self.showMessageBox("Invalid Entry ", "Entered \"Username\" and \"Password\" are not correct")

    #login Main Window Properties
    def setupUi(self, MainWindow_Login):
        MainWindow_Login.setObjectName("MainWindow_Login")
        MainWindow_Login.resize(800, 600)
        MainWindow_Login.setStyleSheet("background-image: url(../Images/Login_Bg_Image.jpeg);")#Window Bg Image
        MainWindow_Login.setWindowIcon(QtGui.QIcon('../Images/Login.png'))

        self.centralwidget = QtWidgets.QWidget(MainWindow_Login)
        self.centralwidget.setObjectName("centralwidget")

        #Title Properties
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(220, 50, 301, 51))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.label.setStyleSheet("color: Yellow")

        #Username Entry Field Properties
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(220, 160, 191, 41))
        self.lineEdit.setFont(font)
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.setStyleSheet("color: White")

        #Passowrd Entry Field Properties
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(220, 240, 191, 41))
        self.lineEdit_2.setFont(font)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password)
        self.lineEdit_2.setStyleSheet("color: White")

        #Username Text properties
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(90, 160, 121, 41))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.label_2.setStyleSheet("color: rgb(255, 255, 255);")

        #Passowrd Text Properties
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(90, 240, 120, 41))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.label_3.setStyleSheet("color: White")

        #Login Button Properties
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(170, 320, 200, 51))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("background-image:url(../Images/Login_Button.png);")
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.logincheck)

        MainWindow_Login.setCentralWidget(self.centralwidget)
        self.retranslateUi(MainWindow_Login)
        QtCore.QMetaObject.connectSlotsByName(MainWindow_Login)

    def retranslateUi(self, MainWindow_Login):
        _translate = QtCore.QCoreApplication.translate
        MainWindow_Login.setWindowTitle(_translate("MainWindow_Login", "Multiple Face Detection"))
        self.label.setText(_translate("MainWindow_Login", " Multiple Face Detection "))
        self.label_2.setText(_translate("MainWindow_Login", " UserName "))
        self.label_3.setText(_translate("MainWindow_Login", " Password"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow_Login = QtWidgets.QMainWindow()
    ui = Ui_MainWindow_Login()
    ui.setupUi(MainWindow_Login)
    MainWindow_Login.show()
    sys.exit(app.exec_())


  • Next we need to develop the Home page for selecting the type of algorithm to use, below is the code
    from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from Code.Haar_AdaBoost import haarBoost
from Code.LBP_AdaBoost import lbpBoost
from Code.Neural_Network import face_detect_GFNN
from Code.Graph import barChart,lineChart


class Ui_MainWindow_Home(object):

    #message Box Properties
    def showMessageBox(self, title, message):
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        msgBox = QtWidgets.QMessageBox()
        msgBox.setIcon(QtWidgets.QMessageBox.Information)
        msgBox.setWindowTitle(title)
        msgBox.setText(message)
        msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)
        msgBox.setStyleSheet("QLabel{ color: red}")
        msgBox.setFont(font)
        msgBox.exec_()

    #Upload Image process
    def Upload_Image(self):
        fileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, "Select File","..\Testing_Images","Image Files(*.*)")
        #print(fileName)
        self.lineEdit.setText(fileName)

    Selected = 0
    process = ""
    #Choosing Haar_Adaboost Process
    def Haar_AdaBoost(self, select):
        if select:
            Ui_MainWindow_Home.process = "Haar-AdaBoost"
            print("process "+Ui_MainWindow_Home.process)

    #Choosing LBP_Adaboost Process
    def LBP_AdaBoost(self, select):
        if select:
            Ui_MainWindow_Home.process = "LBP-AdaBoost"
            print("process " + Ui_MainWindow_Home.process)

    #Choosing Neral_network Process
    def Neural_Network(self, select):
        if select:
            Ui_MainWindow_Home.process = "Neural-Network"
            print("process " + Ui_MainWindow_Home.process)

    #Detection Process
    def face_detect(self):
        try:
            img = self.lineEdit.text()
            alg = Ui_MainWindow_Home.process

            if img == "" and alg == "":
                self.showMessageBox("Details Empty"," Please upload the \"image\" and select the \"method\" then click on detect")

            else:
                if img == "":
                    self.showMessageBox(" Message ", " Please upload the \"image\" then click on detect")
                else:
                    if (alg == "Haar-AdaBoost"):
                        self.hfaces=0
                        self.ht=0
                        faces, dt = haarBoost(img)
                        self.hfaces = faces
                        self.ht = dt
                        Ui_MainWindow_Home.Selected = Ui_MainWindow_Home.Selected + 1
                    elif (alg == "LBP-AdaBoost"):
                        self.lfaces =0
                        self.lt=0
                        faces, dt = lbpBoost(img)
                        self.lfaces = faces
                        self.lt = dt
                        Ui_MainWindow_Home.Selected = Ui_MainWindow_Home.Selected + 1
                    elif (alg == "Neural-Network"):
                        self.nfaces=0
                        self.nt=0
                        faces, dt = face_detect_GFNN(img)
                        self.nfaces = faces
                        self.nt = dt
                        Ui_MainWindow_Home.Selected = Ui_MainWindow_Home.Selected + 1
                    else:
                        self.showMessageBox(" Invalid ", " Please Choose the method")

            if (int(self.hfaces)>0) and (int(self.lfaces)>0 and int(self.nfaces)>0):
                self.pushButton_3.show()

        except Exception as e:
            pass
            #print("Error=" + e.args[0])
           # tb = sys.exc_info()[2]
           # print(tb.tb_lineno)

    #Taking Number Faces identified vlues for each
    def barlist(self):
        barlist = []
        barlist.clear()
        barlist.append(int(self.hfaces))
        barlist.append(int(self.lfaces))
        barlist.append(int(self.nfaces))
        barChart(barlist)

    #Taking Time taken details for the each
    def htlist1(self):
        htlist = []
        htlist.clear()
        htlist.append(float(self.ht))
        htlist.append(float(self.lt))
        htlist.append(float(self.nt))
        lineChart(htlist)

    #Plotting the graph
    def graph(self):
        self.barlist()
        self.htlist1()

    # Home pge UI Properties
    def setupUi(self, MainWindow_Home):
        MainWindow_Home.setObjectName("MainWindow_Home")
        MainWindow_Home.resize(1000, 666)
        MainWindow_Home.setStyleSheet("background-image: url(../Images/Home_Bg_Image.jpg);")
        MainWindow_Home.setWindowIcon(QtGui.QIcon('../Images/Home.png'))
        self.centralwidget = QtWidgets.QWidget(MainWindow_Home)
        self.centralwidget.setStyleSheet("")
        self.centralwidget.setObjectName("centralwidget")

        #Title Properties
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(130, 60, 750, 51))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(30)
        font.setBold(True)
        font.setItalic(True)
        font.setUnderline(False)
        font.setWeight(75)
        font.setStrikeOut(False)
        font.setKerning(True)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignJustify|QtCore.Qt.AlignVCenter)
        self.label.setObjectName("label")
        self.label.setStyleSheet("color : white")

        #User Message Properties
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(160, 160, 660, 50))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.label_2.setStyleSheet("color : white")

        #Choosing Image entry Field properties
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(190, 230, 500, 50))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(9)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit.setFont(font)
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.setStyleSheet("color: rgb(255, 255, 255);")

        #Detect button properties
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(180, 450, 201, 40))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("color : white")
        self.pushButton.setObjectName("pushButton")
        #self.pushButton.setStyleSheet("background-image:url(../Images/detect.jpg);")
        self.pushButton.clicked.connect(self.face_detect)

        #Upload Image Button Properties
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(690, 230, 120, 50))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.clicked.connect(self.Upload_Image)
        self.pushButton_2.setStyleSheet("background-image:url(../Images/Upload_Image.jpg);")

        #Haar Adaboost Radio Button Properties
        self.radioButton = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton.setGeometry(QtCore.QRect(90, 320, 240, 34))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.radioButton.setFont(font)
        self.radioButton.setObjectName("radioButton")
        self.radioButton.toggled.connect(self.Haar_AdaBoost)
        self.radioButton.setStyleSheet("color : white")

        #Neural Network Radio Button Properties
        self.radioButton_1 = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton_1.setGeometry(QtCore.QRect(630, 320, 220, 34))
        self.radioButton_1.setFont(font)
        self.radioButton_1.setObjectName("radioButton_4")
        self.radioButton_1.toggled.connect(self.Neural_Network)
        self.radioButton_1.setStyleSheet("color : white")

        #LBP Adaboost Radio Button Properties
        self.radioButton_2 = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton_2.setGeometry(QtCore.QRect(370, 320, 220, 34))
        self.radioButton_2.setFont(font)
        self.radioButton_2.setObjectName("radioButton_5")   
        self.radioButton_2.toggled.connect(self.LBP_AdaBoost)
        self.radioButton_2.setStyleSheet("color : white")

        #Compare Button Properties
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(550, 450, 201, 40))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_3.hide()
        self.pushButton_3.clicked.connect(self.graph)
        self.pushButton_3.setStyleSheet("color : white")

        #Logout Button Properties
        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setGeometry(QtCore.QRect(820, 610, 160, 40))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_4.setFont(font)
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_4.setStyleSheet("color : white")
        self.pushButton_4.setStyleSheet("background-image:url(../Images/Logout_Button.jpg);")
        self.pushButton_4.clicked.connect(MainWindow_Home.close)

        MainWindow_Home.setCentralWidget(self.centralwidget)

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

    def retranslateUi(self, MainWindow_Home):
        _translate = QtCore.QCoreApplication.translate
        MainWindow_Home.setWindowTitle(_translate("MainWindow_Home", "Multiple Face Detection "))
        self.label.setText(_translate("MainWindow_Home", "Welcome to Multiple Face Detection "))
        self.label_2.setText(_translate("MainWindow_Home", " Upload Image below, select the method and then click on Detect"))
        self.pushButton.setText(_translate("MainWindow_Home", "Detect"))
        #self.pushButton_2.setText(_translate("MainWindow_Home", "Upload"))

        self.radioButton.setText(_translate("MainWindow_Home", "HAAR - AdaBoost"))
        self.radioButton_1.setText(_translate("MainWindow_Home", "Neural Network"))
        self.radioButton_2.setText(_translate("MainWindow_Home", "LBP - AdaBoost"))

        self.pushButton_3.setText(_translate("MainWindow_Home", "Compare"))
        #self.pushButton_4.setText(_translate("MainWindow_Home", "LogOut"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow_Home = QtWidgets.QMainWindow()
    ui = Ui_MainWindow_Home()
    ui.setupUi(MainWindow_Home)
    MainWindow_Home.show()
    sys.exit(app.exec_())


  • Here we are using Three methods, Haar adaboost, LBP Adaboost and Neural Networks
  • We need to write the codes for all three
Haar adaboost.py
import numpy as np
import cv2

import time


def detect_faces(f_cascade, colored_img, scaleFactor=1.1):
    img_copy = np.copy(colored_img)
    # convert the test image to gray image as opencv face detector expects gray images
    gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY)

    #t1 = time.time()
    # let's detect multiscale (some images may be closer to camera than others) images
    faces = f_cascade.detectMultiScale(gray, scaleFactor=scaleFactor);
   # t2 = time.time()
    #dt1 = t2 - t1
    #print("dt=",dt1)
    # print the number of faces found
    print("Haar_AdaBoost")
    print('Faces found: ', len(faces))

    # go over list of faces and draw them as rectangles on original colored img
    for (x, y, w, h) in faces:
        cv2.rectangle(img_copy, (x, y), (x + w, y + h), (0, 255, 0), 2)

    return img_copy,len(faces)


def haarBoost(img):
    image = cv2.imread(img)
    haar_face_cascade = cv2.CascadeClassifier('../Cascade_Files/haarcascade_frontalface_alt.xml')
    t1 = time.time()
    # call our function to detect faces
    faces_detected_img,number_of_faces= detect_faces(haar_face_cascade, image)
    t2 = time.time()
    dt1 = t2 - t1
    print("Detection Time:",dt1)
    print("-----------------------------------------")
    # conver image to RGB and show image
   # plt.imshow()
    cv2.imshow('Haar AdaBoost', faces_detected_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return number_of_faces,dt1



#haarBoost('face3.jpg')


LBP_Adaboost.py

import numpy as np
import cv2

import time


def detect_faces(f_cascade, colored_img, scaleFactor=1.1):
    img_copy = np.copy(colored_img)
    # convert the test image to gray image as opencv face detector expects gray images
    gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY)
   # t1 = time.time()
    # let's detect multiscale (some images may be closer to camera than others) images
    faces = f_cascade.detectMultiScale(gray, scaleFactor=scaleFactor);
    #t2 = time.time()
    #dt1 = t2 - t1
    ##print("dt2=", dt1)
    # print the number of faces found
    print("LBP AdaBoost")
    print('Faces found: ', len(faces))

    # go over list of faces and draw them as rectangles on original colored img
    for (x, y, w, h) in faces:
        cv2.rectangle(img_copy, (x, y), (x + w, y + h), (0, 255, 0), 2)

    return img_copy,len(faces)


def lbpBoost(img):
    image = cv2.imread(img)
    lbp_face_cascade=cv2.CascadeClassifier('../Cascade_Files/lbpcascade_frontalface.xml')
    t1 = time.time()
    # call our function to detect faces
    faces_detected_img,number_of_faces = detect_faces(lbp_face_cascade, image)
    t2 = time.time()
    dt1 = t2 - t1
    print("Detecting time: ",dt1)
    print("-----------------------------------------")
    # conver image to RGB and show image
   # plt.imshow()
    cv2.imshow('LBP AdaBoost', faces_detected_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return number_of_faces, dt1

#lbpBoost('face3.jpg')

Neural Network.py

import  face_recognition
import cv2
from PIL import Image
import time

def face_detect_GFNN(img):
    inputimage = cv2.imread(img)
    image = face_recognition.load_image_file(img)
    t1 = time.time()
    face_locations = face_recognition.face_locations(image)
    t2 = time.time()
    dt1 = t2 - t1
    number_of_faces=format(len(face_locations))

    print("Neural Network")
    print("found {} faces.".format(len(face_locations)))
    print("Detection time=",dt1)
    # i=0
    for face_location in face_locations:
        top, right, bottom, left = face_location
        face_image = image[top:bottom, left:right]
        cv2.rectangle(inputimage, (left, top), (right, bottom), (0, 0, 255), 2)

    cv2.imshow('GF_NN', inputimage)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return number_of_faces, dt1

#face_detect_GFNN('face4.jpg')
 

  • For developing the graph based on result captured we need to write the code using Python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt1
import sys

def barChart(rlist):
    height=rlist
    bars = ('Haar_Adaoost', 'LBP_AdaBoost', 'Neural_Network')
    y_pos = np.arange(len(bars))
    plt.bar(y_pos, height, color=['red', 'green', 'blue'])
    plt.xticks(y_pos, bars)
    plt.xlabel('Algorithms')
    plt.ylabel('Number of Faces')
    plt.title('Prediction Accuracy Analysis')
    plt.show()


def lineChart(list):
    try:
        alg = ['Haar_Adaoost', 'LBP_AdaBoost', 'Neural_Network']
        plt1.plot(alg, list, color='red')
        plt1.xlabel('Algorithms')
        plt1.ylabel('Seconds')
        plt1.title('Prediction Time Analysis')
        plt1.show()


    except Exception as e:
        print("Error=" + e.args[0])
        tb = sys.exc_info()[2]
        print(tb.tb_lineno)
        print(e)

#barChart()
#lineChart()


Efficient Facial Expression Identification Using Machine Learning + Python

Efficient Facial Expression Identification
    
           Here you will learn how to find the facial expression of an human using Python and Machine learning. 
    Here we need some components like,
  • Python
  • PyCharm
  • Visual Studio libraries
  • Panda library
  • Numpy
  • PyQT5 -- For designing UI
  • and basic knowledge of scripting

    • Firstly we need to design the LOGIN PAGE for login purpose. Below is the code for home page and save this as "login_page.py"
            from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):

    #Message Box Properties
    def showMessageBox(self, title, message):
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        msgBox = QtWidgets.QMessageBox()
        msgBox.setIcon(QtWidgets.QMessageBox.Information)
        msgBox.setWindowTitle(title)
        msgBox.setText(message)
        msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)
        msgBox.setStyleSheet("QLabel{ color: red}")
        msgBox.setFont(font)
        msgBox.exec_()

    #Login Button Function
    def logincheck(self):
        unm = self.lineEdit.text().upper()
        pwd = self.lineEdit_2.text().upper()
        if unm == "" or unm == "null" or pwd == "" or pwd == "null":
            self.showMessageBox("Details Empty", "\"Username\" and \"Password\" should not be empty")
        else:
            if unm == "ADMIN" and pwd == "ADMIN":
                from Code.Home_Page import Ui_Home
                MainWindow_LogIn.hide()
                self.window_Home = QtWidgets.QMainWindow()
                self.ui = Ui_Home()
                #Calling Home Page
                self.ui.setupUi(self.window_Home)
                self.window_Home.show()
                print("Login Successful")
            else:
                self.showMessageBox("Invalid Entry ", "Entered \"Username\" and \"Password\" are not correct")

    #Main Widnow UI Code
    def setupUi(self, MainWindow_LogIn):
        MainWindow_LogIn.setObjectName("MainWindow_LogIn")
        MainWindow_LogIn.setWindowModality(QtCore.Qt.ApplicationModal)
        MainWindow_LogIn.resize(950, 666)
        MainWindow_LogIn.setStyleSheet("background-image: url(../Images/Login_Bg_Image.jpeg);")#Window Bg Image
        MainWindow_LogIn.setWhatsThis("")
        self.centralwidget = QtWidgets.QWidget(MainWindow_LogIn)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow_LogIn.setWindowIcon(QtGui.QIcon('../Images/Login.png')) #Window Icon

        #Login Button
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(200, 360, 200, 51))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setStyleSheet("background-image:url(../Images/Login_Button.png);")
        self.pushButton.clicked.connect(self.logincheck)

        #UserName Lable Properties
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(119, 180, 120, 40))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.label.setStyleSheet("color: rgb(255, 255, 255);")

        #UserName Entry Field Properties
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(250, 180, 240, 40))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.setFont(font)
        #self.lineEdit.setText("admin")
        self.lineEdit.setStyleSheet("color: White")

        #Title Properties
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(200, 70, 571, 41))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.label_3.setFont(font)
        self.label_3.setTextFormat(QtCore.Qt.PlainText)
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setWordWrap(False)
        self.label_3.setObjectName("label_3")
        self.label_3.setStyleSheet("color: White")

        #Password Entry Field Properties
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(250, 270, 240, 40))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_2.setFont(font)
        self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password)
        #self.lineEdit_2.setText("admin")
        self.lineEdit_2.setStyleSheet("color: White")

        #Password Label Properties
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(130, 270, 100, 40))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.label_2.setStyleSheet("color: White")

        MainWindow_LogIn.setCentralWidget(self.centralwidget)
        self.retranslateUi(MainWindow_LogIn)
        QtCore.QMetaObject.connectSlotsByName(MainWindow_LogIn)

    def retranslateUi(self, MainWindow_LogIn):
        _translate = QtCore.QCoreApplication.translate
        MainWindow_LogIn.setWindowTitle(_translate("MainWindow_LogIn", "Efficient Facial Expression Recognition"))
        self.label.setText(_translate("MainWindow_LogIn", "UserName"))
        self.label_3.setText(_translate("MainWindow_LogIn", "Efficient Facial Expression Recognition"))
        self.label_2.setText(_translate("MainWindow_LogIn", "Password"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow_LogIn = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow_LogIn)
    MainWindow_LogIn.show()
    sys.exit(app.exec_())

    •  Next we need to develop the HOME PAGE for selecting the input type between Image or live Camera or Camera
                
            from PyQt5 import QtCore, QtGui, QtWidgets
import sys


class Ui_Home(object):

    # Message Box Properties
    def showMessageBox(self, title, message):
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        msgBox = QtWidgets.QMessageBox()
        msgBox.setIcon(QtWidgets.QMessageBox.Information)
        msgBox.setWindowTitle(title)
        msgBox.setText(message)
        msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)
        msgBox.setStyleSheet("QLabel{ color: red}")
        msgBox.setFont(font)
        msgBox.exec_()

    #Image Upload value set
    process = ""
    def Upload_image(self, Upload_image):
        if Upload_image:
            Ui_Home.process = "Image"
            print("Choosed Method : Using Image")

    #Using WebCamera value set
    def Using_WebCamera(self, Using_WebCamera):
        if Using_WebCamera:
            Ui_Home.process = "WebCamera"
            print("Choosed Method : Using WebCamera")

    #Process Selection
    def startprocess(self):
        #Using Image Process
        if Ui_Home.process == "Image":
            try:
                from Code.Image_Upload_Page import Ui_Upload_Image

                self.Dialog2 = QtWidgets.QDialog()
                self.ui2 = Ui_Upload_Image()
                self.ui2.setupUi(self.Dialog2)
                self.Dialog2.show()

            except Exception as e:
                print("Error=" + e.args[0])
                tb = sys.exc_info()[2]
                print(tb.tb_lineno)
                print(e)
        else:
            #Using Web Camera Process
            if Ui_Home.process == "WebCamera":
                try:
                    from Code.WebCamera_Recognise import WebCamDetection

                    self.showMessageBox("Message", "Launching WebCamera, Press 's' to Stop Detection ")
                    WebCamDetection.process()

                except Exception as e:
                    print("Error=" + e.args[0])
                    tb = sys.exc_info()[2]
                    print(tb.tb_lineno)
                    print(e)
            else:
                self.showMessageBox(" Choose Method ", "Please choose any between \"Image\" Or \"web camara\" ")

    #Home Page Properties
    def setupUi(self, MainWindow_Home):
        MainWindow_Home.setObjectName("MainWindow_Home")
        MainWindow_Home.resize(980, 666)
        MainWindow_Home.setAutoFillBackground(False)
        MainWindow_Home.setStyleSheet("background-image: url(../Images/Home_Bg_Image.jpg);")
        MainWindow_Home.setWindowIcon(QtGui.QIcon('../Images/Home.png'))

        #Ttile Properties
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(30)
        font.setBold(True)
        font.setItalic(True)
        font.setUnderline(False)
        font.setWeight(75)
        font.setStrikeOut(False)
        font.setKerning(True)
        self.centralwidget = QtWidgets.QWidget(MainWindow_Home)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(50, 50, 1000, 100))
        self.label.setObjectName("label")
        self.label.setFont(font)
        self.label.setStyleSheet("color : white")

        #Text Message on display properties
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(21)
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(300)
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(90, 150, 800, 60))
        self.label_2.setObjectName("label_2")
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("color : White")

        #Using Image Radio Button Properties
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        font.setBold(True)
        self.radioButton = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton.setGeometry(QtCore.QRect(150, 280, 250, 50))
        self.radioButton.setObjectName("radioButton")
        self.radioButton.toggled.connect(self.Upload_image)
        self.radioButton.setFont(font)
        self.radioButton.setStyleSheet("color:rgb(255,255,255)")

        #Using Web camera Radio Button Properties
        self.radioButton_2 = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton_2.setGeometry(QtCore.QRect(630, 280, 250, 50))
        self.radioButton_2.setObjectName("radioButton_2")
        self.radioButton_2.setFont(font)
        self.radioButton_2.setStyleSheet("color:white")
        self.radioButton_2.toggled.connect(self.Using_WebCamera)

        #Image Image
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(150, 330, 250, 191))
        self.label_3.setObjectName("label_3")
        self.label_3.setStyleSheet("image: url(../Images/Using_Image.png);")

        #Webcam Image
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(630, 330, 250, 190))
        self.label_4.setObjectName("label_4")
        self.label_4.setStyleSheet("image: url(../Images/Using_WebCam.png);")

        #Continue Button Properties
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(300)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(380, 560, 250, 50))
        self.pushButton.setFocusPolicy(QtCore.Qt.NoFocus)
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("background:white;")
        self.pushButton.clicked.connect(self.startprocess)
        self.pushButton.setStyleSheet("background-image:url(../Images/Continue_Button.png);")

        #LogOut Button Properties
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(800, 615, 155, 40))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.setFont(font)
        self.pushButton_2.setStyleSheet("color:Green")
        self.pushButton_2.setStyleSheet("background-image:url(../Images/Logout_Button.jpg);")
        self.pushButton_2.clicked.connect(MainWindow_Home.close)

        MainWindow_Home.setCentralWidget(self.centralwidget)
        self.retranslateUi(MainWindow_Home)
        QtCore.QMetaObject.connectSlotsByName(MainWindow_Home)

    def retranslateUi(self, MainWindow_Home):
        _translate = QtCore.QCoreApplication.translate
        MainWindow_Home.setWindowTitle(_translate("MainWindow_Home", "Efficient Facial Expression Recognition"))
        self.label.setText(_translate("Home", "Welcome to Facial Expression Recognition\n"))
        self.label_2.setText(_translate("Home", "Choose any one option below and click on CONTINUE"))
        self.radioButton.setText(_translate("Home", "Using Image"))
        self.radioButton_2.setText(_translate("Home", "Using WebCamera"))
        self.label_3.setText(_translate("Home", ""))
        self.label_4.setText(_translate("Home", ""))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow_Home = QtWidgets.QMainWindow()
    ui = Ui_Home()
    ui.setupUi(MainWindow_Home)
    MainWindow_Home.show()
    sys.exit(app.exec_())

        
    • Based on selection, If we choose Image as input For uploading the image we need to create one more page as "image_upload_page.py". Here we can upload the image
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Upload_Image(object):

    # Message Box Properties
    def showMessageBox(self, title, message):
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        msgBox = QtWidgets.QMessageBox()
        msgBox.setIcon(QtWidgets.QMessageBox.Information)
        msgBox.setWindowTitle(title)
        msgBox.setText(message)
        msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)
        msgBox.setStyleSheet("QLabel{ color: red}")
        msgBox.setFont(font)
        msgBox.exec_()

    #Upload Image properties
    def uploadimage(self):
        try:
            fileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, "Select File","..\Testing_Images","Image Files(*.*)") #Image Files(*.*)
            #print(fileName)
            self.lineEdit.setText(fileName)

        except Exception as e:
            print("Error=" + e.args[0])
            tb = sys.exc_info()[2]
            print(tb.tb_lineno)
            print(e)

    #Using Web Camera Properties
    def startrecognise(self):
        try:
            fname = self.lineEdit.text()
            if fname == "":
                self.showMessageBox("Insufficient Data","Please upload the \"image\" then click on Recognise")
            else:
                from Code.Image_Recognise import ImageDetection
                ImageDetection.process(fname)

        except Exception as e:
            print(e.args[0])
            tb = sys.exc_info()[2]
            print(tb.tb_lineno)
            print(e)

    #Upload Image UI Properties
    def setupUi(self, Upload_Image):
        Upload_Image.setObjectName("Upload_Image")
        Upload_Image.resize(550, 280)
        Upload_Image.setStyleSheet("background-image: url(../Images/Upload_Bg_Image.jpeg);")
        Upload_Image.setWindowIcon(QtGui.QIcon('../Images/Upload.png'))

        #Display Message to user properties
        self.label = QtWidgets.QLabel(Upload_Image)
        self.label.setGeometry(QtCore.QRect(60, 30, 451, 31))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.label.setStyleSheet("color: rgb(255, 255, 255);")

        #Select image box properties
        self.lineEdit = QtWidgets.QLineEdit(Upload_Image)
        self.lineEdit.setGeometry(QtCore.QRect(70, 100, 270, 40))
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setObjectName("lineEdit")
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(9)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit.setFont(font)
        self.lineEdit.setStyleSheet("color: rgb(255, 255, 255);")


        #Upload button properties
        self.pushButton = QtWidgets.QPushButton(Upload_Image)
        self.pushButton.setGeometry(QtCore.QRect(340, 100, 120, 40))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("background-image:url(../Images/Upload_Image.jpg);")
        self.pushButton.setText("")
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.uploadimage)

        #Recognise Button Properties
        self.pushButton_2 = QtWidgets.QPushButton(Upload_Image)
        self.pushButton_2.setGeometry(QtCore.QRect(150, 170, 150, 40))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.clicked.connect(self.startrecognise)
        self.pushButton_2.setStyleSheet("background-image:url(../Images/Recognise_Button.png);")

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

    def retranslateUi(self, Upload_Image):
        _translate = QtCore.QCoreApplication.translate
        Upload_Image.setWindowTitle(_translate("Upload_Image", "Upload Image"))
        self.label.setText(_translate("Upload_Image", " Upload image below and click on Recognise "))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Upload_Image = QtWidgets.QWidget()
    ui = Ui_Upload_Image()
    ui.setupUi(Upload_Image)
    Upload_Image.show()
    sys.exit(app.exec_())
    
    • Once the image is uploaded we need to click on recognize. For recognition purpose we need to write the code using Neural Networks and HAAR AdaBoost methods.
from statistics import mode
import os
import cv2
from keras.models import load_model
import numpy as np
from utils.datasets import get_labels
from utils.inference import detect_faces
from utils.inference import draw_text
from utils.inference import draw_bounding_box
from utils.inference import apply_offsets
from utils.inference import load_detection_model
from utils.preprocessor import preprocess_input
from PIL import Image


class ImageDetection:

    @staticmethod
    def process(image):
        print("Started Recognising")
        os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
        # parameters for loading data and images
        detection_model_path = '../Models/Detection_Model/haarcascade_frontalface_default.xml'
        emotion_model_path = '../Models/Emotion_Models/fer2013_mini_XCEPTION.110-0.65.hdf5' #fer2013_mini_XCEPTION.102-0.66.hdf5
        emotion_labels = get_labels('fer2013')

        # hyper-parameters for bounding boxes shape
        frame_window = 10
        emotion_offsets = (20, 40)

        # loading models
        face_detection = load_detection_model(detection_model_path)
        emotion_classifier = load_model(emotion_model_path, compile=False)

        # getting input model shapes for inference
        emotion_target_size = emotion_classifier.input_shape[1:3]

        # starting lists for calculating modes
        emotion_window = []

        # starting video streaming
        cv2.namedWindow('window_frame')
        #video_capture = cv2.VideoCapture(0)
        # Load an color image in grayscale
        img = cv2.imread(image)

        bgr_image = img
        gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)
        rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
        faces = detect_faces(face_detection, gray_image)

        for face_coordinates in faces:

            x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets)
            gray_face = gray_image[y1:y2, x1:x2]
            try:
                gray_face = cv2.resize(gray_face, (emotion_target_size))
            except:
                continue

            gray_face = preprocess_input(gray_face, True)
            gray_face = np.expand_dims(gray_face, 0)
            gray_face = np.expand_dims(gray_face, -1)
            emotion_prediction = emotion_classifier.predict(gray_face)
            emotion_probability = np.max(emotion_prediction)
            emotion_label_arg = np.argmax(emotion_prediction)
            emotion_text = emotion_labels[emotion_label_arg]
            emotion_window.append(emotion_text)
            if len(emotion_window) > frame_window:
                emotion_window.pop(0)
            try:
                emotion_mode = mode(emotion_window)
            except:
                continue

            if emotion_text == 'angry':
                color = emotion_probability * np.asarray((255, 0, 0))
            elif emotion_text == 'sad':
                color = emotion_probability * np.asarray((0, 0, 255))
            elif emotion_text == 'happy':
                color = emotion_probability * np.asarray((255, 255, 0))
            elif emotion_text == 'surprise':
                color = emotion_probability * np.asarray((0, 255, 255))
            elif emotion_text == 'fear':
                color = emotion_probability * np.asarray((255, 255, 255))
            else:
                color = emotion_probability * np.asarray((0, 255, 0))

            color = color.astype(int)
            color = color.tolist()

            draw_bounding_box(face_coordinates, rgb_image, color)
            draw_text(face_coordinates, rgb_image, emotion_mode,
                      color, 0, -45, 1, 1)
        bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
        cv2.imwrite("../Images/Temp/output.jpg", bgr_image)
        # os.system("powershell -c out.jpg")
        img = Image.open("../Images/Temp/output.jpg")
        img.show()

    • If we select the video in Home Page, it should launch the camera and start recognizing the expression dynamically

from statistics import mode
import os
import cv2
from keras.models import load_model
import numpy as np
import sys
from utils.datasets import get_labels
from utils.inference import detect_faces
from utils.inference import draw_text
from utils.inference import draw_bounding_box
from utils.inference import apply_offsets
from utils.inference import load_detection_model
from utils.preprocessor import preprocess_input

class WebCamDetection:

    @staticmethod
    def process():
        try:

            os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
            # parameters for loading data and images
            detection_model_path = '../Models/Detection_Model/haarcascade_frontalface_default.xml'
            emotion_model_path = '../Models/Emotion_Models/fer2013_mini_XCEPTION.102-0.66.hdf5'
            emotion_labels = get_labels('fer2013')

            # hyper-parameters for bounding boxes shape
            frame_window = 10
            emotion_offsets = (20, 40)

            # loading models
            face_detection = load_detection_model(detection_model_path)
            emotion_classifier = load_model(emotion_model_path, compile=False)

            # getting input model shapes for inference
            emotion_target_size = emotion_classifier.input_shape[1:3]

            # starting lists for calculating modes
            emotion_window = []

            # starting video streaming
            cv2.namedWindow('window_frame')
            video_capture = cv2.VideoCapture(0)
            while True:
                bgr_image = video_capture.read()[1]
                gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)
                rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
                faces = detect_faces(face_detection, gray_image)

                for face_coordinates in faces:

                    x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets)
                    gray_face = gray_image[y1:y2, x1:x2]
                    try:
                        gray_face = cv2.resize(gray_face, (emotion_target_size))
                    except:
                        continue

                    gray_face = preprocess_input(gray_face, True)
                    gray_face = np.expand_dims(gray_face, 0)
                    gray_face = np.expand_dims(gray_face, -1)
                    emotion_prediction = emotion_classifier.predict(gray_face)
                    emotion_probability = np.max(emotion_prediction)
                    emotion_label_arg = np.argmax(emotion_prediction)
                    emotion_text = emotion_labels[emotion_label_arg]
                    emotion_window.append(emotion_text)

                    if len(emotion_window) > frame_window:
                        emotion_window.pop(0)
                    try:
                        emotion_mode = mode(emotion_window)
                    except:
                        continue

                    if emotion_text == 'angry':
                        color = emotion_probability * np.asarray((255, 0, 0))
                    elif emotion_text == 'sad':
                        color = emotion_probability * np.asarray((0, 0, 255))
                    elif emotion_text == 'happy':
                        color = emotion_probability * np.asarray((255, 255, 0))
                    elif emotion_text == 'surprise':
                        color = emotion_probability * np.asarray((0, 255, 255))
                    else:
                        color = emotion_probability * np.asarray((0, 255, 0))

                    color = color.astype(int)
                    color = color.tolist()

                    draw_bounding_box(face_coordinates, rgb_image, color)
                    draw_text(face_coordinates, rgb_image, emotion_mode,
                              color, 0, -45, 1, 1)

                bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
                cv2.imshow('window_frame', bgr_image)

                if cv2.waitKey(1) & 0xFF == ord('s'):
                    break
        except Exception as e:
            print("Errors=" + e.args[0])
            tb = sys.exc_info()[2]
            print(tb.tb_lineno)
            print(e)


if __name__=="__main__":
    WebCamDetection.process()


  • Here we will use Two files as dataset files for Haar Adaboost method. (Please comment your mail id here if u need these files).
  • For video and full execution explain please watch 

Saturday, September 19, 2020

Selenium + Java Programs and explaination

Steps for how to create the Java Project In Selenium


  1. Add Selenium Jars 
    • Download the Jar files related to  OS ( from selenium.org Site)
                       
    • Once the download is completed, please follow the below steps to add the jars to the out project.
      • Create the new folder under your project named as “lib”
      • Then create the subfolder under the “lib” and name it as “Selenium Jars” 
      • Now copy the downloaded jar file to “selenium Jar” Folder
            
    • Once the copy is done, Do the right click on the Jar file and select the “Build Path” and the select the “Add to Build Path”  
    • Once you clicked on the “Add to build path” u can able to see the jar file added to our project under the referenced Libraries.        
                                            
                    
        2.    Write a program to launch browser and navigate to a specified link
    • Now we need to write a sample program to open the browser and go to the mentioned link in the program.    
    • For that we need to create the New Package inside the Package “src”, and name it as “test”(U can name whatever u want).
    • In “test” Package now we need to create the new class name it as “SeleniumTest”.
    • Now we need to write the program in the Class,
      • We need to create the object for the web Driver 


    • In the above image, u can see some errors in the code, that is because we have not imported the required packages to our package.
    • For importing the package we need to move the mouse over the word and select the appropriate package








    • For opening the browser we use the driver.get (" ")


    • Once we run the above program we will get the error as below,


    • For that, we need to add the “Gecko” Driver to our project
      • https://github.com/mozilla/geckodriver/releases


      • Download the driver which is suitable to OS
    • Once the “Gecko” Driver is downloaded, copy this driver to our project like below


    • Once it is copied in our project we need to add the Gecko Driver to project using below method


    • System.setProperty("webdriver.gecko.driver", "C:\\Java_Manideep\\SeleniumTest2\\lib\\GeckoDriver\\geckodriver.exe");
    • You can get the file path for the gecko driver as below
      • Right-click on the Gecko Driver


    • Go to properties and you can see the path




    • If we moved the project to some other laptop or folder, the file path may get change and it leads to the wrong path 
    • To avoid this issue we have to store the project location in one variable and use this variable while passing the path.


    • The “user.dir”, contains the location of the Project where it is pasted or moved.
    • We can pass the above-created variable like below.






  1.  Download the Chrome Diver from below link
    • https://www.seleniumhq.org/download/

    •           
    • Download the chrome driver which is suitable to OS
    • Once you downloaded the driver just copy it and paste it in our project

                            





  1. è In this, we will separate code into modules

·        we are doing the three things in this program

o   setting the browser

o   Setting the browser Configuration

o   Run test

·        For these, we need to create the three separate methods

o   SetBrowser()

o   SetBrowserConfig()

o   Runtest()

  1. Sample program
    1. package Test;

       

      import org.openqa.selenium.WebDriver;

      import org.openqa.selenium.chrome.ChromeDriver;

      import org.openqa.selenium.firefox.FirefoxDriver;

       

      public class SeleniumTest {

       

             static String Browser;

             static WebDriver Driver;

       

             public static void main(String[] args) {

       

                   SetBrowser();

                   SetBrowserConfig();

                   RunTest();

       

             }

       

             public static void SetBrowser() {

       

                   Browser="FireFox"; // Chrome

       

             }

       

             public static void SetBrowserConfig() {

       

                   String ProjectLocation=System.getProperty("user.dir");

       

                   if(Browser.contains("FireFox"))

                   {

                          System.setProperty("webdriver.gecko.driver", ProjectLocation+"\\lib\\GeckoDriver\\geckodriver.exe");

                          Driver=new FirefoxDriver();

                   }

                   else

                   {

                          System.setProperty("webdriver.chrome.driver", ProjectLocation+"\\lib\\ChromeDriver\\chromedriver.exe");

                          Driver=new ChromeDriver();

                   }

             }

             public static void RunTest() {

       

                   Driver.get("Https://google.com");

                   Driver.quit();

       

             }

       

      }

Selenium Notes

Locators:->

 

Locating elements in Selenium WebDriver is performed with the help of findElement() and findElements() methods provided by WebDriver and WebElement class.

 

identifier =id 

id 

name 

dom = javascriptExpression 

xpath = xpathExpression 

link = textPattern

css = cssSelectorSyntax

 

Most Used Commands

 

 

driver.get("URL") à To navigate to an application.

driver.navigate().to("URL") à Navigate to the URL.

 

element.sendKeys("inputtext") à Enter some text into an input box.

element.clear() à Clear the contents from the input box.

 

select.deselectAll() à Deselect all OPTIONs from the first SELECT on the page

select.selectByVisibleText("some text") à Select the OPTION with the input specified by the user.

 

driver.switchTo().window("windowName") à Move the focus from one window to another.

 

driver.switchTo().frame("frameName") à Swing from frame to frame.

 

driver.switchTo().alert() à Helps in handling alerts.

 

driver.navigate().forward() à To navigate forward.

driver.navigate().back() à To navigate back.

 

driver.close() à Closes the current browser associated with the driver.

 

driver.quit() à Quits the driver and closes all the associated window of that driver.

 driver.refresh() à Refreshes the current page.    


Key Board actions

 

Using the ACTIONS class we can pass the keyboard keys to the program.

è import org.openqa.selenium.interactions.Actions;

è Actions Act=new actions(<driver object name>);

TAB

ENTERà Act.sendKeys(Keys.RETURN).perform();

CTRL+ALT+DELETE

  

MOUSE ACTIONS

MOVE MOUSE

RIGHT-CLICK

DOUBLE CLICK

DRAG AND DROP