Last active
January 3, 2024 20:38
-
-
Save balt-dev/cc2b3dc5cfc3c76fc3eed45d31650a55 to your computer and use it in GitHub Desktop.
Average of all video frames in a video
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
import sys | |
def eprint(*args, **kwargs): | |
print(*args, file=sys.stderr, **kwargs) | |
def main(): | |
# Get the file name | |
args = sys.argv [1:] | |
# Get the capture argument, and the FPS and frame count from it | |
try: | |
outpath = args.pop() | |
capture = cv2.VideoCapture(args.pop()) | |
except IndexError: | |
eprint("Usage: <video> <out-image>") | |
exit(1) | |
count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT)) | |
print(f"Frames: {count}") | |
average_frame = None | |
# Iterate over every frame | |
for frame in range(count): | |
print(f"\r{ (frame + 1) / count * 100: <.2f}%", end = "") | |
# Read the captured frame | |
(read, frame) = capture.read() | |
if average_frame is None: | |
average_frame = np.zeros_like(frame).astype(float) | |
average_frame += frame.astype(float) / count | |
print() | |
if average_frame is None: | |
eprint("No frames found in video") | |
exit(2) | |
# Save the image | |
cv2.imwrite(outpath, average_frame) | |
print("Done") | |
exit(0) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment