施勢帆老師的教學網站

 找回密碼
 立即註冊
搜索
熱搜: 活動 交友 discuz
查看: 13|回復: 0

辨識微笑,拍照儲存

[複製鏈接]

706

主題

717

帖子

3406

積分

管理員

Rank: 9Rank: 9Rank: 9

積分
3406
發表於 3 天前 | 顯示全部樓層 |閱讀模式
import cv2
from deepface import DeepFace
import numpy as np
from PIL import ImageFont, ImageDraw, Image

# 定義該情緒的中文字
text_obj={
    'angry': '生氣',
    'disgust': '噁心',
    'fear': '害怕',
    'happy': '開心',
    'sad': '難過',
    'surprise': '驚訝',
    'neutral': '正常'
}

# 定義加入文字函式
def putText(x,y,text,size=50,color=(255,255,255)):
    global img
    fontpath = 'NotoSansTC-Regular.ttf'            # 字型
    font = ImageFont.truetype(fontpath, size)      # 定義字型與文字大小
    imgPil = Image.fromarray(img)                  # 轉換成 PIL 影像物件
    draw = ImageDraw.Draw(imgPil)                  # 定義繪圖物件
    draw.text((x, y), text_obj[text], fill=color, font=font) # 加入文字
    img = np.array(imgPil)                         # 轉換成 np.array

cap = cv2.VideoCapture(0)

if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    ret, frame = cap.read()
    if not ret:
        print("Cannot receive frame")
        break
    img = cv2.resize(frame,(384,240))
    try:
        analyze = DeepFace.analyze(img, actions=['emotion'])
        emotion = analyze[0]['dominant_emotion']  # 取得情緒文字
        putText(0,40,emotion)                  # 放入文字
        if emotion == 'happy':
            cv2.imwrite('shie1234.jpg', img)   # 存檔
            print('save ok')
    except:
        pass
    cv2.imshow('oxxostudio', img)
    if cv2.waitKey(5) == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

本帖子中包含更多資源

您需要 登錄 才可以下載或查看,沒有帳號?立即註冊

x
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

Archiver|手機版|小黑屋|施勢帆老師的教學網站

GMT+8, 2025-4-19 08:29 , Processed in 0.054892 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回復 返回頂部 返回列表