1

我正在使用以下代码使用 mediapipe 检测手部地标

import cv2
import mediapipe as mp

mphands = mp.solutions.hands
hands = mphands.Hands()
mp_drawing = mp.solutions.drawing_utils
cap = cv2.VideoCapture(0)

while True:
    _, frame = cap.read()
    framergb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    result = hands.process(framergb)
    hand_landmarks = result.multi_hand_landmarks
    if hand_landmarks:
        for handLMs in hand_landmarks:
            mp_drawing.draw_landmarks(frame, handLMs, mphands.HAND_CONNECTIONS)
            print("\n\n\n")
    cv2.imshow("Frame", frame)

    cv2.waitKey(1)

我只想要一个围绕检测器返回的所有点的矩形请告诉是否有任何方法可以在 mediapipe 中内置或使用 opencv

4

1 回答 1

1
  1. while循环之前,确定每帧的宽度和高度:
_, frame = cap.read()

h, w, c = frame.shape
  1. 对于每个landLM检测到的,定义最小xy坐标的初始变量,以及最大xy坐标的初始变量。前两个变量稍后将作为矩形的起点,后两个变量将作为矩形的最后一个点:
            x_max = 0
            y_max = 0
            x_min = w
            y_min = h
  1. 循环遍历handLM变量,并找到手的每个点的x和坐标:y
            for lm in handLMs.landmark:
                x, y = int(lm.x * w), int(lm.y * h)
  1. 在检测到新坐标时更新最小值和最大值x以及变量:y
                if x > x_max:
                    x_max = x
                if x < x_min:
                    x_min = x
                if y > y_max:
                    y_max = y
                if y < y_min:
                    y_min = y
  1. 最后,用点绘制矩形:
            cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2)

共:

import cv2
import mediapipe as mp

mphands = mp.solutions.hands
hands = mphands.Hands()
mp_drawing = mp.solutions.drawing_utils
cap = cv2.VideoCapture()

_, frame = cap.read()

h, w, c = frame.shape

while True:
    _, frame = cap.read()
    framergb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    result = hands.process(framergb)
    hand_landmarks = result.multi_hand_landmarks
    if hand_landmarks:
        for handLMs in hand_landmarks:
            x_max = 0
            y_max = 0
            x_min = w
            y_min = h
            for lm in handLMs.landmark:
                x, y = int(lm.x * w), int(lm.y * h)
                if x > x_max:
                    x_max = x
                if x < x_min:
                    x_min = x
                if y > y_max:
                    y_max = y
                if y < y_min:
                    y_min = y
            cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2)
            mp_drawing.draw_landmarks(frame, handLMs, mphands.HAND_CONNECTIONS)
    cv2.imshow("Frame", frame)

    cv2.waitKey(1)
于 2021-03-30T19:31:40.947 回答