利用opencv+openpose实现人体姿态检测,附详细代码。
通过一个偶然机会,我了解到了人体姿态解算,在学习K210之余,我便想着通过opencv实现这个功能,查找了很多资料,发现可以利用opencv+openpose实现,接着我又开始找一些资料,在pycharm上部署。
前言
人体姿态估计的一个有趣应用是 CGI(computer graphic image,一种电影制造技术)应用。如果可以检测出人体姿态,那么图形、风格、特效增强、设备和艺术造型等就可以被加载在人体上。
通过追踪人体姿态的变化,渲染的图形可以在人动的时候“自然”地与人“融合”。姿态估计的一个有趣应用是在交互游戏中追踪人体对象的运动。
比较流行的 Kinect 使用 3D 姿态估计(采用 IR 传感器数据)来追踪人类玩家的运动,从而利用它来渲染虚拟人物的动作。
应用:
用于检测一个人是否摔倒或疾病
用于健身、体育和舞蹈等的自动教学
用于理解全身的肢体语言(如机场跑道信号、交警信号等)
用于增强安保和监控
一、环境配置
pycharm2021.2.2
pycharm是一个很好用的软件,刚开始我们必须要配置相应的环境,当然你使用我主页里那篇模型训练的环境也可以,在你运行的时候系统会提示你缺少了什么环境,并让你安装,你直接安装即可。这里我就不过多的赘述了。
1.导入文件
在pycharm上导入相应的文件后,你可以直接点击运行,系统会提示你缺少了什么环境,缺少什么就安装什么,通过终端使用pip安装即可。
2.具体代码
# To use Inference Engine backend, specify location of plugins: # export LD_LIBRARY_PATH=/opt/intel/deeplearning_deploymenttoolkit/deployment_tools/external/mklml_lnx/lib:$LD_LIBRARY_PATH import cv2 as cv import numpy as np import argparse parser = argparse.ArgumentParser() parser.add_argument('--input', help='Path to image or video. Skip to capture frames from camera') parser.add_argument('--thr', default=0.2, type=float, help='Threshold value for pose parts heat map') parser.add_argument('--width', default=368, type=int, help='Resize input to specific width.') parser.add_argument('--height', default=368, type=int, help='Resize input to specific height.') args = parser.parse_args() BODY_PARTS = { "Nose": 0, "Neck": 1, "RShoulder": 2, "RElbow": 3, "RWrist": 4, "LShoulder": 5, "LElbow": 6, "LWrist": 7, "RHip": 8, "RKnee": 9, "RAnkle": 10, "LHip": 11, "LKnee": 12, "LAnkle": 13, "REye": 14, "LEye": 15, "REar": 16, "LEar": 17, "Background": 18 } POSE_PAIRS = [ ["Neck", "RShoulder"], ["Neck", "LShoulder"], ["RShoulder", "RElbow"], ["RElbow", "RWrist"], ["LShoulder", "LElbow"], ["LElbow", "LWrist"], ["Neck", "RHip"], ["RHip", "RKnee"], ["RKnee", "RAnkle"], ["Neck", "LHip"], ["LHip", "LKnee"], ["LKnee", "LAnkle"], ["Neck", "Nose"], ["Nose", "REye"], ["REye", "REar"], ["Nose", "LEye"], ["LEye", "LEar"] ] inWidth = args.width inHeight = args.height net = cv.dnn.readNetFromTensorflow("graph_opt.pb") cap = cv.VideoCapture(args.input if args.input else 0) while cv.waitKey(1) < 0: hasFrame, frame = cap.read() if not hasFrame: cv.waitKey() break frameWidth = frame.shape[1] frameHeight = frame.shape[0] net.setInput(cv.dnn.blobFromImage(frame, 1.0, (inWidth, inHeight), (127.5, 127.5, 127.5), swapRB=True, crop=False)) out = net.forward() out = out[:, :19, :, :] # MobileNet output [1, 57, -1, -1], we only need the first 19 elements assert(len(BODY_PARTS) == out.shape[1]) points = [] for i in range(len(BODY_PARTS)): # Slice heatmap of corresponging body's part. heatMap = out[0, i, :, :] # Originally, we try to find all the local maximums. To simplify a sample # we just find a global one. However only a single pose at the same time # could be detected this way. _, conf, _, point = cv.minMaxLoc(heatMap) x = (frameWidth * point[0]) / out.shape[3] y = (frameHeight * point[1]) / out.shape[2] # Add a point if it's confidence is higher than threshold. points.append((int(x), int(y)) if conf > args.thr else None) for pair in POSE_PAIRS: partFrom = pair[0] partTo = pair[1] assert(partFrom in BODY_PARTS) assert(partTo in BODY_PARTS) idFrom = BODY_PARTS[partFrom] idTo = BODY_PARTS[partTo] if points[idFrom] and points[idTo]: cv.line(frame, points[idFrom], points[idTo], (0, 255, 0), 3) cv.ellipse(frame, points[idFrom], (3, 3), 0, 0, 360, (0, 0, 255), cv.FILLED) cv.ellipse(frame, points[idTo], (3, 3), 0, 0, 360, (0, 0, 255), cv.FILLED) t, _ = net.getPerfProfile() freq = cv.getTickFrequency() / 1000 cv.putText(frame, '%.2fms' % (t / freq), (10, 20), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0)) cv.imshow('OpenPose using OpenCV', frame)
这里便是主函数的代码。
3.效果展示
这副图片便是识别的效果,帧率还是很不错的。
三、效果优化
这个帧率虽然可以,但是效果属实有点拉跨。教我K210的学长便指导我进行优化改进,这里附上学长的连接(https://blog.csdn.net/hyayq8124spm=1001.2014.3001.5509)
1.具体代码
import cv2 import time import mediapipe as mp from tqdm import tqdm # 导入solution mp_pose = mp.solutions.pose mp_drawing = mp.solutions.drawing_utils pose = mp_pose.Pose(static_image_mode=False, # model_complexity=1, smooth_landmarks=True, # enable_segmentation=True, min_detection_confidence=0.5, min_tracking_confidence=0.5) def process_frame(img): # BGR转RGB img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) results = pose.process(img_RGB) # 可视化 mp_drawing.draw_landmarks(img, results.pose_landmarks, mp_pose.POSE_CONNECTIONS) # look_img(img) # mp_drawing.plot_landmarks(results.pose_world_landmarks, mp_pose.POSE_CONNECTIONS) # # BGR转RGB # img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # # results = hands.process(img_RGB) # if results.multi_hand_landmarks: # 如果有检测到手 # # for hand_idx in range(len(results.multi_hand_landmarks)): # hand_21 = results.multi_hand_landmarks[hand_idx] # mpDraw.draw_landmarks(img, hand_21, mp_hands.HAND_CONNECTIONS) return img cap = cv2.VideoCapture(1) # 打开cap cap.open(0) # 无限循环,直到break被触发 while cap.isOpened(): # 获取画面 success, frame = cap.read() if not success: print('Error') break ## !!!处理帧函数 frame = process_frame(frame) # 展示处理后的三通道图像 cv2.imshow('my_window', frame) if cv2.waitKey(1) in [ord('q'), 27]: break cap.release() cv2.destroyAllWindows()
2.效果展示
总结
到这里这篇文章就结束了,写这篇博客只是单纯记录自己的学习过程。希望看到这篇博客的你,能够更加坚定的学习。胡适说过一句话我觉得特别好,这里分享给大家。
全部0条评论
快来发表一下你的评论吧 !