文章目錄
- 前言
- 前期準備
- 識別手部模型
- 識別視頻輸入方法
- 手勢識別方法
- 完整代碼
- 結語
前言
人工智能的浪潮正在席卷全球,一個已經被談論了幾十年的概念,如今這幾年,相關技術的發展速度越來越快,機器學習、深度學習、計算機視覺等名詞逐漸走進人們的生活,它們同屬于人工智能的范疇之中,
計算機視覺是人工智能領域的一個分支計算機視覺實際上是一個跨領域的交叉學科,包括計算機科學,數學,工程學,物理學,生物學和心理學等領域,許多科學家認為,計算機視覺為人工智能的發展開拓了道路,
簡單來說,計算機視覺就是賦予計算機一雙觀察世界的眼睛,再使用計算機優秀的大腦快速的計算,服務人類,
今天我們將深入淺出,簡單介紹Python計算機視覺中的手勢識別方法,識別手勢——數字(一、二、三、四、五和大拇指的贊賞),如果你喜歡本篇文章或對你有幫助的話,別忘了點贊+關注噢!
前期準備
本篇我們將會用到Python的OpenCV模塊和手部模型模塊mediapipe,在Python的pip安裝方法中,安裝方法如下:
opencv是常用的影像識別模塊
mediapipe是谷歌開發并開源的多媒體機器學習模型應用框架,
pip install opencv-python
pip install mediapipe
如果你的電腦裝有Anaconda,建議選擇在Anaconda的環境命令列中進行相應模塊的安裝,以此構建更具體的機器學習環境
當你安裝好OpenCV和mediapipe模塊以后,你可以在Python代碼中寫入
import cv2
import mediapipe as mp
如果運行成功,那么你的Opencv-python模塊即為安裝成功,那么我們現在就開始進入今天的正題吧!
識別手部模型
既然要做手勢識別,那么就要去找到我們傳入影像的手部資訊,本處我們將使用mediapipe模型去找到手部模型,并完成手部模型的識別模塊,并命名,我們將在后續手勢識別內容中將其作為模塊引入
HandTrackingModule.py
# -*- coding:utf-8 -*-
"""
CODE >>> SINCE IN CAIXYPROMISE.
MOTTO >>> STRIVE FOR EXCELLENT.
CONSTANTLY STRIVING FOR SELF-IMPROVEMENT.
@ By: CaixyPromise
@ Date: 2021-10-17
"""
import cv2
import mediapipe as mp
class HandDetector:
"""
使用mediapipe庫查找手,匯出地標像素格式,添加了額外的功能,
如查找方式,許多手指向上或兩個手指之間的距離,而且提供找到的手的邊界框資訊,
"""
def __init__(self, mode=False, maxHands=2, detectionCon=0.5, minTrackCon=0.5):
"""
:param mode: 在靜態模式下,對每個影像進行檢測
:param maxHands: 要檢測的最大手數
:param detectionCon: 最小檢測置信度
:param minTrackCon: 最小跟蹤置信度
"""
self.mode = mode
self.maxHands = maxHands
self.detectionCon = detectionCon
self.minTrackCon = minTrackCon
self.mpHands = mp.solutions.hands
self.hands = self.mpHands.Hands(self.mode, self.maxHands,
self.detectionCon, self.minTrackCon)
self.mpDraw = mp.solutions.drawing_utils
self.tipIds = [4, 8, 12, 16, 20]
self.fingers = []
self.lmList = []
def findHands(self, img, draw=True):
"""
從影像(BRG)中找到手部,
:param img: 用于查找手的影像,
:param draw: 在影像上繪制輸出的標志,
:return: 帶或不帶圖形的影像
"""
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 將傳入的影像由BGR模式轉標準的Opencv模式——RGB模式,
self.results = self.hands.process(imgRGB)
if self.results.multi_hand_landmarks:
for handLms in self.results.multi_hand_landmarks:
if draw:
self.mpDraw.draw_landmarks(img, handLms,
self.mpHands.HAND_CONNECTIONS)
return img
def findPosition(self, img, handNo=0, draw=True):
"""
查找單手的地標并將其放入串列中像素格式,還可以回傳手部周圍的邊界框,
:param img: 要查找的主影像
:param handNo: 如果檢測到多只手,則為手部id
:param draw: 在影像上繪制輸出的標志,(默認繪制矩形框)
:return: 像素格式的手部關節位置串列;手部邊界框
"""
xList = []
yList = []
bbox = []
bboxInfo =[]
self.lmList = []
if self.results.multi_hand_landmarks:
myHand = self.results.multi_hand_landmarks[handNo]
for id, lm in enumerate(myHand.landmark):
h, w, c = img.shape
px, py = int(lm.x * w), int(lm.y * h)
xList.append(px)
yList.append(py)
self.lmList.append([px, py])
if draw:
cv2.circle(img, (px, py), 5, (255, 0, 255), cv2.FILLED)
xmin, xmax = min(xList), max(xList)
ymin, ymax = min(yList), max(yList)
boxW, boxH = xmax - xmin, ymax - ymin
bbox = xmin, ymin, boxW, boxH
cx, cy = bbox[0] + (bbox[2] // 2), \
bbox[1] + (bbox[3] // 2)
bboxInfo = {"id": id, "bbox": bbox,"center": (cx, cy)}
if draw:
cv2.rectangle(img, (bbox[0] - 20, bbox[1] - 20),
(bbox[0] + bbox[2] + 20, bbox[1] + bbox[3] + 20),
(0, 255, 0), 2)
return self.lmList, bboxInfo
def fingersUp(self):
"""
查找串列中打開并回傳的手指數,會分別考慮左手和右手
:return:豎起手指的陣列(串列),陣列長度為5,
其中,由大拇指開始數,立起標為1,放下為0,
"""
if self.results.multi_hand_landmarks:
myHandType = self.handType()
fingers = []
# Thumb
if myHandType == "Right":
if self.lmList[self.tipIds[0]][0] > self.lmList[self.tipIds[0] - 1][0]:
fingers.append(1)
else:
fingers.append(0)
else:
if self.lmList[self.tipIds[0]][0] < self.lmList[self.tipIds[0] - 1][0]:
fingers.append(1)
else:
fingers.append(0)
# 4 Fingers
for id in range(1, 5):
if self.lmList[self.tipIds[id]][1] < self.lmList[self.tipIds[id] - 2][1]:
fingers.append(1)
else:
fingers.append(0)
return fingers
def handType(self):
"""
檢查傳入的手部是左還是右
:return: "Right" 或 "Left"
"""
if self.results.multi_hand_landmarks:
if self.lmList[17][0] < self.lmList[5][0]:
return "Right"
else:
return "Left"
識別視頻輸入方法
完成手部模型的獲取與識別,現在我們就要將內容傳入到計算機當中,使其能進行手部的識別以及手勢的識別,本處我們將使用OpenCV進行內容的輸入流,開啟計算機的攝像頭獲取內容,并使用剛剛我們寫的HandTrackingModule模塊作為手部的識別模塊,
Main.py
# -*- coding:utf-8 -*-
"""
CODE >>> SINCE IN CAIXYPROMISE.
MOTTO >>> STRIVE FOR EXCELLENT.
CONSTANTLY STRIVING FOR SELF-IMPROVEMENT.
@ By: CaixyPromise
@ Date: 2021-10-17
"""
import cv2
from HandTrackingModule import HandDetector
class Main:
def __init__(self):
self.camera = cv2.VideoCapture(0,cv2.CAP_DSHOW) # 以視頻流傳入
self.camera.set(3, 1280) # 設定解析度
self.camera.set(4, 720)
def Gesture_recognition(self):
while True:
self.detector = HandDetector()
frame, img = self.camera.read()
img = self.detector.findHands(img) # 找到你的手部
lmList, bbox = self.detector.findPosition(img) # 獲取你手部的方位
cv2.imshow("camera", img)
if cv2.getWindowProperty('camera', cv2.WND_PROP_VISIBLE) < 1:
break
# 通過關閉按鈕退出程式
cv2.waitKey(1)
# if cv2.waitKey(1) & 0xFF == ord("q"):
# break # 按下q退出
現在,當我們運行程式后,程式會運行你的計算機默認攝像頭,當你露出你的手時,會傳出影像圈住你的手部,并且繪制出你的手部主要關節點,
其中,你的手部主要關節點已經標好序號,你的手部分為了21個關節點,指尖分別為4 8 12 16 20
具體關節分為:

手勢識別方法
通過前面的講解,我們完成了手部獲取與識別、識別內容的輸入,那么我們現在就來開始寫我們的手勢識別方法,這里,我們用到識別模塊里的fingersUp()方法,
找到我們剛剛寫的Main.py檔案(識別內容輸入方法),當我們找到并繪制出我們的手部位置以后,此時的findPosition()方法會得到你的手部具體方位,其中lmList是關節位置方位(type:list),bbox是邊框方位(type:dict),當未識別到內容時兩者均為空,所以,我們只需要寫當陣列中存在資料(非空),進行手指判斷即可,那么我們可以寫成
# -*- coding:utf-8 -*-
"""
CODE >>> SINCE IN CAIXYPROMISE.
MOTTO >>> STRIVE FOR EXCELLENT.
CONSTANTLY STRIVING FOR SELF-IMPROVEMENT.
@ By: CaixyPromise
@ Date: 2021-10-17
"""
def Gesture_recognition(self):
while True:
self.detector = HandDetector()
frame, img = self.camera.read()
img = self.detector.findHands(img)
lmList, bbox = self.detector.findPosition(img)
if lmList:
x1, x2, x3, x4, x5 = self.detector.fingersUp()
上面我們fingersUp()方法談到,fingersUp()方法會傳回從大拇指開始數的長度為5的陣列,立起的手指標記為1,放下標記為0,
本次我們的目的時寫一個識別我們生活常見的數字手勢以及一個贊揚大拇指的手勢,結合我們生活,識別你的手勢可以寫為
# -*- coding:utf-8 -*-
"""
CODE >>> SINCE IN CAIXYPROMISE.
MOTTO >>> STRIVE FOR EXCELLENT.
CONSTANTLY STRIVING FOR SELF-IMPROVEMENT.
@ By: CaixyPromise
@ Date: 2021-10-17
"""
def Gesture_recognition(self):
while True:
self.detector = HandDetector()
frame, img = self.camera.read()
img = self.detector.findHands(img)
lmList, bbox = self.detector.findPosition(img)
if lmList:
x1, x2, x3, x4, x5 = self.detector.fingersUp()
if (x2 == 1 and x3 == 1) and (x4 == 0 and x5 == 0 and x1 == 0):
# TWO
elif (x2 == 1 and x3 == 1 and x4 == 1) and (x1 == 0 and x5 == 0):
# THREE
elif (x2 == 1 and x3 == 1 and x4 == 1 and x5 == 1) and (x1 == 0):
# FOUR
elif x1 == 1 and x2 == 1 and x3 == 1 and x4 == 1 and x5 == 1:
# FIVE
elif x2 == 1 and (x1 == 0, x3 == 0, x4 == 0, x5 == 0):
# ONE
elif x1 and (x2 == 0, x3 == 0, x4 == 0, x5 == 0):
# NICE_GOOD
完成基本的識別以后,我們要把內容表達輸出出來,這里我們結合bbox回傳的手部方框方位,再使用opencv里的putText方法,實作識別結果的輸出,
# -*- coding:utf-8 -*-
"""
CODE >>> SINCE IN CAIXYPROMISE.
MOTTO >>> STRIVE FOR EXCELLENT.
CONSTANTLY STRIVING FOR SELF-IMPROVEMENT.
@ By: CaixyPromise
@ Date: 2021-10-17
"""
def Gesture_recognition(self):
while True:
self.detector = HandDetector()
frame, img = self.camera.read()
img = self.detector.findHands(img)
lmList, bbox = self.detector.findPosition(img)
if lmList:
x_1, y_1 = bbox["bbox"][0], bbox["bbox"][1]
x1, x2, x3, x4, x5 = self.detector.fingersUp()
if (x2 == 1 and x3 == 1) and (x4 == 0 and x5 == 0 and x1 == 0):
cv2.putText(img, "2_TWO", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3,
(0, 0, 255), 3)
elif (x2 == 1 and x3 == 1 and x4 == 1) and (x1 == 0 and x5 == 0):
cv2.putText(img, "3_THREE", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3,
(0, 0, 255), 3)
elif (x2 == 1 and x3 == 1 and x4 == 1 and x5 == 1) and (x1 == 0):
cv2.putText(img, "4_FOUR", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3,
(0, 0, 255), 3)
elif x1 == 1 and x2 == 1 and x3 == 1 and x4 == 1 and x5 == 1:
cv2.putText(img, "5_FIVE", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3,
(0, 0, 255), 3)
elif x2 == 1 and (x1 == 0, x3 == 0, x4 == 0, x5 == 0):
cv2.putText(img, "1_ONE", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3,
(0, 0, 255), 3)
elif x1 and (x2 == 0, x3 == 0, x4 == 0, x5 == 0):
cv2.putText(img, "GOOD!", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3,
(0, 0, 255), 3)
cv2.imshow("camera", img)
if cv2.getWindowProperty('camera', cv2.WND_PROP_VISIBLE) < 1:
break
cv2.waitKey(1)
現在,我們已經完成手勢的識別與結果輸出,我們把完整代碼運行一下,即可驗證出我們的代碼效果,
完整代碼
完整代碼如下
# -*- coding:utf-8 -*-
"""
CODE >>> SINCE IN CAIXYPROMISE.
STRIVE FOR EXCELLENT.
CONSTANTLY STRIVING FOR SELF-IMPROVEMENT.
@ by: caixy
@ date: 2021-10-1
"""
import cv2
from HandTrackingModule import HandDetector
class Main:
def __init__(self):
self.camera = cv2.VideoCapture(0,cv2.CAP_DSHOW)
self.camera.set(3, 1280)
self.camera.set(4, 720)
def Gesture_recognition(self):
while True:
self.detector = HandDetector()
frame, img = self.camera.read()
img = self.detector.findHands(img)
lmList, bbox = self.detector.findPosition(img)
if lmList:
x_1, y_1 = bbox["bbox"][0], bbox["bbox"][1]
x1, x2, x3, x4, x5 = self.detector.fingersUp()
if (x2 == 1 and x3 == 1) and (x4 == 0 and x5 == 0 and x1 == 0):
cv2.putText(img, "2_TWO", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3,
(0, 0, 255), 3)
elif (x2 == 1 and x3 == 1 and x4 == 1) and (x1 == 0 and x5 == 0):
cv2.putText(img, "3_THREE", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3,
(0, 0, 255), 3)
elif (x2 == 1 and x3 == 1 and x4 == 1 and x5 == 1) and (x1 == 0):
cv2.putText(img, "4_FOUR", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3,
(0, 0, 255), 3)
elif x1 == 1 and x2 == 1 and x3 == 1 and x4 == 1 and x5 == 1:
cv2.putText(img, "5_FIVE", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3,
(0, 0, 255), 3)
elif x2 == 1 and (x1 == 0, x3 == 0, x4 == 0, x5 == 0):
cv2.putText(img, "1_ONE", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3,
(0, 0, 255), 3)
elif x1 and (x2 == 0, x3 == 0, x4 == 0, x5 == 0):
cv2.putText(img, "GOOD!", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3,
(0, 0, 255), 3)
cv2.imshow("camera", img)
if cv2.getWindowProperty('camera', cv2.WND_PROP_VISIBLE) < 1:
break
cv2.waitKey(1)
# if cv2.waitKey(1) & 0xFF == ord("q"):
# break
if __name__ == '__main__':
Solution = Main()
Solution.Gesture_recognition()
效果一目了然,計算機成功識別了你的手勢并把內容輸出,快去試試吧!
結語
本篇計算機視覺的手勢識別內容寫完了,這也是本人第一篇關于人工智能類計算機視覺的推文,后續我們也會持續輸出有關于人工智能類的文章,如果本篇寫作有紕漏和錯誤或疑問的地方,還望各位能在評論區指出,讓我們一起共同進步一起學習,
創作不易,如果你覺得這篇文章對你有用的話,別忘了點贊在看+關注噢!
下一篇我們將介紹手勢識別的進階——動態手勢的識別,我們會將文章第一時間發送在微信公眾號:“01編程小屋”當中,別忘了關注我們的公眾號以免錯過了噢!

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/321498.html
標籤:其他
上一篇:物體識別——InceptionV3遷移學習簡單實作步驟
下一篇:快速搭建本地服務器
