【PyTorch深度學習專案實戰100例】—— Python+OpenCV+MediaPipe手勢識別系統 | 第2例
前言
大家好,我是阿光。
本專欄整理了《PyTorch深度學習專案實戰100例》,內包含了各種不同的深度學習專案,包含專案原理以及原始碼,每一個專案例項都附帶有完整的程式碼+資料集。
正在更新中~ ✨
🚨 我的專案環境:
- 平臺:Windows10
- 語言環境:python3.7
- 編譯器:PyCharm
- PyTorch版本:1.8.1
💥 專案專欄:【PyTorch深度學習專案實戰100例】
在這裡插入圖片描述
「安裝所需模組:」
pip install cv2
pip install midiapipe
MediaPipe
MediaPipe 為直播和流媒體提供跨平臺、可定製的機器學習解決方案。
- 端到端加速引擎:內建的快速 ML 推理和處理即使在常見硬體上也能加速
- 一次構建,任意部署:統一解決方案適用於 Android、iOS、桌面/雲、Web 和物聯網
- 即用型解決方案:先進的機器學習解決方案展示了框架的全部功能
- 免費開源:Apache 2.0下的框架和解決方案,完全可擴充套件和可定製
image-20211205181548455
「MediaPipe主要應用:」
- 人臉檢測
- 臉部幾何
- 物體檢測
- 即時物體追蹤
我們首先構建一個Hand物件,然後建立hands和mpDraw兩個物件,分別用於檢測手和繪製手指關鍵點。
「手地標模型:」
image-20211205182136432
mpHands = mp.solutions.hands
hands = mpHands.Hands(args.mode, args.maxHands, args.model_complexity, args.detectionCon, args.trackCon) # 用於檢測手
mpDraw = mp.solutions.drawing_utils # 繪製關鍵點
results = 0
image-20211205182145584
該物件會識別出人手的21個關鍵點部位,如上圖所示,21個關鍵點分別對應人手的不同關節位置,用於定位手的位置。
``` def findHands(img, draw=True): imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) global results results = hands.process(imgRGB)
if results.multi_hand_landmarks: for handLms in results.multi_hand_landmarks: if draw: mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS)
return img ```
該段程式碼用於檢測影象中的手,首先將圖片轉成RGB影象,然後利用hands物件進行識別,然後再使用mpDrwa在人手上繪製關鍵點。
```
獲取關節點位置
def findPosition(img, draw=True): lmLists = []
if results.multi_hand_landmarks: for handLms in results.multi_hand_landmarks: for id, lm in enumerate(handLms.landmark): h, w, c = img.shape cx, cy = int(lm.x * w), int(lm.y * h) lmLists.append([id, cx, cy]) if draw: cv2.circle(img, (cx, cy), 12, (255, 0, 255), cv2.FILLED)
return lmLists ```
如果已經檢測到手部,之後會進行檢測關鍵點位置,將其進行返回,返回的是一個包含21個元素的列表,每個元素由為一個列表,內建有不同關鍵點的相對座標。
``` if len(lmList) != 0: max_list = [lmList[4][2], lmList[8][2], lmList[12][2], lmList[16][2], lmList[20][2]] # 每個手指的尖端部位
count = 0 # 手勢數字結果
# 手勢為4 if max_list[1] < lmList[9][2] and max_list[2] < lmList[9][2] and max_list[3] < lmList[9][2] and max_list[ 4] < \ lmList[9][2] and max_list[0] > lmList[9][2] and max_list[0] > lmList[17][2]: count = 4 # 手勢為3 elif max_list[1] < lmList[9][2] and max_list[2] < lmList[9][2] and max_list[3] < lmList[9][2] and \ lmList[20][ 2] > lmList[9][2]: count = 3 # 手勢為2 elif max_list[1] < lmList[9][2] < lmList[16][2] and max_list[2] < lmList[9][2] < lmList[20][2]: count = 2 # 手勢為1 elif max_list[1] < lmList[9][2] < lmList[16][2] and lmList[20][2] > lmList[9][2] and lmList[12][2] > \ lmList[9][ 2]: count = 1 # 手勢為5 else: count = 5 ```
該段程式碼用於進行手勢識別,按照21個關鍵點的相對位置,判斷此時影象的手勢情況。
image-20211205182825010
完整程式碼
本專案可以使用檔案輸入和攝像頭進行輸入,下面程式碼採用的是檔案輸入,如果需要使用攝像頭作為輸入源,只需要將 cap = cv2.VideoCapture("video/finger3.MP4")
內部引數置為0即可,不過還需要調整一下其它位置,這裡不做過多敘述。
【PyTorch深度學習專案實戰100例】—— Python+OpenCV+MediaPipe手勢識別系統 | 第2例_咕 嘟的部落格-CSDN部落格_python深度學習實戰