| 1 |
import cv2 |
| 2 |
from os import remove |
| 3 |
from pathlib import Path |
| 4 |
from cv2 import resize, INTER_CUBIC |
| 5 |
|
| 6 |
|
| 7 |
def process_video(input_filename, output_filename, max_frames, frames_stride, reduce_frame_size): |
| 8 |
|
| 9 |
cap = cv2.VideoCapture(input_filename) |
| 10 |
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) |
| 11 |
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) |
| 12 |
fps = int(cap.get(cv2.CAP_PROP_FPS)) |
| 13 |
|
| 14 |
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) |
| 15 |
convert_rgb = int(cap.get(cv2.CAP_PROP_CONVERT_RGB)) |
| 16 |
print("Input video:\nFrame width: " + str(frame_width) + ", frame height: " + str(frame_height)) |
| 17 |
print("Fps: " + str(fps)) |
| 18 |
print("Number of frames: " + str(frame_count)) |
| 19 |
print("Convert to RGB: " + str(convert_rgb)) |
| 20 |
|
| 21 |
|
| 22 |
if Path(output_filename).is_file(): |
| 23 |
remove(output_filename) |
| 24 |
|
| 25 |
|
| 26 |
frame_width = frame_width - frame_width % reduce_frame_size |
| 27 |
frame_height = frame_height - frame_height % reduce_frame_size |
| 28 |
frame_width_output = int(frame_width / reduce_frame_size) |
| 29 |
frame_height_output = int(frame_height / reduce_frame_size) |
| 30 |
|
| 31 |
print("Shape of output frames: (" + str(frame_width_output) + ", " + str( |
| 32 |
frame_height_output) + ")") |
| 33 |
|
| 34 |
fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X') |
| 35 |
out = cv2.VideoWriter(output_filename, fourcc, fps, (frame_width_output, frame_height_output)) |
| 36 |
|
| 37 |
frame_index_read = 0 |
| 38 |
frame_index_written = 0 |
| 39 |
|
| 40 |
while cap.isOpened(): |
| 41 |
ret, frame = cap.read() |
| 42 |
if not frame_index_read % frames_stride: |
| 43 |
output_frame = resize(frame, (frame_width_output, frame_height_output), |
| 44 |
interpolation=INTER_CUBIC) |
| 45 |
out.write(output_frame) |
| 46 |
frame_index_written += 1 |
| 47 |
if frame_index_written == max_frames: |
| 48 |
break |
| 49 |
frame_index_read += 1 |
| 50 |
if frame_index_read == frame_count: |
| 51 |
break |
| 52 |
|
| 53 |
cap.release() |
| 54 |
out.release() |
| 55 |
|
| 56 |
print("Number of frames read: " + str(frame_index_read)) |
| 57 |
print("Number of frames written: " + str(frame_index_written)) |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
input_filename = 'D:\SW-Development\Python\PlanetarySystemStacker\Examples\Moon_2018-03-24\Moon_Tile-024_043939.avi' |
| 62 |
output_filename = 'D:\SW-Development\Python\PlanetarySystemStacker\Examples\Moon_2018-03-24\Moon_Tile-024_043939_resampled.avi' |
| 63 |
max_frames = 1000 |
| 64 |
frames_stride = 20 |
| 65 |
reduce_frame_size = 4 |
| 66 |
|
| 67 |
process_video(input_filename, output_filename, max_frames, frames_stride, reduce_frame_size) |