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

ビデオファイルから固定位置の画像を取り出す。

Last updated at Posted at 2026-01-06

ビデオファイルから固定位置のコマ画像をファイル化

生成AIで作った動画ファイルやビデオ撮りした動画ファイルから定位置の画像を取り出します。
使用するライブラリはOpenCVのみです。
今回はインストール方法を省略します。

OpenCVのインストール方法は、こちらを参考にしてください。
OpenCVでビデオのコマ画像を取り出す。
こちらのコマンドでは、フレームの位置を移動しながら取り出したい画像をセーブしますがちょっと面倒だったので今回は定位置のコマを取り出すようにしました。

ソース

Linux用(Ubuntu系用)にシバンを指定しているのでソースをダウンロードして実行権をつけてくれればコマンドとして動作します。

実行権の付け方は
chmod +x picn
で実行はコマンドのあるディレクトリに移動して ./picn で実行します。

#!/usr/bin/python3

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))
ploc=[25,50,75,100]

icmd=""
for pn in ploc:
    r,img = cap.read()
    if not r:
        break
    cap.set(cv2.CAP_PROP_POS_FRAMES, pn)
    fpos = cap.get(cv2.CAP_PROP_POS_FRAMES)
    print(f'max frame {frame_count} now {fpos}')
    cv2.imwrite(f'{fname}{int(fpos)}.png',img)
    cv2.imshow("Frame",img)
    cv2.waitKey(10)

このソースをpicnとして保存してください。
34行目にある、ploc=[xx,xx,xx]のxx(数字)が取り出すコマの位置になっているのでここを適当に変えるとつねにその位置の画像をファイル化してくれます。
ファイル名は指定したファイル名、例えばhoge.mp4なら hoge.mp4.25.png が25コマ目のイメージ画像で50、75、100の4枚が出来上がります。

Windowsで動かす場合は

python picn
で動きます。

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