使用OpenCV和MediaPipe实现姿态识别!

这篇具有很好参考价值的文章主要介绍了使用OpenCV和MediaPipe实现姿态识别!。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

opencv 姿态识别,opencv,python,人工智能,计算机视觉,开发语言

大家好,我是小F~

MediaPipe是一款由Google开发并开源的数据流处理机器学习应用开发框架。

它是一个基于图的数据处理管线,用于构建使用了多种形式的数据源,如视频、音频、传感器数据以及任何时间序列数据。

MediaPipe通过将各个感知模型抽象为模块并将其连接到可维护的图中来解决这些问题。

项目地址:

https://github.com/google/mediapipe

今天小F就给大家介绍一下,如何使用MediaPipe实现姿态识别!

opencv 姿态识别,opencv,python,人工智能,计算机视觉,开发语言

通过这项技术,我们可以结合摄像头,智能识别人的行为,然后做出一些处理。

比如控制电脑音量,俯卧撑计数,坐姿矫正等功能。

/ 01 /

依赖安装

使用的Python版本是3.9.7。

需要安装以下依赖。

mediapipe==0.9.2.1
numpy==1.23.5
opencv-python==4.7.0.72

使用pip命令进行安装,环境配置好后,就可以来看姿态识别的情况了。

有三种,包含全身、脸部、手部的姿态估计。

/ 02 /

全身姿态估计

首先是人体姿态估计,一次只能跟踪一个人。

并且会在人的身体上显示33个对应的坐标点。

具体代码如下。

import os
import time
import cv2 as cv
import mediapipe as mp


class BodyPoseDetect:
    def __init__(self, static_image=False, complexity=1, smooth_lm=True, segmentation=False, smooth_sm=True, detect_conf=0.5, track_conf=0.5):
        self.mp_body = mp.solutions.pose
        self.mp_draw = mp.solutions.drawing_utils
        self.body = self.mp_body.Pose(static_image, complexity, smooth_lm, segmentation, smooth_sm, detect_conf, track_conf)

    def detect_landmarks(self, img, disp=True):
        img_rgb = cv.cvtColor(img, cv.COLOR_BGR2RGB)
        results = self.body.process(img_rgb)
        detected_landmarks = results.pose_landmarks

        if detected_landmarks:
            if disp:
                self.mp_draw.draw_landmarks(img, detected_landmarks, self.mp_body.POSE_CONNECTIONS)
        return detected_landmarks, img

    def get_info(self, detected_landmarks, img_dims):
        lm_list = []
        if not detected_landmarks:
            return lm_list

        height, width = img_dims
        for id, b_landmark in enumerate(detected_landmarks.landmark):
            cord_x, cord_y = int(b_landmark.x * width), int(b_landmark.y * height)
            lm_list.append([id, cord_x, cord_y])

        return lm_list


def main(path, is_image):
    if is_image:
        detector = BodyPoseDetect(static_image=True)
        ori_img = cv.imread(path)

        img = ori_img.copy()
        landmarks, output_img = detector.detect_landmarks(img)
        info_landmarks = detector.get_info(landmarks, img.shape[:2])
        # print(info_landmarks[3])

        cv.imshow("Original", ori_img)
        cv.imshow("Detection", output_img)
        cv.waitKey(0)

    else:
        detector = BodyPoseDetect()
        cap = cv.VideoCapture(path)
        prev_time = time.time()
        cur_time = 0

        frame_width = int(cap.get(3))
        frame_height = int(cap.get(4))
        out = cv.VideoWriter('output.avi', cv.VideoWriter_fourcc('M', 'J', 'P', 'G'), 10, (frame_width, frame_height))  # 保存视频

        while True:
            ret, frame = cap.read()
            if not ret:
                print("Video Over")
                break

            img = frame.copy()
            landmarks, output_img = detector.detect_landmarks(img)
            info_landmarks = detector.get_info(landmarks, img.shape[:2])

            cur_time = time.time()
            fps = 1/(cur_time - prev_time)
            prev_time = cur_time
            cv.putText(output_img, f'FPS: {str(int(fps))}', (10, 70), cv.FONT_HERSHEY_COMPLEX_SMALL, 2, (0, 50, 170), 2)

            cv.namedWindow('Original', cv.WINDOW_NORMAL)  # 窗口大小可设置
            cv.resizeWindow('Original', 580, 330)  # 重设大小
            cv.namedWindow('Detection', cv.WINDOW_NORMAL)  # 窗口大小可设置
            cv.resizeWindow('Detection', 580, 330)  # 重设大小

            out.write(output_img)

            cv.imshow("Original", frame)
            cv.imshow("Detection", output_img)
            if cv.waitKey(1) & 0xFF == ord('q'):
                break

        cap.release()

    cv.destroyAllWindows()


