人臉介面化 新增

參考 https://blog.csdn.net/a1a1a/article/details/79981788'

markdown 參考 https://blog.csdn.net/a1a1a/article/details/79981788' 原網址的程式碼:

from tkinter import *
import cv2
from PIL import Image,ImageTk

def take_snapshot():
    print("有人给你点赞啦!")


def video_loop():
    success, img = camera.read()  # 从摄像头读取照片
    if success:

        cv2.waitKey(1000)
        cv2image = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA)#转换颜色从BGRRGBA
        current_image = Image.fromarray(cv2image)#将图像转换成Image对象
        imgtk = ImageTk.PhotoImage(image=current_image)
        panel.imgtk = imgtk
        panel.config(image=imgtk)
        root.after(1, video_loop)

camera = cv2.VideoCapture(0)    #摄像头
root = Tk()
root.title("opencv + tkinter")
#root.protocol('WM_DELETE_WINDOW', detector)

panel = Label(root)  # initialize image panel
panel.pack(padx=10, pady=10)
root.config(cursor="arrow")
btn = Button(root, text="点赞!", command=take_snapshot)
btn.pack(fill="both", expand=True, padx=10, pady=10)

video_loop()
root.mainloop()

# 当一切都完成后,关闭摄像头并释放所占资源

camera.release()
cv2.destroyAllWindows()

作者:荣轩浩 来源:CSDN 原文:https://blog.csdn.net/a1a1a/article/details/79981788 版权声明:本文为博主原创文章,转载请附上博文链接!

加以修改後

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

"""
Created on Fri May 10 17:34:03 2019
@author: User
"""

from tkinter import *
import cv2
from PIL import Image,ImageTk
import tkinter as tk  # 使用Tkinter前需要先匯入
import tkinter.messagebox  # 要使用messagebox先要匯入模組
import time

global i
i=0

def take_snapshot():
    success, img = camera.read()  # 从摄像头读取照片
    print("拍照")
    global i
    cv2.imwrite('photo/BB/'+'photo_'+str(i)+'.jpg',img)
    i=i+1

def video_loop():
    success, img = camera.read()  # 从摄像头读取照片
    if success:
        cv2.waitKey(1000)
        cv2image = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA)#转换颜色从BGRRGBA
        current_image = Image.fromarray(cv2image)#将图像转换成Image对象
        imgtk = ImageTk.PhotoImage(image=current_image)
        panel.imgtk = imgtk
        panel.config(image=imgtk)
        root.after(1, video_loop)

def Recognize():
    print("1111")
    def align_image(img):
        return alignment.align(96, img, alignment.getLargestFaceBoundingBox(img),

                           landmarkIndices=AlignDlib.OUTER_EYES_AND_NOSE)

    def load_metadata1(path):
        metadata1 = []
        for i in os.listdir(path):
            for f in os.listdir(os.path.join(path, i)):
            # Check file extension. Allow only jpg/jpeg' files.
                ext = os.path.splitext(f)[1]
                if ext == '.jpg' or ext == '.jpeg':
                    metadata1.append(IdentityMetadata(path, i, f))
        return np.array(metadata1)
    metadata1 = load_metadata1('photo')

    for i, m in enumerate(metadata1):
        img = load_image(m.image_path())
        img = align_image(img)
        # scale RGB values to interval [0,1]
        img = (img / 255.).astype(np.float32)
        # obtain embedding vector for image
        embedded[i] = nn4_small2_pretrained.predict(np.expand_dims(img, axis=0))[0]

    def distance(emb1, emb2):
        return np.sum(np.square(emb1 - emb2))

    def show_pair(idx1, idx2): 
        x=str(distance(embedded[idx1], embedded[idx2]))
        print(x)
    def load_image1(path):
        img1 = cv2.imread(path, 1)

    # OpenCV loads images with color channels
    # in BGR order. So we need to reverse them

        return img1[...,::-1]

    #embedded = np.zeros((metadata1.shape[0], 128))
    import warnings
    # Suppress LabelEncoder warning
    warnings.filterwarnings('ignore')

    example_idx = i
    example_image = load_image1(metadata1[example_idx].image_path())
    example_prediction = svc.predict([embedded[example_idx]])
    show_pair(example_prediction,example_idx)
    example_identity = encoder.inverse_transform(example_prediction)[0]

    plt.imshow(example_image)
    plt.title(f'Recognized as {example_identity}');
    localtime = time.asctime( time.localtime(time.time()) )

    f = open('A.txt', 'a', encoding = 'UTF-8')
    f.write(f'時間 :  {localtime}   ')
    f.write(f'Recognized as {example_identity}')
    f.write('\n')
    f.close()
    f.close()
    tkinter.messagebox.showinfo(title='Hi', message=f'Recognized as {example_identity}')   # 提示資訊對話窗


#############################################################################

camera = cv2.VideoCapture(0) 
root = Tk()
root.title("Face Recognition")

#root.protocol('WM_DELETE_WINDOW', detector)
panel = Label(root)  # initialize image panel
panel.pack(padx=10, pady=10)
root.config(cursor="arrow")


def combine_funcs(*funcs):
    def combined_func(*args, **kwargs):
        for f in funcs:
            f(*args, **kwargs)
    return combined_func

btn = Button(root, text="辨識", command=combine_funcs(take_snapshot, Recognize))
btn.pack(fill="both", expand=True, padx=10, pady=10)

video_loop()
root.mainloop()
camera.release()
cv2.destroyAllWindows()

==================================================================

原先設計拍照一個按鈕,辨識也是一個按鈕,這樣方便測試,後續已完成後合併成一個按鈕,程式碼的部分參考

https://codeday.me/bug/20180830/229722.html

def combine_funcs(*funcs):
    def combined_func(*args, **kwargs):
        for f in funcs:
            f(*args, **kwargs)
    return combined_func
self.testButton = Button(self, text = "test", 
                         command = combine_funcs(func1, func2))

另外介面化在python,這裡是用tk來做。

留言