PythonのOpenCVで動画ファイルから指定フレームを画像として抽出

高輪牛町朧月景 コンピュータ
出典:国立国会図書館「NDLイメージバンク」 (https://rnavi.ndl.go.jp/imagebank/)
動画再生位置の移動(シーク)方法を調べてみました。確認のため移動したフレームを画像として抽出してみました。
#!/usr/bin/env python3
import cv2

file = "H:\py\sample.mov"

vc = cv2.VideoCapture(file)

frame_cnt = int(vc.get(cv2.CAP_PROP_FRAME_COUNT)) # フレーム数
fps = int(vc.get(cv2.CAP_PROP_FPS)) # FPS

print("frames:{0},fps:{1}".format(frame_cnt, fps))

ret, img = vc.read()
if not ret:
    quit()  # 終了

cv2.imwrite("frame.png", img)

frame_pos = int(vc.get(cv2.CAP_PROP_POS_FRAMES)) 
print("frame_pos:{0}/{1}".format(frame_pos, frame_cnt))

# 500フレーム目に移動
vc.set(cv2.CAP_PROP_POS_FRAMES, 500)
frame_pos = int(vc.get(cv2.CAP_PROP_POS_FRAMES)) 
print("frame_pos:{0}/{1}".format(frame_pos, frame_cnt))

ret, img = vc.read()
if not ret:
    quit()  # 終了

cv2.imwrite("frame500.png", img)

vc.release()
松本城

出典:8K/4K映像/ハイビジョン映像素材集 (Royalty Free 8K/4K/HD Footage)
– 映像ライブラリ, Stock Footage, 8K/4K/HD Video Footage -(http://www.openspc2.org/HDTV/)

スポンサーリンク

コメント