Skip to content

Instantly share code, notes, and snippets.

@2kwatts
Created December 17, 2022 22:59
Show Gist options
  • Select an option

  • Save 2kwatts/ed41a3fe3babe71eefcc3e8e46f75a38 to your computer and use it in GitHub Desktop.

Select an option

Save 2kwatts/ed41a3fe3babe71eefcc3e8e46f75a38 to your computer and use it in GitHub Desktop.
Script that takes 50 random snapshots from a video and puts em in an HTML file
import cv2
import random
import os
# Create the "snaps" directory if it doesn't exist
if not os.path.exists("snaps"):
os.makedirs("snaps")
# Open the video file
video_capture = cv2.VideoCapture("video.mp4")
# Get the total number of frames in the video
total_frames = video_capture.get(cv2.CAP_PROP_FRAME_COUNT)
# Open the HTML file for writing
with open("snaps/index.html", "w") as html_file:
# Write the HTML header
html_file.write("<html>\n<body>\n")
# Take 50 random snapshots
for i in range(50):
# Select a random frame number
frame_number = random.randint(0, total_frames)
# Set the video capture to the selected frame
video_capture.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
# Read the frame from the video capture
success, frame = video_capture.read()
# Check if the frame was successfully read
if success:
# Save the frame as an image file in the "snaps" directory
cv2.imwrite(f"snaps/snapshot_{i}.jpg", frame)
# Write the corresponding <img> element to the HTML file
html_file.write(f'<img src="snapshot_{i}.jpg">\n')
else:
print("Unable to read frame from video")
# Write the HTML footer
html_file.write("</body>\n</html>")
# Release the video capture
video_capture.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment