10
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?

OpenCVでビデオのコマ画像を取り出す。

Last updated at Posted at 2025-12-03

OpenCVでビデオのコマ画像を取り出す

このコマンドでは、OpenCVを使ってビデオの1コマを取り出して、PNGファイルにセーブするプログラムです。

ライブラリ

OpenCVを使います。
pip install opencv-python
でインストール
最近のDebian系では
sudo apt install python3-opencv
でないとだめな場合があります。

ソース

picpic.py
import cv2
import numpy as np

fname=input("Filename:")
cap = cv2.VideoCapture(fname)

if not cap.isOpened():
    print(f'fname:{fname} is not opened')
    exit()

# 幅と高さを取得
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# 総フレーム数を取得
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

icmd=""
while icmd != "end":
    r,img = cap.read()
    if not r:
        break
    cv2.imshow("Frame",img)
    cv2.waitKey(10)
    fpos = cap.get(cv2.CAP_PROP_POS_FRAMES)
    print(f'max frame {frame_count} now {fpos}')
    icmd=input("frame number:")
    if icmd=="end":
        pass
    elif icmd=="sv":
        cv2.imwrite(f'sv{int(fpos)}.png',img)
    else:
        try:
            rpos = int(icmd)
        except:
            rpos = 0
            print("number error")
    if rpos > frame_count:
        rpos = frame_count-1
    cap.set(cv2.CAP_PROP_POS_FRAMES, rpos)

ダウンロードと使い方

ダウンロードはこちら
ダウンロードしたファイルは
tar xovfz picpic.tgzで解凍してください。
Windowsの人はWSLで使ってね。

使い方はビデオでそうぞ
https://youtu.be/GXUxvClQIiE
動画で使っているサンプル動画をテスト用に入れてます。
ビデオファイルはプログラムをおいているディレクトリにおいてくださいね。

10
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
10
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?