画像認識などで使用するビデオのサイズをかえて,画面の一部をとりのぞきたいときがある. そういうときにつかえるプログラムを掲載する. 使用法はつぎのとおりである.
clip(inFile, outFile, options...)
inFile が入力ファイル名,outFile が出力ファイル名である. outHeightMin および outHeightMax は出力画面の垂直方向の範囲を指定する. outWidth は出力画面の幅である.
### Clipping video -- reducing the vertical size ###
 
import cv2, cv, time
import numpy as np
 
def createPedestrianWriter(outFile, width, height):
    writer = cv2.VideoWriter()
    writer.open(outFile, cv.CV_FOURCC('P','I','M','1'), fps = 30,
                frameSize = (width, height), isColor = False)
    return writer
 
def clip(inFile, outFile,
         outHeightMin = 80, outHeightMax = 280, outWidth = 1280):
    reader = cv2.VideoCapture(inFile)
    writer = createPedestrianWriter(
        outFile, width = outWidth, height = outHeightMax - outHeightMin
    )
    ret, oframe = reader.read()
    while ret:
        frame = cv2.cvtColor(oframe, cv2.COLOR_BGR2GRAY)
        writer.write(frame[outHeightMin:outHeightMax])
        ret, oframe = reader.read()
                           
                            