if __name__ == "__main__":

    # is_image = True
    # media_path = '.\\Data\\Images\\running.jpg'
    is_image = False
    media_path = '.\\Data\\Videos\\basketball.mp4'

    if os.path.exists(os.path.join(os.getcwd(), media_path)):
        main(media_path, is_image)
    else:
        print("Invalid Path")

运行代码后,结果如下。

opencv 姿态识别,opencv,python,人工智能,计算机视觉,开发语言

左侧是原图,右侧是检测结果。

其中代码里的is_image参数表示是否为图片或视频

media_path参数则表示的是源文件的地址。

我们还可以看视频的检测效果,具体如下。

opencv 姿态识别,opencv,python,人工智能,计算机视觉,开发语言

效果还不错。

/ 03 /

脸部识别跟踪

第二个是脸部,MediaPipe可以在脸部周围画一个网格来进行检测和跟踪。

具体代码如下。

import os
import time
import argparse
import cv2 as cv
import mediapipe as mp

class FaceDetect:
    def __init__(self, static_image=False, max_faces=1, refine=False, detect_conf=0.5, track_conf=0.5):
        self.draw_utils = mp.solutions.drawing_utils
        self.draw_spec = self.draw_utils.DrawingSpec(color=[0, 255, 0], thickness=1, circle_radius=2)
        self.mp_face_track = mp.solutions.face_mesh
        self.face_track = self.mp_face_track.FaceMesh(static_image, max_faces, refine, detect_conf, track_conf)

    def detect_mesh(self, img, disp=True):
        results = self.face_track.process(img)
        detected_landmarks = results.multi_face_landmarks

        if detected_landmarks:
            if disp:
                for f_landmarks in detected_landmarks:
                    self.draw_utils.draw_landmarks(img, f_landmarks, self.mp_face_track.FACEMESH_CONTOURS, self.draw_spec, self.draw_spec)

        return detected_landmarks, img

    def get_info(self, detected_landmarks, img_dims):
        landmarks_info = []
        img_height, img_width = img_dims
        for _, face in enumerate(detected_landmarks):
            mesh_info = []
            for id, landmarks in enumerate(face.landmark):
                x, y = int(landmarks.x * img_width), int(landmarks.y * img_height)
                mesh_info.append((id, x, y))
            landmarks_info.append(mesh_info)

        return landmarks_info

def main(path, is_image=True):
    print(path)
    if is_image:
        detector = FaceDetect()
        ori_img = cv.imread(path)
        img = ori_img.copy()
        landmarks, output = detector.detect_mesh(img)
        if landmarks:
            mesh_info = detector.get_info(landmarks, img.shape[:2])
            # print(mesh_info)

        cv.imshow("Result", output)
        cv.waitKey(0)

    else:
        detector = FaceDetect(static_image=False)
        cap = cv.VideoCapture(path)
        curr_time = 0
        prev_time = time.time()

        frame_width = int(cap.get(3))
        frame_height = int(cap.get(4))
        out = cv.VideoWriter('output.avi', cv.VideoWriter_fourcc('M', 'J', 'P', 'G'), 10, (frame_width, frame_height))  # 保存视频

        while True:
            ret, frame = cap.read()
            if not ret:
                print("Video Over")
                break

            img = frame.copy()
            landmarks, output = detector.detect_mesh(img)
            if landmarks:
                mesh_info = detector.get_info(landmarks, img.shape[:2])
                # print(len(mesh_info))

            curr_time = time.time()
            fps = 1/(curr_time - prev_time)
            prev_time = curr_time
            cv.putText(output, f'FPS: {str(int(fps))}', (10, 70), cv.FONT_HERSHEY_COMPLEX_SMALL, 2, (0, 50, 170), 2)
            cv.namedWindow('Result', cv.WINDOW_NORMAL)  # 窗口大小可设置
            cv.resizeWindow('Result', 580, 330)  # 重设大小

            out.write(output)

            cv.imshow("Result", output)
            if cv.waitKey(20) & 0xFF == ord('q'):
                break

        cap.release()
    cv.destroyAllWindows()


if __name__ == "__main__":

    # is_image = True
    # media_path = '.\\Data\\Images\\human_2.jpg'
    is_image = False
    media_path = '.\\Data\\Videos\\humans_3.mp4'

    if os.path.exists(os.path.join(os.getcwd(), media_path)):
        main(media_path, is_image)
    else:
        print("Invalid Path")

效果如下。

opencv 姿态识别,opencv,python,人工智能,计算机视觉,开发语言

/ 04 /

手部跟踪识别

最后一个是手部,可以同时跟踪2只手并且在手部显示相应的坐标点。

具体代码如下。

