Combining two python codes

Hello!!
I’m new here so sorry in advance.
I’m currently using Pycharm.

I have two codes, one is for face recognition and the other is for reading information from the Arduino IDE.

The main idea of the project is that we’re going to read the RFID card and then we’re going to get the serial number and we will see if that serial number is approved or not. if the RFID card is recognized, it would move to face recognition.

Now what I want to do is that after executing the RFID code(if approved), I want it to read and execute the face recognition code.

Below are the codes

Reading from Arduino:


import serial
import time
import pandas as pd


device = 'COM6'
try:
    print("Connecting to device"), device
    arduino = serial.Serial(device, 9600)
except:
    print("Failed to connect on"), device

while True:
    time.sleep(1)

    try:
        data = arduino.readline()
        print(data)

        try:
            if data == b'213 237 169 54\r\n':
                print("Approved")

        except:
            print("no")

    except:
        print("Processing")

Here is the face recognition code:

import cv2
import pickle

face_cascade = cv2.CascadeClassifier('C:/Users/Person/PycharmProjects/pythonProject/cascade/haarcascade_frontalface_default.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("recognizer/training.yml")

labels = {}
with open("labels.pickle", 'rb') as f:
    og_labels = pickle.load(f)
    labels = {v: k for k, v in og_labels.items()}



cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)
    for(x, y, w, h) in faces:
        #print(x, y, w, h)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = frame[y:y+h, x:x+w]

        id_, conf = recognizer.predict(roi_gray)
        if conf>=73 and conf <=100:
           # print(id_)
            print(labels[id_])
            print("face recognized")
            font = cv2.FONT_HERSHEY_SIMPLEX
            name = labels[id_]
            color = (255, 255, 255)
            stroke = 2
            cv2.putText(frame, name, (x, y), font, 1, color, stroke, cv2.LINE_AA)



        img_item = "person.png"
        cv2.imwrite(img_item, roi_gray)

        color = (255, 0, 0)
        stroke = 2
        end_cord_x = x + w
        end_cord_y = y + h
        cv2.rectangle(frame, (x, y), (end_cord_x, end_cord_y), color, stroke )



    cv2.imshow("Video Capture", frame)

    if cv2.waitKey(20) & 0xff == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

I would really appreciate the help.

Then you should write that high level code first:

def check_user(rfid_serial, face_cap):
    ''' Poll a connected serial port `rfid_serial` and a video source `face_cap`.
        Return `True` if both have valid/recognised data, `False` 
        otherwise.
    '''
    if not poll_serial(rfid_serial, b'213 237 169 54\r\n'):
        return False
    if not poll_video(face_cap):
        return False
    return True

This has the advantage that you now know which other bits of code you
need and how you need them to look.

Then similarly write poll_serial() and poll_video(). Each of those
should do a single read-and-check operation. FOr example, the
poll_serial() function would do your arduino.readline() call and
compare it with the expected string (a parameter to the function). It
should not contain a loop. Similarly the poll_video() function
should fetch a single video frame and test it for a face. No loop.

The write your main programme to:

  • open the serial port
  • connect the video source
  • run a loop

The loop then calls check_user() once and exits the loop on success,
otherwise it sleeps for 1 second and tries again.

In fact, because check_user is a test you loop can look a bit like
this:

while not check_user(arduino, cap):
    print("no user recognised")
    sleep(1)
print("user recognised")

Finally, I note you have several “bare excepts”:

try:
    ....
except:
    print("no")

This is very bad. Code may raise exceptions for many reasons, and you
should only catch and handle those you understand. I strongly
recommand:

try:
    ....
except SomeExpectedException as e:
    print("badness!", e)

This (a) handles only a specific exception and (b) reports the
exception. The former mean you don’t conceal unexpected errors
(including Python’s NameError, when you use an unknown name, which will
happen if you misspell a variable name). The latter means you get to see
what the error was.

Anything you don’t catch will escape and produce a nice stack trace,
telling you where the exception occurred and what it was.

Using a bare except hides all this, and generally prevents you writing
correct code.

Cheers,
Cameron Simpson cs@cskk.id.au