Skip to content

Instantly share code, notes, and snippets.

@karthikeyan5
Last active April 3, 2021 13:15
Show Gist options
  • Save karthikeyan5/ec5c62942c09fac1e5976f22f2efc9e1 to your computer and use it in GitHub Desktop.
Save karthikeyan5/ec5c62942c09fac1e5976f22f2efc9e1 to your computer and use it in GitHub Desktop.
This script captures frames at a given interval from a supported live stream
  • This script captures frames at a given interval from a supported live stream.
  • Refer to Streamlink Plugins for supported live streams.

To run this script:

  • Install the python dependencies if not already there using pip install opencv-python streamlink
  • Run this script using python livestream_frame_capture.py <live_stream_url> --stream-quality best -ipf 8
#!/usr/bin/env python3
import logging
import sys
import streamlink
import os.path
import datetime
try:
import cv2
except ImportError:
sys.stderr.write("This script requires opencv-python to be installed")
raise
log = logging.getLogger(__name__)
def stream_to_url(url, quality='best'):
streams = streamlink.streams(url)
if streams:
return streams[quality].to_url()
else:
raise ValueError("No steams were available")
def main(url, quality='best', ipf=8):
stream_url = stream_to_url(url, quality)
log.info("Loading stream {0}".format(stream_url))
cap = cv2.VideoCapture(stream_url)
frame_last_save_time = datetime.datetime.now() - datetime.timedelta(seconds=ipf)
while True:
try:
ret, frame = cap.read()
if ret:
if frame_last_save_time <= datetime.datetime.now() - datetime.timedelta(seconds=ipf):
frame_last_save_time = datetime.datetime.now()
print(frame_last_save_time)
time_str = str(frame_last_save_time).replace(' ', '_').replace(':', '-').replace('.', '-') + '_' + str(frame_last_save_time.timestamp()).replace('.', '-')
cv2.imwrite('Frame-'+time_str+'.jpg', frame)
else:
break
except KeyboardInterrupt:
break
cap.release()
if __name__ == "__main__":
import argparse
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description="Save frame in given interval via Streamlink and opencv")
parser.add_argument("url", help="URL of Stream")
parser.add_argument("--stream-quality", help="Requested stream quality [default=best]",
default="best", dest="quality")
parser.add_argument("--ipf", help="Frame Capture interval (expect ~2 sec less ipf) [default=8]",
default=8, type=int)
opts = parser.parse_args()
main(opts.url, opts.quality, opts.ipf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment