用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - python代码库

人脸识别+拍照 1.0

2022-03-18 作者: mikeKil举报

[python]代码库

from tkinter import messagebox as mes
from PIL import Image
from PIL import ImageTk
import threading
import easygui as gui
import tkinter as tk
import os
import time
import random
import cv2
import base64
import requests

os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (600, 1000)
#鼠标样式列表
#list=["arrow","circle","clock","cross","dotbox","exchange","fleur","heart","man","mouse","pirate","plus","shuttle","sizing","spider","spraycan","star","target","tcross","trek","watch"]

root = tk.Tk()          
root.geometry("700x500")
root.resizable(0, 0)    
root.title("相机 1.0")  
canvas = tk.Canvas(root,bg='lightyellow',height=500,width=700)
canvas.pack()

i = 1
fileList = [] 

def getToken():
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials' \
               '&client_id=zZeG8xxXGQ0L6dvz6K4kqywI&client_secret=zlbT0qtEhcmNFQ54p2FAXcFfu1tELGtM'
    response = requests.get(host)
    content = response.json()
    content = content['access_token']
    return content

def getData(imgUrl):    #获取人脸识别数据
    requestUrl = 'https://aip.baidubce.com/rest/2.0/face/v3/detect'
    token = getToken()
    params = {'access_token': token}
    f = open(imgUrl, 'rb')
    temp = f.read()
    image = base64.b64encode(temp)
    data = {
        'image':image,
        'image_type':'BASE64',
        'face_field':'age,gender,face_shape'
    }
    try:
        response = requests.post(requestUrl, params=params, data=data)
        content = response.json()
        age = content['result']['face_list'][0]['age']  # 人脸得分
        gender = content['result']['face_list'][0]['gender']['type']
        shape = content['result']['face_list'][0]['face_shape']['type']
        if gender == 'male':gender='男'
        else:gender='女'
        if shape == 'square':shape = '国字脸'
        elif shape == 'triangle':shape = '瓜子脸'
        elif shape == 'oval':shape = '鹅蛋脸'
        elif shape == 'heart':shape = '心形脸'
        else:shape = '圆形脸'
        gui.msgbox("性别:"+gender+"\n年龄:"+str(age)+"\n脸型:"+shape,"识别成功")
    except:
        mes.showerror("错误", "-未识别到人脸-")

def video_demo():
    global t
    try:
        def cc():
            global ret, frame
            capture = cv2.VideoCapture(0)
            while True:
                ret, frame = capture.read()
                frame = cv2.flip(frame, 1)
                cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
                img = Image.fromarray(cv2image)
                image_file=ImageTk.PhotoImage(img)
                canvas.create_image(25,80,anchor='nw',image=image_file)
        t=threading.Thread(target=cc)
        t.start()
    except:
        mes.showerror("错误", "摄像头已打开")
    
def takePhoto_data():
    try:
        output_dir = './'
        path = "photo.jpg"
        output_path = os.path.join(output_dir,path)
        cv2.imwrite(output_path, frame)
        #调用getData方法,获取人脸数据
        getData(output_path)
        os.remove(output_path)
    except:
        mes.showerror("错误", "摄像头尚未打开")

def takePhoto():
    global i
    output_dir = './'
    a=mes.askquestion('提示', '确定将图片存放于此路径?\n' + output_dir)
    if a == "yes":
        path = "%d.jpg" % i
        while os.path.exists(path):
            i += 1
            path = "%d.jpg" % i
        output_path = os.path.join(output_dir,path)
        cv2.imwrite(output_path, frame)
        i += 1
    else:
        path = gui.enterbox("请输入你要保存的文件路径:(文件名自带)")
        try:
            path_name = "%d.jpg" % i
            while os.path.exists(path_name):
                i += 1
                path = "%d.jpg" % i
            output_path = os.path.join(path,path_name)
            cv2.imwrite(output_path, frame)
            i += 1
        except:
            mes.showerror("错误", "该文件路径无效")
            
def closeVideo():
    try:
        global root
        root.destroy()
    except:
        mes.showerror("错误", "摄像头已关闭")

tk.Button(root,text="   打开摄像头   ",bg='lightgreen',cursor="hand2",command=video_demo).place(relx=0.06,rely=0.06)
tk.Button(root,text="   拍照   ",bg='lightgreen',cursor="hand2",command=takePhoto).place(relx=0.3,rely=0.06)
tk.Button(root,text="   人脸识别   ",bg='lightgreen',cursor="hand2",command=takePhoto_data).place(relx=0.54,rely=0.06)
tk.Button(root,text="   关闭摄像头   ",bg='lightgreen',cursor="hand2",command=closeVideo).place(relx=0.78,rely=0.06)

root.mainloop()


网友评论    (发表评论)

共2 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...