---
# System prepended metadata

title: '*2022/06/06 影像處理 期末報告*'
tags: [影像處理]

---

###### tags: `影像處理`
# *2022/06/06 影像處理 期末報告*


## mian.py:
```
import module_Unlock as MU #導入解鎖模組
import winsound #導入Windows內建音效撥放模組
filename_1 = './WelcomeVoice.wav' #設定解鎖成功音效
filename_2 = './ErrorVoice.wav' #設定解鎖失敗音效
UnlockCheck = MU.Unlocker() #呼叫模組方程式進行解鎖，解鎖成功會回傳1

if UnlockCheck==1: #解鎖成功
    print("\n-------------------------------------------")
    print("Unclock Successful! Enjoy!")
    winsound.PlaySound(filename_1, winsound.SND_FILENAME) #播放解鎖成功音效
else:
    print("\n-------------------------------------------")
    print("You are not match person")
    winsound.PlaySound(filename_2, winsound.SND_FILENAME) #播放解鎖失敗音效

print("\n-------------------------------------------")
print("Thank You!")
print("Invite you to participate in feedback activity sincerely!")

```
## module_Unlock.py:
```
import module_Record as MR #導入建模模組
import cv2
import numpy as np
import time

#解鎖引導程式
def Unlocker():
    print("Welcome to use Unlocker")
    print("Protect Your file by FaceID")
    print("Support Mask wearing\n")
    print("-------------------------------------------")
    print("Please enter your Name:", end='')
    Name = input()#取得使用者名字(建議使用英文)
    CheckNumber_Without = 1#設定沒有口罩的驗證flag為1，方便不用每次都要重新建模
    CheckNumber_With = 1#同理
    PassNumber = 0#解鎖成功flag，預設為0
    num_of_secs = 5#關閉視窗秒數
    while True:
        print("-------------------------------------------")
        print("Options:")
        print("1.Record Face without Mask")
        print("2.Record Face with Mask")
        print("3.Unlock Progress")
        print("4.Quick")
        Selection = int(input("Select one options: "))#取得使用者選擇
        if Selection == 1:
            CheckNumber_Without = Build_Module_Without_Mask()#呼叫建模函式

        elif Selection == 2:
            CheckNumber_With = Build_Module_With_Mask()#呼叫模組建模

        elif Selection == 3:
            print("\n-------------------------------------------")
            print("Preparing......")
            if CheckNumber_With == 0 or CheckNumber_Without == 0:#確認是否已建模
                print("You can't Unlock because you haven't create a module")
                break
            else:#已經建模了
            
                # Training產生YML檔
                detector = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')  # import the OpenCV Model of face
                recog = cv2.face.LBPHFaceRecognizer_create()  # Open Training method
                faces = []  # Store face
                ids = []  # Store id

                for i in range(1, 13):
                    img = cv2.imread(f'./Model_No_Mask/Model_No_Mask{i}.jpg')  #依序開啟每一張照片
                    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  #色彩轉換成黑白
                    img_np = np.array(gray, 'uint8')  
                    face = detector.detectMultiScale(gray)  #擷取人臉區域
                    for (x, y, w, h) in face:
                        faces.append(img_np[y:y + h, x:x + w])  #記錄人臉的位置和大小內像素的數值
                        ids.append(1)  #記錄人臉對應的 id，只能是整數，都是 1 表示人臉的 id 為 1

                for i in range(1, 13):
                    img = cv2.imread(f'./Model_Wearing_Mask/Model_Wearing_Mask{i}.jpg')  #依序開啟每一張照片
                    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  #色彩轉換成黑白
                    img_np = np.array(gray, 'uint8')  
                    face = detector.detectMultiScale(gray)  #擷取人臉區域
                    for (x, y, w, h) in face:
                        faces.append(img_np[y:y + h, x:x + w])  #記錄人臉的位置和大小內像素的數值
                        ids.append(2)#記錄人臉對應的 id，只能是整數，都是 2表示人臉的 id 為 2
                recog.train(faces, np.array(ids))  # 開始訓練
                recog.save('face.yml')#生成YML檔案

                # Recognize the face
                recognizer = cv2.face.LBPHFaceRecognizer_create()  #啟用訓練人臉模型方法
                recognizer.read('./face.yml')  # 讀取人臉模型YML檔
                cascade_path = "./haarcascade_frontalface_default.xml"  #載入人臉追蹤模型
                face_cascade = cv2.CascadeClassifier(cascade_path)  #啟用人臉追蹤

                cap = cv2.VideoCapture(0)  #開啟攝影機
                if not cap.isOpened():
                    print("Camera Open Failure")#攝影機開啟失敗
                    exit()
                while True:
                    ret, img = cap.read()
                    if not ret:
                        print("Cannot receive frame")
                        break
                    img = cv2.resize(img, (640, 480))  #預設尺寸為680*480
                    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  #轉換成黑白
                    faces = face_cascade.detectMultiScale(gray)  #追蹤人臉 (目的在於標記出外框 )

                    # 建立姓名和 id 的對照表
                    name = {
                        '1': Name,
                        '2': Name + str("_Mask")
                    }
                    for (x, y, w, h) in faces:
                        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)  #標記人臉外框
                        idnum, confidence = recognizer.predict(gray[y:y + h, x:x + w])  #取出 id 號碼以及信心指數 confidence
                        if confidence < 50:
                            text = name[str(idnum)]  # 如果信心指數小於 50，取得對應的名字
                            print("Check Finished")
                            PassNumber = 1#將解鎖成功flag設為1
                            print("The Windows Will close in 5 seconds")
                            while num_of_secs:
                                print(num_of_secs, end=' ')
                                time.sleep(1)
                                num_of_secs -= 1
                            print("\n")
                            break
                        else:
                            text = 'Unrecognize'  # 不然就是Unrecognize
                        # 在人臉外框旁加上名字
                        cv2.putText(img, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)

                    if PassNumber == 1:
                        return PassNumber#回傳解鎖成功的訊號回主程式
                        break

                    cv2.imshow('Recognize Window', img)
                    if cv2.waitKey(5) == ord('q'):#按下 q 鍵停止解鎖
                        print("Unlock Unseccessful")
                        PassNumber=0#將解鎖成功flag設為0，表示失敗
                        return PassNumber#回傳解鎖失敗的訊號回主程式
                        break  
                cap.release()
                cv2.destroyAllWindows()#關閉所有視窗

        elif Selection == 4:
            break
    return PassNumber#將解鎖成功flag預設的0回傳，表示失敗(沒有經過解鎖認證)

def Build_Module_Without_Mask():
    print("-------------------------------------------")
    print("Please Press 'S' to Shot")#按下S表示拍照建模
    print("We Will Shot for 12 times")#取得12個角度的人臉模型
    print("Press 'Q' to Quick Building")#按下Q表示放棄建模
    print("Preparing.......")
    CheckNumber_Without = MR.FaceRecordWithoutMask()  # Call Module to Record a Face and set a flag to check whether successful
    # Check the Model whether build successfully
    while True:
        if (CheckNumber_Without == 1):#建模成功
            break
        else:#建模失敗
            print("Build Fail")
            print("Please try again")
            print("Preparing......")
            CheckNumber_Without = MR.FaceRecordWithoutMask()#重新再建模
    return CheckNumber_Without#CheckNumber_Without=1表示建模成功，否則失敗

def Build_Module_With_Mask():
    print("-------------------------------------------")
    print("Please Press 'S' to Shot")
    print("We Will Shot for 12 times")
    print("Press 'Q' to Quick Building")
    print("Preparing.......")
    CheckNumber_With = MR.FaceRecordWithMask()  # Call Module to Record a Face and set a flag to check whether successful
    while True:
        if (CheckNumber_With == 1):
            break
        else:
            print("Build Fail")
            print("Please try again")
            print("Preparing......")
            CheckNumber_With = MR.FaceRecordWithoutMask()
    return CheckNumber_With#CheckNumber_With=1表示建模成功，否則失敗

```
## module_Record.py
```
import cv2

#Block_01
#Record the Face Without Mask
def FaceRecordWithoutMask():
    cap = cv2.VideoCapture(0)  # 建立一個 VideoCapture 物件
    num = 1  # 遞增，用來儲存檔名
    CheckNumber = 1
    while (cap.isOpened()):  # 迴圈讀取每一幀
        ret_flag, Vshow = cap.read()  # 返回兩個引數，第一個是bool是否正常開啟，第二個是照片陣列
        cv2.imshow("Model_No_Mask", Vshow)  # 視窗顯示，顯示名為 Model_No_Mask
        k = cv2.waitKey(1) & 0xFF  # 每幀資料延時 1ms，延時不能為 0，否則讀取的結果會是靜態幀
        if k == ord('s') :  # 若檢測到按鍵 ‘s’，列印字串
            cv2.imwrite("./Model_No_Mask/" +"Model_No_Mask"+ str(num) + ".jpg", Vshow)
            print("Success to save " +"Model_No_Mask"+ str(num) + ".jpg")
            print("-------------------------")
            num = num+1
            CheckNumber = 1
        elif k == ord('q'):  # 若檢測到按鍵 ‘q’，退出
            CheckNumber = 0
            break
        elif num==13:
            print("Model Build Successfully")
            break
    cap.release()  # 釋放攝像頭
    cv2.destroyAllWindows()  # 刪除建立的全部視窗

    return CheckNumber

#Block_02
#Record the Face With Mask
def FaceRecordWithMask():
    cap = cv2.VideoCapture(0)  # 建立一個 VideoCapture 物件
    num = 1  # 遞增，用來儲存檔名
    CheckNumber = 1
    while (cap.isOpened()):  # 迴圈讀取每一幀
        ret_flag, Vshow = cap.read()  # 返回兩個引數，第一個是bool是否正常開啟，第二個是照片陣列，如果只設定一個則變成一個tumple包含bool和圖片
        cv2.imshow("Model_Wearing_Mask", Vshow)  # 視窗顯示，顯示名為 Capture_Test
        k = cv2.waitKey(1) & 0xFF  # 每幀資料延時 1ms，延時不能為 0，否則讀取的結果會是靜態幀
        if k == ord('s') :  # 若檢測到按鍵 ‘s’，列印字串
            cv2.imwrite("./Model_Wearing_Mask/" +"Model_Wearing_Mask"+ str(num) + ".jpg", Vshow)
            print("Success to save " +"Model_Wearing_Mask"+ str(num) + ".jpg")
            print("-------------------------")
            num = num+1
            CheckNumber = 1
        elif k == ord('q'):  # 若檢測到按鍵 ‘q’，退出
            CheckNumber = 0
            break
        elif num==13:
            print("Model Build Successfully")
            break
    cap.release()  # 釋放攝像頭
    cv2.destroyAllWindows()  # 刪除建立的全部視窗

    return CheckNumber
```
## module_AutoBox.py
```
from selenium import webdriver
import click as click

driver = webdriver.Chrome('./chromedriver')
driver.get('https://sso.tku.edu.tw/NEAI/logineb.jsp?myurl=https://sso.tku.edu.tw/aissinfo/emis/tmw0012.aspx') # 開啟淡江大學成績查看頁面登入視窗

def login():
    # Login information
    # StudentID
    # 利用HTML語法中的id抓取學號輸入格
    account = driver.find_element_by_xpath("//*[@id=\"username\"]")

    account.clear()
    account.send_keys("學號")

    # StudentPassword
    # 利用HTML語法中的id抓取密碼輸入格
    password = driver.find_element_by_xpath("//*[@id=\"password\"]")
    password.clear()
    password.send_keys("密碼")

    # Login
    # 利用HTML語法中的id抓取登入鍵並按下
    driver.find_element_by_xpath("//*[@id=\"loginbtn\"]").click()

    # ShowGrade
    # 利用HTML語法中的id抓取成績選項
    driver.find_element_by_xpath("//*[@href=\"TMWS030.aspx\"]").click()

    return 0

```