【目次】
Gitは,バージョン管理システム.ソースコードの管理や複数人での共同に役立つ.
【サイト内の関連ページ】
Windows での Git のインストール: 別ページ »で説明している.
【関連する外部ページ】
Git の公式ページ: https://git-scm.com/
【サイト内の関連ページ】
【関連する外部ページ】
Python の公式ページ: https://www.python.org/
【サイト内の関連ページ】
NVIDIA グラフィックスボードを搭載しているパソコンの場合には, NVIDIA ドライバ, NVIDIA CUDA ツールキット, NVIDIA cuDNN のインストールを行う.
【関連する外部ページ】
コマンドプロンプトを管理者として実行: 別ページ »で説明
PyTorch のページ: https://pytorch.org/index.html
次のコマンドを実行することにより, PyTorch 2.3 (NVIDIA CUDA 11.8 用)がインストールされる. 但し,Anaconda3を使いたい場合には別手順になる.
事前に NVIDIA CUDA のバージョンを確認しておくこと(ここでは,NVIDIA CUDA ツールキット 11.8 が前もってインストール済みであるとする).
PyTorch で,GPU が動作している場合には,「torch.cuda.is_available()」により,True が表示される.
python -m pip install -U --ignore-installed pip python -m pip uninstall -y torch torchvision torchaudio torchtext xformers python -m pip install -U torch torchvision torchaudio numpy --index-url https://download.pytorch.org/whl/cu118 python -c "import torch; print(torch.__version__, torch.cuda.is_available())"
Anaconda3を使いたい場合には, Anaconda プロンプト (Anaconda Prompt) を管理者として実行し, 次のコマンドを実行する. (PyTorch と NVIDIA CUDA との連携がうまくいかない可能性があるため,Anaconda3を使わないことも検討して欲しい).
conda install -y pytorch torchvision torchaudio pytorch-cuda=11.8 cudnn -c pytorch -c nvidia py -c "import torch; print(torch.__version__, torch.cuda.is_available())"
【サイト内の関連ページ】
【関連する外部ページ】
コマンドプロンプトを管理者として実行: 別ページ »で説明
python -m pip install -U openmim mim install mmengine mim install mmcv mim install mmdet mim install mmpose cd %USERPROFILE% rmdir /s /q mmaction2 git clone https://github.com/open-mmlab/mmaction2.git cd mmaction2 pip install -v -e . mim download mmaction2 --config tsn_imagenet-pretrained-r50_8xb32-1x1x8-100e_kinetics400-rgb --dest .
エラーメッセージが出ていないこと.
cd %USERPROFILE%\mmaction2 notepad actreg.py
このプログラムは, 公式の GitHub のページで公開されていたものを変更して使用している.
このプログラムは,動作認識のためにMMActionを使用する.事前学習済みモデルを読み込んで指定されたビデオファイルで実行し,動作認識結果の上位5位の動作ラベルとそれに対応するスコアを表示する.
from operator import itemgetter from mmaction.apis import init_recognizer, inference_recognizer def load_labels(label_file): with open(label_file, 'r') as file: labels = [line.strip() for line in file.readlines()] return labels def get_top5_action_labels(model, video_file, labels): try: pred_result = inference_recognizer(model, video_file) except Exception as e: print(f"Error during model inference: {e}") return [] pred_scores = pred_result.pred_score.tolist() score_tuples = tuple(zip(range(len(pred_scores)), pred_scores)) score_sorted = sorted(score_tuples, key=itemgetter(1), reverse=True) top5_label = score_sorted[:5] return [(labels[k[0]], k[1]) for k in top5_label] # モデルとラベルの読み込み config_file = 'tsn_imagenet-pretrained-r50_8xb32-1x1x8-100e_kinetics400-rgb.py' checkpoint_file = 'tsn_imagenet-pretrained-r50_8xb32-1x1x8-100e_kinetics400-rgb_20220906-2692d16c.pth' video_file = 'demo/demo_skeleton.mp4' label_file = 'tools/data/kinetics/label_map_k400.txt' try: model = init_recognizer(config_file, checkpoint_file, device='cpu') # or device='cuda:0' labels = load_labels(label_file) except Exception as e: print(f"Error initializing model or loading labels: {e}") else: results = get_top5_action_labels(model, video_file, labels) print('The top-5 labels with corresponding scores are:') for result in results: print(f'{result[0]}: {result[1]}')
Python プログラムの実行
Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.
Python のまとめ: 別ページ »にまとめ
プログラムを actreg.pyのようなファイル名で保存したので, 「python actreg.py」のようなコマンドで行う.
cd %USERPROFILE%\mmaction2 python actreg.py
他の動画を試したいときは, cd %USERPROFILE%\mmaction2\demo に動画ファイルを置き, actreg.py の「video_file = 'demo/demo_skeleton.mp4'」のところを変更して実行する.
ビデオカメラの動作認識を行うプログラム
cd %USERPROFILE%\mmaction2 notepad vidactreg.py
ビデオカメラから読み込み,一定数(ここでは30)のフレームが集まるたびに,最新の120フレームを使用して動作認識を実行する.これを行うために,フレームを一時的に保存するバッファ(リスト)を使用する.このプログラムでは,ビデオからフレームを読み込み,frame_buffer(Pythonのdequeを使用)に保存する.このバッファは最大120フレームを保持し,古いフレームは自動的に削除される.30フレームごとにrecognize_action関数を呼び出し,その時点での最新の120フレームで動作認識を実行する.
import cv2 from mmaction.apis import init_recognizer, inference_recognizer from collections import deque from operator import itemgetter # モデルとラベルの初期化 def initialize_model(config_file, checkpoint_file): try: model = init_recognizer(config_file, checkpoint_file, device='cpu') # or 'cuda:0' return model except Exception as e: print(f"Error initializing model: {e}") return None # ラベルの読み込み def load_labels(label_file): with open(label_file, 'r') as file: labels = [line.strip() for line in file.readlines()] return labels # アクション認識と結果の表示 def recognize_action(model, frames, labels): try: pred_result = inference_recognizer(model, frames) pred_scores = pred_result.pred_score.tolist() score_tuples = tuple(zip(range(len(pred_scores)), pred_scores)) score_sorted = sorted(score_tuples, key=itemgetter(1), reverse=True) top5_label = score_sorted[:5] results = [(labels[k[0]], k[1]) for k in top5_label] for result in results: print(f'{result[0]}: {result[1]}') except Exception as e: print(f"Error during model inference: {e}") def process_video(config_file, checkpoint_file, label_file): model = initialize_model(config_file, checkpoint_file) labels = load_labels(label_file) if not model: return cap = cv2.VideoCapture(0) frame_buffer = deque(maxlen=120) # フレームサイズを取得(動画ファイルの初期化用) frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) while True: ret, frame = cap.read() if not ret: break frame_buffer.append(frame) vidfile = 'a.mp4' if len(frame_buffer) % 30 == 0: # 30フレームごとに # ビデオファイルへの書き込みの初期化 out = cv2.VideoWriter(vidfile, cv2.VideoWriter_fourcc(*'mp4v'), 30, (frame_width, frame_height)) # バッファ内のフレームをビデオファイルに書き込み for f in frame_buffer: out.write(f) out.release() # ビデオライターを解放 recognize_action(model, vidfile, labels) cv2.imshow('Video Frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() # モデルとラベルの読み込み config_file = 'tsn_imagenet-pretrained-r50_8xb32-1x1x8-100e_kinetics400-rgb.py' checkpoint_file = 'tsn_imagenet-pretrained-r50_8xb32-1x1x8-100e_kinetics400-rgb_20220906-2692d16c.pth' label_file = 'tools/data/kinetics/label_map_k400.txt' # ビデオ処理の実行 process_video(config_file, checkpoint_file, label_file)
Python プログラムの実行
Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.
Python のまとめ: 別ページ »にまとめ
プログラムを vidactreg.pyのようなファイル名で保存したので, 「python vidactreg.py」のようなコマンドで行う.
cd %USERPROFILE%\mmaction2 python vidactreg.py