動画の手振れ補正

2019/07/04

Python2.7.8, OpenCV4.1.1

# -*- coding: utf-8 -*-
import cv2
import numpy as np

# 入力動画
fourcc = 'DIB '
fps = 24
size = (170,300)
cap = cv2.VideoCapture(r'C:\Temp\input.avi')

# 基準となる画像を取得
ret, base = cap.read()
base = cv2.resize(base, size)
base = cv2.cvtColor(base, cv2.COLOR_BGR2GRAY)

# 出力先
video1 = cv2.VideoWriter(r'C:\Temp\output2.avi',
                         cv2.VideoWriter_fourcc(*fourcc), fps, size)

warp_type = cv2.MOTION_HOMOGRAPHY
warp = np.eye(3,3,dtype=np.float32)

while True:

    # フレーム取得
    ret, frame = cap.read()
    if not ret:
        break
    frame = cv2.resize(frame, size)
    tmp = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.findTransformECC(tmp, base, warp, cv2.MOTION_HOMOGRAPHY)

    # 出力は元画像(カラー画像)
    out = cv2.warpPerspective(frame, warp, size)

    # 表示かつAVIに出力
    cv2.imshow('frame', out)
    video1.write(out)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
video1.release()
cv2.destroyAllWindows()


PythonとOpenCVでブレ動画を定点カメラっぽくする
https://qiita.com/tAkihiko/items/d34cfeee7003ff321583