Here's a simple Python program using OpenCV and the Kalman filter to stabilize a video stream from a webcam. You can adjust the stabilization level, and choose between blending the edges, cropping in, or leaving them black.
import numpy as np
import cv2
def stabilize_video(cap, stabilization_strength=0.9, method='blend'):
kalman_filter = cv2.KalmanFilter(4, 2)
kalman_filter.measurementMatrix = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], np.float32)
kalman_filter.transitionMatrix = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32)
kalman_filter.processNoiseCov = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32) * 0.03
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
corners, _ = cv2.findChessboardCorners(gray, (7, 7), None)
if corners is not None:
measurement = np.array([[corners[0, 0, 0], corners[0, 0, 1]]], np.float32)
kalman_filter.correct(measurement)
state = kalman_filter.predict()
dx, dy = state[0, 0] - corners[0, 0, 0], state[1, 0] - corners[0, 0, 1]
H = np.float32([[1, 0, dx * stabilization_strength], [0, 1, dy * stabilization_strength]])
stabilized_frame = cv2.warpAffine(frame, H, (frame.shape[1], frame.shape[0]))
if method == 'blend':
alpha = 1 - stabilization_strength
beta = stabilization_strength
stabilized_frame = cv2.addWeighted(frame, alpha, stabilized_frame, beta, 0)
elif method == 'crop':
crop_rect = np.float32([[0, 0], [frame.shape[1], 0], [frame.shape[1], frame.shape[0]], [0, frame.shape[0]]]) - np.float32([dx, dy])
stabilized_frame = cv2.getRectSubPix(stabilized_frame, (frame.shape[1], frame.shape[0]), tuple(crop_rect.mean(axis=0)))
cv2.imshow('Stabilized Video', stabilized_frame)
else:
cv2.imshow('Stabilized Video', frame)
key = cv2.waitKey(1)
if key == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
cap = cv2.VideoCapture(0)
stabilize_video(cap, stabilization_strength=0.9, method='blend')
In this code, you can adjust the stabilization_strength variable to control the amount of stabilization, where 0 represents no stabilization, and 1 represents full stabilization. The method variable can be set to 'blend', 'crop', or 'black' to choose between different ways of handling the edges.
Note that this script uses chessboard corners for tracking points in the video. Feel free to replace findChessboardCorners() with any other feature detection and tracking method if needed.