Skip to content

Instantly share code, notes, and snippets.

@BillKek
Forked from kscottz/opencv_twitch.py
Last active June 9, 2019 19:34
Show Gist options
  • Save BillKek/2e81bc38b1c8413d51ff3060db7a9c5f to your computer and use it in GitHub Desktop.
Save BillKek/2e81bc38b1c8413d51ff3060db7a9c5f to your computer and use it in GitHub Desktop.
A hack to slurp up twitch streams and process them with opencv.
# do not forget > pip install opencv-python
import cv2
import numpy as np
import time
# livestreamer is dead. use streamlink instead
# do not forget > pip install streamlink
import streamlink
# use live streamer to figure out the stream info
streams = streamlink.streams("https://www.twitch.tv/raulrita")
stream = streams['best']
# open our out file.
fname = "test.mpg"
vid_file = open(fname,"wb")
# dump from the stream into an mpg file -- get a buffer going
fd = stream.open()
for i in range(0,2*2048):
if i%256==0:
print("Buffering...")
new_bytes = fd.read(1024)
vid_file.write(new_bytes)
# open the video file from the begining
print("Done buffering.")
cam = cv2.VideoCapture(fname)
while True:
ret, img = cam.read()
try:
if ret:
img = 255-img # invert the colors
cv2.imshow('live_img',img)
except:
print("DERP")
continue
if (0xFF & cv2.waitKey(5) == 27) or img.size == 0:
break
time.sleep(0.05)
# dump some more data to the stream so we don't run out.
new_bytes = fd.read(1024*16)
vid_file.write(new_bytes)
vid_file.close()
fd.close()
@BillKek
Copy link
Author

BillKek commented Jun 9, 2019

livestreamer is dead. use streamlink instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment