LoginSignup
9
8

More than 5 years have passed since last update.

【Python】OpenCVで取り込んだビデオデータを連番のjpgファイルで保存

Last updated at Posted at 2016-09-27

正直、フリーツールとか探せばもっと良いのがゴロゴロしてると思う。
仕事とか迂闊にフリーツールを入れれない環境とかで、
毎回似たようなものを作成しているので、備忘録的に記載。

第1引数にビデオソース。
 →Webカメラにアクセスする際は、0-9の数字を指定。
  動画ファイルにアクセスするときは、相対か絶対パスで動画ファイルを指定。
第2引数にフレームレート。
 →表示する際のフレームレート。cv2.waitKey()の待ち時間を変更しているだけの手抜き処理。
第3引数に縮小率。
 →吐き出すjpgファイルのサイズを変更する際に指定。
  2を指定すると1/2の横縦幅の画像に。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
video2jpg.py.

Usage:
  video2jpg.py [<video source>] [<fps>] [<resize_rate>]
'''

import numpy as np
import cv2
import sys

print(__doc__)

try:
    fn = sys.argv[1]
    if fn.isdigit() == True:
        fn = int(fn)
except:
    fn = 0
print fn

try:
    fps = sys.argv[2]
    fps = int(fps)
except:
    fps = 30
print fps

try:
    resize_rate = sys.argv[3]
    resize_rate = int(resize_rate)
except:
    resize_rate = 1
print resize_rate

video_input = cv2.VideoCapture(fn)
if (video_input.isOpened() == False):
    exit()

count = 0
while(True):
    count += 1
    count_padded = '%05d' % count

    ret, frame = video_input.read()

    height, width = frame.shape[:2]
    small_frame = cv2.resize(frame, (int(width/resize_rate), int(height/resize_rate)))

    cv2.imshow('frame', small_frame)
    c = cv2.waitKey(int(1000/fps)) & 0xFF

    write_file_name = count_padded + ".jpg"
    cv2.imwrite(write_file_name, small_frame)

    if c==27: # ESC
        break

video_input.release()
cv2.destroyAllWindows()
9
8
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
9
8