# fer 模組(python) ## (在colab下執行) ### fer 模組 介紹 1. 模組功能: 偵測圖片中人臉的表情 2. 安裝參考: https://pypi.org/project/fer/ 3. 安裝指令: !pip install fer 4. 官方網站: https://github.com/justinshenk/fer 5. 範例結果所使用的圖片: https://drive.google.com/file/d/1pNdMvBFZ7KtAh5FN4N5CZRecVSVZbzWf/view?usp=sharing 6. 注意事項: - <font color='red' size=5>**必須在GPU下執行**</font> ```python= !pip install fer ```  ### 模組使用方式 1. 匯入 fer 模組 ```python= from fer import FER # 匯入 FER 模組 ``` 2. 使用 FER 模組必須要以 OpenCV 模組讀取圖片, 需匯入OpenCV模組 ```python= import cv2 # 匯入OpenCV模組 ``` 3. OpenCV 以 imread()讀取 圖片案 ```python= image = cv2.imread('angry1.jpg') print(type(image)) print(len(image)) print(image.shape) print(f'image height is: {image.shape[0]}') print(f'image width is: {image.shape[1]}') ```  4. <font color='red'> 在 colab 中要以 OpenCV 顯示圖片 必須 匯入修正colab模組</font> ```python= from google.colab.patches import cv2_imshow cv2_imshow(image)s: {image.shape[1]}') ```  5. 建立 FER 偵測物件<br> <font color='red'> FER偵測物件 = FER(mtcnn=布林值)</font> - mtcnn: True 代表使用 MTCNN的神經網路, 效果較佳, 但是會使用較多的系統資源 - mtcnn: False 代表使用 OpenCV 的 HAAR神經網路 ```python= detector = FER() # 省略mtcnn參數設定,使用預設值 mtcnn=False ``` 6. 使用 FER偵測物件 的 detect_emotions(圖片變數) 來偵測臉部表情<br> 偵測結果串列 = FER偵測物件.detect_emotions(圖片變數) - 偵測結果串列包含 人臉矩形座標及各種表情的機率 - 偵測結果串列包含 7種 表情機率 - angry: 憤怒 - disgust: 厭惡 - fear: 害怕 - happy: 快樂 - sad: 悲傷 - surprise: 驚訝 - neutral: 神經質 ```python= emotions = detector.detect_emotions(image) emotions #print(emotions) ```  ### 讀取圖片中人臉的情緒後顯示完整程式 ```python= from fer import FER # 匯入 FER 模組 import cv2 # 匯入OpenCV模組 detector = FER() # 省略mtcnn參數設定,使用預設值 mtcnn=False image = cv2.imread('angry1.jpg') emotions = detector.detect_emotions(image) # 偵測image的臉部表情 print(emotions) # 顯示偵測結果 print(emotions[0]['box']) print(emotions[0]['emotions']['angry']) ```  ### 直接取得臉部表情 1. 使用 FER偵測物件 的 top_emotions(圖片變數) 來偵測臉部表情機率最高的表情<br> <font color="red">**偵測結果串列 = FER偵測物件<font color="grent">.top_emotions<font color="red">(圖片變數)**<font> <font color="#000000"> - <font color="#000000"> 偵測結果包含 人臉表情機率最高的表情及機率</font> 2. 使用<font color="red">top_emotions()必須注意要寫在 try:...except: 中</font> ```python= # 匯入 FER 模組 from fer import FER # 匯入 openCV 模組 import cv2 # 匯入 cv2_imshow 模組 from google.colab.patches import cv2_imshow IMG_FILES = ["happy1.jpg", "angry1.jpg"] # 依序讀取要偵測表情的圖片 for idx, file in enumerate(IMG_FILES): print(f"目前編號:{idx}\t目前檔名:{file}") # 讀取 file 圖片 img = cv2.imread(file) # 建立 FER()偵測物件 detector = FER(mtcnn=True) # 取得人臉表情機率最高的表情及機率 try: emotions, score = detector.top_emotion(img) print(f"表情為:{emotions}, 機率為:{score}") except: print("未偵測到人臉") ``` 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up