0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Webカメラを使って✋手をリアルタイム認識してみた(MediaPipe + Python)

Posted at

はじめに

この記事では、PythonとMediaPipeを使って、Webカメラのみで手の動きをリアルタイムに認識する方法を紹介します。TouchDesignerやインタラクティブ展示にも応用可能です。


環境

  • OS:Windows 10 / macOS
  • Python:3.10
  • ライブラリ:
    • mediapipe
    • opencv-python

目的

  • Webカメラで手を認識してみたい
  • 関節の位置を取得して可視化・応用したい
  • 展示やパフォーマンスに活かしたい!

実装手順

1. 必要なライブラリのインストール

pip install mediapipe opencv-python

2. コードを書く

import cv2
import mediapipe as mp

# MediaPipeのモジュール初期化
mp_hands = mp.solutions.hands
mp_drawing = mp.solutions.drawing_utils

# Webカメラを開く
cap = cv2.VideoCapture(0)

# MediaPipe Hands 初期化
with mp_hands.Hands(
    max_num_hands=2,
    min_detection_confidence=0.7,
    min_tracking_confidence=0.5
) as hands:

    while cap.isOpened():
        success, image = cap.read()
        if not success:
            print("カメラが読み込めませんでした")
            continue

        # OpenCVはBGR、MediaPipeはRGBなので変換
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        image.flags.writeable = False  # 高速化のために書き込み不可に

        # 手の検出
        results = hands.process(image)

        # 描画のために再びBGRに変換
        image.flags.writeable = True
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

        # ランドマークの描画
        if results.multi_hand_landmarks:
            for hand_landmarks in results.multi_hand_landmarks:
                mp_drawing.draw_landmarks(
                    image,
                    hand_landmarks,
                    mp_hands.HAND_CONNECTIONS
                )

        # ウィンドウ表示
        cv2.imshow('Hand Tracking', image)

        # ESCキーで終了
        if cv2.waitKey(5) & 0xFF == 27:
            break

# 終了処理
cap.release()
cv2.destroyAllWindows()

3.解説

🔹 手の検出について

MediaPipe Handsは、21個の関節をリアルタイムでトラッキングできます。

🔹 ランドマークの意味

例:
• landmark[4]: 親指の先端
• landmark[8]: 人差し指の先端
→ この2点の距離でピンチジェスチャーを検出できます

4.詰まったポイント・注意点

• カメラがうまく動作しない場合、cap = cv2.VideoCapture(1)などに変更
• 処理が重い場合は解像度を下げる、関節の描画を省略するなど調整

5.まとめ

MediaPipeを使うと、シンプルなコードで手の認識ができ、リアルタイム作品の土台としてとても便利です。今後はジェスチャー検出や、外部ソフトとの連携も試してみたいと思います!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?