OpenCV를 사용하여 실시간 비디오 안정화를 구현하는 방법
이 기술을 사용하여 비디오에 영리한 수학을 적용하고 흔들림을 줄이세요.
비디오 안정화는 비디오 영상에서 원치 않는 움직임과 흔들림을 줄이는 기술입니다. 손으로 들고 촬영하는 경우, 진동, 움직임 등으로 인해 카메라가 불안정하게 움직일 수 있습니다. 비디오 안정화는 더욱 부드러운 영상을 생성합니다.
비디오 안정화의 주요 목표는 연속 프레임 사이의 카메라 움직임을 추정하는 것입니다. 그런 다음 프로세스는 프레임을 정렬하기 위해 적절한 변환을 적용할 수 있습니다. 이렇게 하면 인지된 움직임이 최소화됩니다.
환경 설정
프로그램을 실행하기 위해 설치하는 패키지가 기존 패키지와 충돌하지 않도록 가상 환경을 만드는 것부터 시작하세요. 그런 다음 이 터미널 명령을 실행하여 필요한 라이브러리를 설치합니다.
pip install opencv-python numpy
이 명령은 NumPy 및 OpenCV 라이브러리를 설치합니다. NumPy는 수치 작업을 위한 도구를 제공하고 OpenCV는 컴퓨터 비전 작업을 처리합니다.
전체 소스 코드는 GitHub 저장소에서 사용할 수 있습니다.
필수 라이브러리 가져오기 및 세 가지 중요한 기능 정의
새 Python 파일을 만들고 원하는 이름을 지정합니다. 스크립트 시작 부분에서 NumPy 및 OpenCV 라이브러리를 가져옵니다.
import numpy as np
import cv2이러한 라이브러리를 가져오면 코드에서 해당 기능을 사용할 수 있습니다.
다음으로 안정화 프로세스에 중요한 세 가지 기능을 정의합니다.
계산_이동_평균 함수
함수를 만들고 이름을 calculate_moving_average로 지정합니다. 이 함수는 지정한 반경을 사용하여 주어진 곡선의 이동 평균을 계산합니다. 지정된 창 크기와 균일한 커널을 사용하는 컨볼루션 작업을 사용합니다. 이 이동 평균은 궤적의 변동을 완화하는 데 도움이 됩니다.
def calculate_moving_average(curve, radius):
# Calculate the moving average of a curve using a given radius
window_size = 2 * radius + 1
kernel = np.ones(window_size) / window_size
curve_padded = np.lib.pad(curve, (radius, radius), 'edge')
smoothed_curve = np.convolve(curve_padded, kernel, mode='same')
smoothed_curve = smoothed_curve[radius:-radius]
return smoothed_curve
이 함수는 부드러운 곡선을 반환합니다. 이는 곡선의 소음과 변동을 줄이는 데 도움이 됩니다. 이는 슬라이딩 창 내의 값을 평균화하여 수행됩니다.
Smooth_trajectory 함수
다른 함수를 만들고 이름을 smooth_trajectory로 지정합니다. 이 함수는 궤적의 각 차원에 이동 평균을 적용합니다. 이는 원래 궤적의 매끄러운 복사본을 생성하여 이를 달성합니다. 이렇게 하면 영상의 안정성이 더욱 향상됩니다.
def smooth_trajectory(trajectory):
# Smooth the trajectory using moving average on each dimension
smoothed_trajectory = np.copy(trajectory)
for i in range(3):
smoothed_trajectory[:, i] = calculate_moving_average(
trajectory[:, i],
radius=SMOOTHING_RADIUS
)
return smoothed_trajectory
smooth_trajectory 함수는 매끄러운 궤적을 반환합니다.
fix_border 함수
최종 함수를 만들고 이름을 fix_border로 지정합니다. 이 함수는 회전 및 크기 조정 변환을 적용하여 프레임의 테두리를 수정합니다. 입력 프레임을 가져와서 모양을 계산하고 변환 행렬을 구성한 다음 프레임에 변환을 적용합니다. 마지막으로 고정 프레임을 반환합니다.
def fix_border(frame):
# Fix the frame border by applying rotation and scaling transformation
frame_shape = frame.shape
matrix = cv2.getRotationMatrix2D(
(frame_shape[1] / 2, frame_shape[0] / 2),
0,
1.04
)
frame = cv2.warpAffine(frame, matrix, (frame_shape[1], frame_shape[0]))
return framefix_border 기능은 안정화된 프레임에 안정화 프로세스로 인해 발생한 테두리 아티팩트가 없는지 확인합니다.
비디오 안정화 초기화 및 입력 받기
궤적 스무딩 기능이 사용할 반경을 설정하는 것부터 시작합니다.
SMOOTHING_RADIUS = 50
그런 다음 안정화하려는 흔들리는 비디오의 비디오 경로를 전달합니다.
# Open the input video file
# Replace the path with 0 to use your webcam
cap = cv2.VideoCapture('inputvid.mp4')흔들리는 비디오의 속성을 가져옵니다.
num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)출력 형식을 설정합니다. 이는 프로그램이 안정화된 비디오를 저장하는 형식입니다. 원하는 일반적인 비디오 형식을 사용할 수 있습니다.
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
마지막으로 비디오 작성기를 초기화합니다.
out = cv2.VideoWriter('video_out.mp4', fourcc, fps, (2 * width, height))비디오 작가에게 전달하는 파일 이름의 확장자는 출력 형식에서 설정한 것과 동일해야 합니다.
프레임 읽기 및 처리
흔들리는 영상을 처리하는 첫 번째 단계는 여기서부터 시작됩니다. 여기에는 입력 비디오에서 프레임을 읽고, 변환을 계산하고, 변환 배열을 채우는 작업이 포함됩니다.
첫 번째 프레임을 읽는 것부터 시작하세요.
_, prev_frame = cap.read()
prev_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY)
그런 다음 변환 배열을 초기화합니다. 각 프레임에 대한 정보를 저장합니다.
transforms = np.zeros((num_frames - 1, 3), np.float32)
마지막으로 연속 프레임 간의 광학 흐름을 계산해야 합니다. 그런 다음 점 사이의 아핀 변환을 추정합니다.
for i in range(num_frames - 2):
# Calculate optical flow between consecutive frames
prev_points = cv2.goodFeaturesToTrack(
prev_gray,
maxCorners=200,
qualityLevel=0.01,
minDistance=30,
blockSize=3
)
success, curr_frame = cap.read()
if not success:
break
curr_gray = cv2.cvtColor(curr_frame, cv2.COLOR_BGR2GRAY)
curr_points, status, err = cv2.calcOpticalFlowPyrLK(
prev_gray,
curr_gray,
prev_points,
None
)
assert prev_points.shape == curr_points.shape
idx = np.where(status == 1)[0]
prev_points = prev_points[idx]
curr_points = curr_points[idx]
# Estimate affine transformation between the points
matrix, _ = cv2.estimateAffine2D(prev_points, curr_points)
translation_x = matrix[0, 2]
translation_y = matrix[1, 2]
rotation_angle = np.arctan2(matrix[1, 0], matrix[0, 0])
transforms[i] = [translation_x, translation_y, rotation_angle]
prev_gray = curr_gray
루프는 각 프레임(마지막 프레임 제외)을 반복하여 변환을 계산합니다. Lucas-Kanade 방법을 사용하여 연속 프레임 간의 광학 흐름을 계산합니다. cv2.goodFeaturesToTrack은 이전 프레임 prev_gray에서 특징점을 감지합니다. 그런 다음 cv2.calcOpticalFlowPyrLK는 현재 프레임 curr_gray에서 이러한 지점을 추적합니다.
상태가 1(성공적인 추적을 나타냄)인 포인트만 아핀 변환 행렬을 추정하는 데 도움이 됩니다. 코드는 다음 반복을 위해 prev_gray 변수를 현재 회색조 프레임으로 업데이트합니다.
궤적을 부드럽게 하기
안정적인 결과를 얻으려면 변환에서 얻은 궤적을 부드럽게 해야 합니다.
# Calculate the trajectory by cumulatively summing the transformations
trajectory = np.cumsum(transforms, axis=0)
# Smooth the trajectory using moving average
smoothed_trajectory = smooth_trajectory(trajectory)
# Calculate the difference between the smoothed and original trajectory
difference = smoothed_trajectory - trajectory
# Add the difference back to the original transformations to obtain smooth
# transformations
transforms_smooth = transforms + difference위의 코드는 카메라 움직임의 궤적을 계산하고 이를 부드럽게 합니다.
프레임 안정화 및 작성
마지막 단계는 프레임을 안정화하고 안정화된 비디오를 출력 파일에 쓰는 것입니다.
비디오 캡처를 재설정하여 시작하십시오. 이렇게 하면 향후 작업이 비디오 시작 부분부터 읽혀지게 됩니다.
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
그런 다음 각 프레임을 처리하여 비디오를 안정화합니다.
# Process each frame and stabilize the video
for i in range(num_frames - 2):
success, frame = cap.read()
if not success:
break
translation_x = transforms_smooth[i, 0]
translation_y = transforms_smooth[i, 1]
rotation_angle = transforms_smooth[i, 2]
# Create the transformation matrix for stabilization
transformation_matrix = np.zeros((2, 3), np.float32)
transformation_matrix[0, 0] = np.cos(rotation_angle)
transformation_matrix[0, 1] = -np.sin(rotation_angle)
transformation_matrix[1, 0] = np.sin(rotation_angle)
transformation_matrix[1, 1] = np.cos(rotation_angle)
transformation_matrix[0, 2] = translation_x
transformation_matrix[1, 2] = translation_y
# Apply the transformation to stabilize the frame
frame_stabilized = cv2.warpAffine(
frame,
transformation_matrix,
(width, height)
)
# Fix the border of the stabilized frame
frame_stabilized = fix_border(frame_stabilized)
# Concatenate the original and stabilized frames side by side
frame_out = cv2.hconcat([frame, frame_stabilized])
# Resize the frame if its width exceeds 1920 pixels
if frame_out.shape[1] > 1920:
frame_out = cv2.resize(
frame_out,
(frame_out.shape[1] // 2, frame_out.shape[0] // 2)
)
# Display the before and after frames
cv2.imshow("Before and After", frame_out)
cv2.waitKey(10)
# Write the frame to the output video file
out.write(frame_out)위의 코드는 변환 및 회전 조정을 포함하여 계산된 변환을 사용하여 각 프레임을 안정화합니다. 그런 다음 안정화된 프레임을 원본 프레임과 결합하여 비교를 제공합니다.
비디오 캡처 및 작가 출시
비디오 캡처 및 작가 개체를 릴리스하여 프로그램을 마무리합니다.
# Release the video capture and writer, and close any open windows
cap.release()
out.release()
cv2.destroyAllWindows()이 코드는 열려 있는 창도 닫습니다.
최종 프로그램 출력
프로그램의 출력은 다음과 같습니다.
안정화된 비디오의 예는 다음과 같습니다.
출력에는 흔들리는 비디오와 안정화된 비디오 간의 비교가 표시됩니다.
OpenCV 기능 살펴보기
컴퓨터 비전과 관련된 다양한 분야에 OpenCV를 적용할 수 있습니다. 다양한 기능을 제공하기 때문입니다. 컴퓨터 비전과 관련된 더 많은 프로젝트를 수행하여 그 기능을 탐색해야 합니다. 이는 여러분에게 새로운 개념을 소개하고 연구할 새로운 영역을 제공할 것입니다.

