前言
大家好,我是阿光。
本专栏整理了《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深度学习实战