import os
import time
import argparse
import cv2 as cv
import mediapipe as mp

class HandPoseDetect:
    def __init__(self, static_image=False, max_hands=2, complexity=1, detect_conf=0.5, track_conf=0.5):
        self.mp_hands = mp.solutions.hands
        self.mp_draw = mp.solutions.drawing_utils
        self.hands = self.mp_hands.Hands(static_image, max_hands, complexity, detect_conf, track_conf)

    def detect_landmarks(self, img, disp=True):
        img_rgb = cv.cvtColor(img, cv.COLOR_BGR2RGB)
        results = self.hands.process(img_rgb)
        detected_landmarks = results.multi_hand_landmarks

        if detected_landmarks:
            if disp:
                for h_landmark in detected_landmarks:
                    self.mp_draw.draw_landmarks(img, h_landmark, self.mp_hands.HAND_CONNECTIONS)
        return detected_landmarks, img

    def get_info(self, detected_landmarks, img_dims, hand_no=1):
        lm_list = []
        if not detected_landmarks:
            return lm_list

        if hand_no > 2:
            print('[WARNING] Provided hand number is greater than max number 2')
            print('[WARNING] Calculating information for hand 2')
            hand_no = 2
        elif hand_no < 1:
            print('[WARNING] Provided hand number is less than min number 1')
            print('[WARNING] Calculating information for hand 1')

        if len(detected_landmarks) < 2:
            hand_no = 0
        else:
            hand_no -= 1

        height, width = img_dims
        for id, h_landmarks in enumerate(detected_landmarks[hand_no].landmark):
            cord_x, cord_y = int(h_landmarks.x * width), int(h_landmarks.y * height)
            lm_list.append([id, cord_x, cord_y])

        return lm_list

def main(path, is_image=True):
    if is_image:
        detector = HandPoseDetect(static_image=True)
        ori_img = cv.imread(path)

        img = ori_img.copy()
        landmarks, output_img = detector.detect_landmarks(img)
        info_landmarks = detector.get_info(landmarks, img.shape[:2], 2)
        # print(info_landmarks)

        cv.imshow("Landmarks", output_img)
        cv.waitKey(0)

    else:
        detector = HandPoseDetect()
        cap = cv.VideoCapture(path)
        prev_time = time.time()
        cur_time = 0

        frame_width = int(cap.get(3))
        frame_height = int(cap.get(4))
        out = cv.VideoWriter('output.avi', cv.VideoWriter_fourcc('M', 'J', 'P', 'G'), 10, (frame_width, frame_height))  # 保存视频

        while True:
            ret, frame = cap.read()
            if not ret:
                print("Video Over")
                break

            img = frame.copy()
            landmarks, output_img = detector.detect_landmarks(img)
            info_landmarks = detector.get_info(landmarks, img.shape[:2], 2)
            # print(info_landmarks)

            cur_time = time.time()
            fps = 1/(cur_time - prev_time)
            prev_time = cur_time
            cv.putText(output_img, f'FPS: {str(int(fps))}', (10, 70), cv.FONT_HERSHEY_COMPLEX_SMALL, 2, (0, 50, 170), 2)

            cv.namedWindow('Original', cv.WINDOW_NORMAL)  # 窗口大小可设置
            cv.resizeWindow('Original', 580, 330)  # 重设大小
            cv.namedWindow('Detection', cv.WINDOW_NORMAL)  # 窗口大小可设置
            cv.resizeWindow('Detection', 580, 330)  # 重设大小

            out.write(output_img)

            cv.imshow("Detection", output_img)
            cv.imshow("Original", frame)
            if cv.waitKey(1) & 0xFF == ord('q'):
                break

        cap.release()

    cv.destroyAllWindows()


if __name__ == "__main__":
    is_image = False
    media_path = '.\\Data\\Videos\\piano_playing.mp4'

    if os.path.exists(os.path.join(os.getcwd(), media_path)):
        main(media_path, is_image)
    else:
        print("Invalid Path")

结果如下所示。

opencv 姿态识别,opencv,python,人工智能,计算机视觉,开发语言

/ 05 /

总结

以上操作,就是MediaPipe姿态识别的部分内容。

当然我们还可以通过MediaPipe其它的识别功能,来做出有趣的事情。

比如结合摄像头,识别手势动作,控制电脑音量。这个大家都可以自行去学习。

相关文件及代码都已上传,公众号回复【姿态识别】即可获取。

万水千山总是情,点个 👍 行不行

推荐阅读

opencv 姿态识别,opencv,python,人工智能,计算机视觉,开发语言

opencv 姿态识别,opencv,python,人工智能,计算机视觉,开发语言

opencv 姿态识别,opencv,python,人工智能,计算机视觉,开发语言

