學(xué)習(xí)目標(biāo)
1、可以識別到人體姿態(tài)關(guān)鍵點
2、可以通過角度識別的方法識別到人體的動作(自定義)
源碼地址:????????
一、mediapipe的安裝
其實這部分很簡單,直接在windows命令行的環(huán)境下
pip install mediepipe
就可以啦
二、使用mediapipe檢測關(guān)鍵點
1、mediapipe的介紹
Mediapipe是一個用于構(gòu)建機器學(xué)習(xí)管道的框架,用戶處理視頻、音頻等時間序列數(shù)據(jù)。這個跨平臺框架適用于桌面/服務(wù)器、Android、ios和各類嵌入式設(shè)備。
目前mediapipe包含16個solutions,分別為
人臉檢測
Face Mesh
虹膜
手
姿態(tài)
人體
人物分割
頭發(fā)分割
目標(biāo)檢測
Box Tracking
instant Motion Tracking
3D目標(biāo)檢測
特征匹配
AutoFlip
MediaSequence
YouTuBe_8M
總的來說,mediapipe是一個很好的庫,可以解決我們處理ML項目中面臨的大部分麻煩,而且很適合做行為識別方向的小伙伴練手使用。
2、使用mediapipe檢測人體
這里僅使用mediapipe關(guān)于人體識別的方法(solution),谷歌官方將這種人體姿態(tài)識別的方法叫做Blazepose。
(0)檢測前的準(zhǔn)備工作
'''導(dǎo)入一些基本的庫'''
import cv2
import mediapipe as mp
import time
from tqdm import tqdm
import numpy as np
from PIL import Image, ImageFont, ImageDraw
# ------------------------------------------------
# mediapipe的初始化
# 這一步是必須的,因為要使用到以下定義的幾個類
# ------------------------------------------------
mp_pose = mp.solutions.pose
mp_drawing = mp.solutions.drawing_utils
pose = mp_pose.Pose(static_image_mode=True)
(1)檢測圖片
def process_frame(img):
start_time = time.time()
h, w = img.shape[0], img.shape[1] # 高和寬
# 調(diào)整字體
tl = round(0.005 * (img.shape[0] + img.shape[1]) / 2) + 1
tf = max(tl-1, 1)
# BRG-->RGB
img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 將RGB圖像輸入模型,獲取 關(guān)鍵點 預(yù)測結(jié)果
results = pose.process(img_RGB)
keypoints = ['' for i in range(33)]
if results.pose_landmarks:
mp_drawing.draw_landmarks(img, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)
for i in range(33):
cx = int(results.pose_landmarks.landmark[i].x * w)
cy = int(results.pose_landmarks.landmark[i].y * h)
keypoints[i] = (cx, cy) # 得到最終的33個關(guān)鍵點
else:
print("NO PERSON")
struction = "NO PERSON"
img = cv2.putText(img, struction, (25, 100), cv2.FONT_HERSHEY_SIMPLEX, 1.25, (255, 255, 0),
6)
end_time = time.time()
process_time = end_time - start_time # 圖片關(guān)鍵點預(yù)測時間
fps = 1 / process_time # 幀率
colors = [[random.randint(0,255) for _ in range(3)] for _ in range(33)]
radius = [random.randint(8,15) for _ in range(33)]
for i in range(33):
cx, cy = keypoints[i]
#if i in range(33):
img = cv2.circle(img, (cx, cy), radius[i], colors[i], -1)
'''str_pose = get_pos(keypoints) #獲取姿態(tài)
cv2.putText(img, "POSE-{}".format(str_pose), (12, 100), cv2.FONT_HERSHEY_TRIPLEX,
tl / 3, (255, 0, 0), thickness=tf)'''
cv2.putText(img, "FPS-{}".format(str(int(fps))), (12, 100), cv2.FONT_HERSHEY_SIMPLEX,
tl/3, (255, 255, 0),thickness=tf)
return img
如果需要執(zhí)行代碼,則在文末的主函數(shù)中使用
if __name__ == '__main__':
# 讀取圖片
img0 = cv2.imread("./data/outImage--20.jpg")
# 因為有中文路徑,所以加上此行
image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), -1)
img = image.copy()
# 檢測關(guān)鍵點,得到的image是檢測過后的圖片
image = process_frame(img)
# 使用matplotlib畫圖
fig, axes = plt.subplots(nrows=1, ncols=2)
axes[0].imshow(img0[:,:,::-1])
axes[0].set_title("原圖")
axes[1].imshow(image[:,:,::-1])
axes[1].set_title("檢測并可視化后的圖片")
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams["axes.unicode_minus"] = False
plt.show()
fig.savefig("./data/out.png")
最后附上檢測效果。
(2)檢測視頻
任何不涉及3D卷積的機器視覺方法,檢測視頻其實就是檢測圖片。因為視頻是由多幀圖片融合得來的。
比如說一個30幀的視頻,那么它的每一秒鐘,就是由30張圖片疊加而成。
將這些分割出的圖片分別進行檢測,最后將檢測的圖片進行融合,得到的就是檢測后的視頻。
有了這個依據(jù),我們就可以把圖片檢測過程寫成一個函數(shù),在視頻的每一幀中調(diào)用這個函數(shù)就可以啦
一般使用opencv庫將視頻分解為圖片幀的形式,示例代碼如下:
def video2image(videoPath="./video/demo1.mp4",
image_dir="./image"):
'''videoPath是視頻路徑, image_dir是圖片保存的文件夾路徑'''
cap = cv2.VideoCapture(videoPath)
frame_count = 0
while(cap.isOpened()):
success,frame = cap.read()
if not success:
break
frame_count += 1
print("視頻總幀數(shù):", frame_count)
cap.release()
cap = cv2.VideoCapture(videoPath)
count = 0
with tqdm(total=frame_count-1) as pbar:
try:
while(cap.isOpened()):
success, frame = cap.read()
if not success:
break
#處理幀
try:
if count % 20 == 0:
cv2.imwrite("{}/outImage--{}.jpg".format(image_dir, count), frame)
except:
print("error")
pass
if success == True:
pbar.update(1)
count+=1
except:
print("中途中斷")
pass
cv2.destroyAllWindows()
cap.release()
print("視頻已經(jīng)處理結(jié)束,進行下一步操作?。?!")
那么落實到本文想要實現(xiàn)的功能上,就可以在視頻分解出的幀后面加上圖片檢測函數(shù)。
代碼如下所示:
def process_video(video_path="./Data.mp4"):
video_flag = False
cap = cv2.VideoCapture(video_path)
out_path = "./out_Data.mp4"
print("視頻開始處理……")
frame_count = 0
while (cap.isOpened()):
success, frame = cap.read()
frame_count += 1
if not success:
break
cap.release()
print("總幀數(shù) = ", frame_count)
cap = cv2.VideoCapture(video_path)
if video_flag == False:
frame_size = cap.get(cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT) #處理圖像的尺寸。
fourcc = cv2.VideoWriter_fourcc(*'mp4v') #保存視頻文件的格式為mp4
fps = cap.get(cv2.CAP_PROP_FPS)
out = cv2.VideoWriter(out_path, fourcc, fps, (int(frame_size[0]),int(frame_size[1])), ) #輸出圖像的句柄
with tqdm(total=frame_count-1) as pbar:
try:
while cap.isOpened():
success, frame = cap.read()
if success:
pbar.update(1)
frame = process_frame(frame) # frame就是視頻截取的幀,process_frame表示對其檢測。
cv2.namedWindow("frame", cv2.WINDOW_NORMAL)
cv2.imshow("frame", frame)
out.write(frame)
if cv2.waitKey(1) == 27:
break
else:
break
except:
print("中途中斷")
pass
cap.release()
cv2.destroyAllWindows()
out.release()
print("視頻已保存至", out_path)
有了視頻的代碼,那么就可以在主函數(shù)中對其進行調(diào)用,可視化效果就不展示了。
三、使用mediapipe-BlazePose檢測自定義簡單行為
1、原理介紹
將Mediapipe用于行為檢測是比較復(fù)雜的一件事;如果這樣做,那么行為檢測的精度就完全取決于Mediapipe關(guān)鍵點的檢測精度。
于是可以根據(jù)下圖中人的關(guān)節(jié)夾角來對人的位姿進行檢測。
如舉手的時候,大臂與水平方向夾角是一定大于0度的。
叉腰的時候,雙手垂下,大臂與小臂的夾角大于60度小于120度
那么這樣就可以完成一些基本動作的分類。
我這里只列出幾種比較簡單的。
(1)舉雙手(2)舉左手(3)舉右手(4)叉腰(5)比三角形
先看一下效果圖
2、實現(xiàn)過程
首先要知道,由坐標(biāo)求得矢量的公式,其實就是兩個坐標(biāo)相減。
那么求兩個矢量之間的夾角公式:
那么到代碼中就是:
v1 = (x1, y1) - (x2, y2)
v2 = (x0, y0) - (x2, y2)
def get_angle(v1, v2):
angle = np.dot(v1, v2) / (np.sqrt(np.sum(v1 * v1)) * np.sqrt(np.sum(v2 * v2)))
angle = np.arccos(angle) / 3.14 * 180
cross = v2[0] * v1[1] - v2[1] * v1[0]
if cross < 0:
angle = - angle
return angle
這樣就可以得到兩個矢量的夾角。
之后,就可以通過夾角對行為進行判斷,這里的規(guī)則是
舉雙手 左手矢量小于0右手矢量夾角大于0
舉左手 左手矢量小于0右手矢量小于0
舉右手 左手矢量大于0右手矢量大于0
比三角形 舉雙手的同時,大臂與小臂的夾角小于120度
正常 左手矢量大于0右手矢量夾角小于0
叉腰 正常情況下,左手肘夾角小于120度,右手肘夾角也小于0
給出的代碼示例如下:
def get_pos(keypoints):
str_pose = ""
# 計算左臂與水平方向的夾角
keypoints = np.array(keypoints)
v1 = keypoints[12] - keypoints[11]
v2 = keypoints[13] - keypoints[11]
angle_left_arm = get_angle(v1, v2)
#計算右臂與水平方向的夾角
v1 = keypoints[11] - keypoints[12]
v2 = keypoints[14] - keypoints[12]
angle_right_arm = get_angle(v1, v2)
#計算左肘的夾角
v1 = keypoints[11] - keypoints[13]
v2 = keypoints[15] - keypoints[13]
angle_left_elow = get_angle(v1, v2)
# 計算右肘的夾角
v1 = keypoints[12] - keypoints[14]
v2 = keypoints[16] - keypoints[14]
angle_right_elow = get_angle(v1, v2)
if angle_left_arm<0 and angle_right_arm<0:
str_pose = "LEFT_UP"
elif angle_left_arm>0 and angle_right_arm>0:
str_pose = "RIGHT_UP"
elif angle_left_arm<0 and angle_right_arm>0:
str_pose = "ALL_HANDS_UP"
if abs(angle_left_elow)<120 and abs(angle_right_elow)<120:
str_pose = "TRIANGLE"
elif angle_left_arm>0 and angle_right_arm<0:
str_pose = "NORMAL"
if abs(angle_left_elow)<120 and abs(angle_right_elow)<120:
str_pose = "AKIMBO"
return str_pose
得到的str_pose就是行為字符串,在process_frame中可以在圖片幀中可視化。
到這里,關(guān)鍵點檢測與簡單行為檢測已經(jīng)全部介紹結(jié)束了,如果實在復(fù)現(xiàn)不成的,可以直接看我代碼倉庫中的源碼
計劃:將在未來的博客里,把基于wxpython的UI設(shè)計與Mediapipe進行融合,實現(xiàn)可視化的交互過程,請持續(xù)關(guān)注。文章來源:http://www.zghlxwxcb.cn/news/detail-786595.html
學(xué)習(xí)之路逆水行舟,加油加油?。?!文章來源地址http://www.zghlxwxcb.cn/news/detail-786595.html
到了這里,關(guān)于基于mediapipe的姿態(tài)識別和簡單行為識別的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!