···  END  ···文章来源地址https://www.toymoban.com/news/detail-673368.html

到了这里,关于使用OpenCV和MediaPipe实现姿态识别!的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 人工智能-OpenCV+Python实现人脸识别(人脸检测)

    在OpenCV中使用Haar特征检测人脸,那么需要使用OpenCV提供的xml文件(级联表)在haarcascades目录下。这张级联表有一个训练好的AdaBoost训练集。首先要采用样本的Haar特征训练分类器,从而得到一个级联的AdaBoost分类器。Haar特征值反映了图像的灰度变化情况。例如:脸部的一些特征

    2024年02月06日
    浏览(81)
  • 树莓派4B Python3.7.3 Opencv+Mediapipe 手指方向识别

    起因: 2023年4月接触树莓派之后,想实现手指方向的实时识别,现有Google的框架Mediapipe可以实现21个手指关键点位置实时识别,去尝试装Mediapipe以及相关依赖库,发现树莓派的源(官方源),一些库比较旧(15年的都有),所以整体思想要装15年 16年的版本,才能适配 系统环境

    2024年02月03日
    浏览(37)
  • [ Python+OpenCV+Mediapipe ] 实现手势控制音量

    目录 一、写在前面 二、本文内容 三、开发环境  四、代码实现 4.1引入所需包 4.2 定义一个类并初始化 4.3 定义绘制一界面并实现音量控制的主方法 五、看一看实际效果吧 六、完整代码 七、小结  八、感谢        本文所用例子为个人学习的小结,如有不足之处请各位多多

    2024年02月22日
    浏览(44)
  • Opencv + MediaPipe -> 手势识别

    一、概述         OpenCV(Open Source Computer Vision Library)是一个跨平台的计算机视觉库,它提供了许多用于图像和视频处理的功能,包括图像和视频的读取、预处理、特征提取、特征匹配、目标检测等。OpenCV是C++编写的,也提供了Python、Java等语言的接口,可以方便地在不同

    2024年02月05日
    浏览(60)
  • 基于opencv-mediapipe的手势识别

    上一篇文章介绍了基于opencv的手势识别,如果大家运行了我的代码,会发现代码中找出手部轮廓的效果不是很理想。当时我在网上找寻解决的办法,刚好找到了mediapip库,然后我就利用opencv和mediapipe这两个库重新进行了手势识别的代码编写。效果还不错,写篇文章记录一下。

    2024年02月09日
    浏览(37)
  • python+opencv+mediapipe实现手势检测上下左右(含完整代码)

    应用场景:ai换脸,根据左右手势选择图片,上下则表示选中。 版本号:python3.7(一开始是3.6,但是mediapipe最低就是3.7 因为网上检测的都不太准,所以我在判断的时候加入了如果70次里55次检测的是左才返回左,测试完之后效果还可以,蛮准的。判断方法想的头都要秃了。 实

    2024年04月11日
    浏览(36)
  • 基于opencv与mediapipe的面部跟踪(人脸检测追踪)python代码实现

            面部跟踪主要是从图像或视频中检测出人脸并输出人脸位置及其大小等有效信息,并在后续帧中继续捕获人脸的位置及其大小等信息,实时跟踪人脸。此技术可用于海关、机场、视频会议、拍照对焦、面部打码等业务场景。(与人脸识别是不同范畴)         本

    2024年01月17日
    浏览(49)
  • 基于opencv与mediapipe的民族舞舞蹈动作识别

    需要项目的请关注、私信 Opencv(Open Source Computer Vision Library)是一个基于开源发行的跨平台计算机视觉库,它实现了图像处理和计算机视觉方面的很多通用算法,已成为计算机视觉领域最有力的研究工具。在这里我们要区分两个概念:图像处理和计算机视觉的区别:图像处理

    2024年02月10日
    浏览(35)
  • Python+OpenCV+OpenPose实现人体姿态估计(人体关键点检测)

    1、人体姿态估计简介 2、人体姿态估计数据集 3、OpenPose库 4、实现原理 5、实现神经网络 6、实现代码 人体姿态估计(Human Posture Estimation),是通过将图片中已检测到的人体关键点正确的联系起来,从而估计人体姿态。 人体关键点通常对应人体上有一定自由度的关节,比如颈、

    2024年02月04日
    浏览(28)
  • 基于mediapipe的姿态识别和简单行为识别

    源码地址: 🚀🚀🚀🚀 其实这部分很简单,直接在windows命令行的环境下 就可以啦 Mediapipe是一个用于构建机器学习管道的框架,用户处理视频、音频等时间序列数据。这个跨平台框架适用于桌面/服务器、Android、ios和各类嵌入式设备。 目前mediapipe包含16个solutions,分别为 总

    2024年02月02日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包