def Qualities(title, url, summary, thumb, art, is_streamlink): """ get streams from url with livestreamer, list the qualities, return none if none available """ if is_streamlink: try: streams = streamlink.streams(url) except: pass new_streams = list() for quality in streams: if is_streamlink: st = stream_type_streamlink(streams[quality]) if (st == "HLSStream") or (st == "HTTPStream"): surl = streams[quality].url new_streams.append(u"{}|{}|{}".format(st, quality, surl)) if not new_streams: return None thumb = thumb if thumb != 'na' else '' art = art if art != 'na' else '' final_streams = "livestreamerccloud://" + u"title={},summary={},url={},thumb={},art={}|||".format(title, (E(JSON.StringFromObject(summary))), (E(JSON.StringFromObject(url))), thumb, art) + "||".join(new_streams) #final_streams = "livestreamerccloud://" + (E(JSON.StringFromObject({"url": url, "title": title, "summary": summary, "thumb": thumb, "art": art})) +"$$$") + (E(JSON.StringFromObject("||".join(new_streams)))) vco = VideoClipObject( url=final_streams, title=title, summary=summary, thumb=thumb if thumb else None, art=art if art else None ) return vco
def _get_streams(self): res = http.get(self.url) m = self.iframe_re.search(res.text) yt_url = m and m.group(1) if yt_url: self.logger.debug("Deferring to YouTube plugin with URL: {0}".format(yt_url)) return streams(yt_url)
def CheckLivestreamer(url): """ only checks if livestreamer has a plugin to support this url, might still return no streams """ try: streams = streamlink.streams(url) if Prefs['debug']: Log("Streamlink can handle the url %s" % url) return True except: pass return False
def download_videos(d_vi_description, d_vi_url): # This method lets you download all vods 1 by 1 d_vi_user_input = input("Do you want to download all VODs? (y/n): ") if d_vi_user_input == "y": for i in range(0, len(d_vi_url)): stream = streamlink.streams(d_vi_url[i])["best"].url download = subprocess.Popen([ "streamlink", "--hls-segment-threads", "4", "-o", d_vi_description[i] + ".mkv", stream, "best", ]) download.wait() elif d_vi_user_input == "n": return 0 else: print("Wrong choice, start again") download_videos(d_vi_description, d_vi_url)
def getTwitchStream(user): stream = streamlink.streams("http://twitch.tv/" + user) #print(stream.keys()) # Check to see if stream is live if bool(stream) is False: result = {'channelExists' : False} print("Stream is not live!") return result stream = stream['audio_only'] fd = stream.open() start_time_in_seconds = time.time() time_limit = 5 with open(streamFile , 'wb') as f: while time.time() - start_time_in_seconds < time_limit: data = fd.read(1024) f.write(data) f.close() result = {'channelExists' : True} return result
def read(self): streams = streamlink.streams(self.streamURL) if not streams: return None for resolution in self.res: if resolution in streams: url = streams[resolution].url break vid = cv2.VideoCapture(url) succ, frame = vid.read() if succ: vid.release() self.frame = frame return frame else: print("No frame to read!\n") self.frame = None vid.release() return None
def set_bot_active(self, bot_active): self.bot_active = bot_active #An instance of the repeated timer already exists, terminate it if self.repeated_timer: self.repeated_timer.stop() if bot_active: self.streams = streamlink.streams(self.stream_url) self.stream = self.streams[self.stream_quality].url self.repeated_timer = RepeatedTimer(20, stream_check) self.repeated_timer.start() print('Starting stream checks...') print( 'The first check might fail because of the Twitch purple screen of death' ) else: self.streams = {} self.stream = None
def get_video(roomId): movie = 'https://live.bilibili.com/' + str(roomId) if not os.path.exists('video'): os.makedirs('video') # print('文件将会下载到video文件夹') print() session = Streamlink() #创建一个会话 try: streams = session.streams(movie) #在会话里输入url会返回直播的flv缓存地址 except: try: streams = streamlink.streams(movie) except: print('[INFO]该网站不存在plug接口') exit(0) # print(streams) print('[INFO]获取了视屏流地址.....') list = ['source', 'medium', 'best', 'worse'] for l in list: if streams[l].url: print('[INFO]获得视频%s' % l) source = streams[l].url if 'm3u8' in str(source): print('[ERROR]%s存在m3u8,暂不支持下载,' % l) continue else: socket.setdefaulttimeout(10) while streams[l].url: try: name = time.strftime('%y%m%d_%H%M%S', time.localtime()) + '.flv' print(name + '正在缓存') path = './video/' + name request.urlretrieve( source, os.path.join(path)) # 'video/1.flv' print('[INFO]您缓存的直播已下播......') break except socket.timeout: continue
def record(username_in, output_in): print("recording " + username_in) try: streams = streamlink.streams("http://twitch.tv/" + username_in) except: print("type error or 410 for " + username_in + ", no clue why, maybe something else..." ) #it was happening to fextralife try: stream = streams["best"] #always select best, we're not messing around filename = username_in + ( datetime.datetime.now().strftime("_%Y-%m-%d_%H-%M-%S.ts")) output_file = (output_in + filename) open(output_file, "w+") #creates the first file with open(output_file, "ab") as ouput: fd = stream.open() recording = 1 while (recording == 1): #this is dirty but it'll work for now :/ try: data = fd.read(1024) except OSError: #try to close then reopen the file :P print("file read timeout hiccup, fix later") fd.close() fd = stream.open() #checks if the data stream has ended, if so, ends the recording if not data: fd.close() ouput.close print(username_in + "'s stream has ended, go in peace") recording = 0 ouput.write(data) except KeyError: print(username_in + "'s stream is still winding down...")
def record_stream(url, total_time, tmp_folder, output_file, block_size=20): start_time = datetime.datetime.now().timestamp() prev_data = "" tmp_folder = tmp_folder.rstrip('/') counter = 0 segment_duration = 0 total_iter = 1 while counter != total_iter: tmp_file_path = tmp_folder + '/tmp-' + str(counter // block_size) + '.ts' streams = streamlink.streams(url) stream_url = streams["best"] m3u8_obj = m3u8.load(stream_url.args['url']) str_uri = m3u8_obj.segments[0].uri filedata = urllib.request.urlopen(str_uri).read() if filedata != prev_data: f = open(tmp_file_path, 'ab+') f.write(filedata) f.close() if segment_duration == 0: os.chdir(tmp_folder) segment_duration = round( float(subprocess.getoutput('ffmpeg -i tmp-' + str(counter // block_size) + '.ts -hide_banner') .split('\n')[1] .split(', ')[0][-5:]) ) total_iter = math.ceil(total_time / segment_duration) log_print('Segment_duration sated to {0}. Basing on this data setting iterations to {1}' .format(segment_duration, total_iter), 0) os.chdir('../') prev_data = filedata counter += 1 log_print('Writing segment {0}. File path - {1} . Left {2} segments and {3} seconds' .format(counter, tmp_file_path, total_iter - counter,(total_iter - counter)*segment_duration),1) merge_all(tmp_folder, output_file) log_print('Total time - {0} s' .format(round(datetime.datetime.now().timestamp() - start_time)), 1)
def play_stream(stream_url): """ Resolve and play a stream at the provided url. :param stream_url: str :return: None """ try: urls = streamlink.streams(stream_url) except streamlink.exceptions.NoPluginError: xbmcgui.Dialog().notification( 'Unable to play stream', 'no plugin for stream at {}'.format(stream_url), xbmcgui.NOTIFICATION_ERROR, 5000) return if not urls: #check if the plugin actually returned playable urls xbmcgui.Dialog().notification( 'Unable to play stream', 'no playable stream found at {}, url list is empty'.format( stream_url), xbmcgui.NOTIFICATION_ERROR, 5000) return best = urls['best'] if type(best).__name__ == 'RTMPStream': #RTMPstream for some reason does not support .url, so we have to build it ourself url = str(best.params['rtmp']) #start with rtmp://url for key, value in best.params.iteritems(): if key != 'rtmp': url += ' ' + str(key) + "=" + str( value) #add ' key=value' for all other params to url else: #all other streams simply work url = best.url # Pass the item to the Kodi player. xbmcplugin.setResolvedUrl(pluginhandle, True, listitem=xbmcgui.ListItem(path=url))
def __init__( self, twitch_id: str, buffer_size: int, block_size: int, channels: int = None, sample_rate: int = None, ): """ :param twitch_id: :param buffer_size: Number of blocks used for buffering :param block_size: Block size """ self.twitch_id = twitch_id streams = streamlink.streams(f"https://twitch.tv/{twitch_id}") logging.info(f"streamlink.streams keys: {list(streams.keys())}") self.audio_stream_url = streams['audio_only'].url logging.info(f"{self.audio_stream_url=}") stream_info = ffmpeg.probe(self.audio_stream_url, cmd=r'ffmpeg\ffprobe.exe') logging.info(f"{stream_info=}") audio_streams = [_stream for _stream in stream_info['streams'] if _stream.get('codec_type') == 'audio'] if len(audio_streams) != 1: raise ValueError(f"{len(audio_streams)} audio streams found (expected 1).") audio_stream = audio_streams[0] logging.info(f"{audio_stream=}") self.channels = audio_stream['channels'] if channels is None else channels self.sample_rate = int(audio_stream['sample_rate']) if sample_rate is None else sample_rate self.buffer_size = buffer_size self.block_size = block_size self.read_size = self.block_size * self.channels * 2 # s16 is 2 bytes
def get_frame(*args): import streamlink import numpy as np import subprocess as sp from PIL import Image streams = streamlink.streams(args[0]) FFMPEG_BIN = "ffmpeg" pipe = sp.Popen( [ FFMPEG_BIN, "-i", streams['720p'].url, "-loglevel", "quiet", # no text output "-an", # disable audio "-f", "image2pipe", "-pix_fmt", "bgr24", "-vcodec", "rawvideo", "-" ], stdin=sp.PIPE, stdout=sp.PIPE) raw_image = pipe.stdout.read(960 * 720 * 3) # read 432*240*3 bytes (= 1 frame) image = np.fromstring(raw_image, dtype='uint8').reshape((720, 960, 3)) result = Image.fromarray((image).astype(np.uint8)) result.save('frontend/static/images/pre_in.png') pipe.kill() pipe.terminate()
def retrieve_stream(modelname): LOGGER.info(f"{modelname}: Creating Thread") modelpage = f"https://en.chaturbate.com/{modelname}/" streamurl = None resp = requests.get(modelpage) for line in resp.text.split("\n"): if "m3u8" in line: #LOGGER.info(f"LINE:\n{line}") streamurl = line.split(".m3u8")[0].split("http")[1] streamurl = f"http{streamurl}.m3u8".replace(r"\u002D", "-") #LOGGER.info(f"Streamurl: {streamurl}") if streamurl is not None: try: start_date = f"{dt.now().month}_{dt.now().day}_{dt.now().year}" start_time = f"{dt.now().hour}_{dt.now().minute}" LOGGER.info(f"Perparing Filesystem for Streams from {modelname}") modeldir = f"{CAPTURELOCATION}{modelname}{SLASH}" if not os.path.exists(modeldir): os.mkdir(modeldir) filename = f"{modeldir}{modelname}_{start_date}_{start_time}.mp4" LOGGER.info(f"Saving stream for {modelname}") stream = streamlink.streams(streamurl)["best"] with open(filename, "wb") as inputstream: with stream.open() as stream_fd: while True: inputstream.write(stream_fd.read(1024)) LOGGER.info(f"{modelname} is done") return modelname except Exception as excp: LOGGER.exception(f"Thread for {modelname} threw:\n{excp}") finally: return modelname else: #LOGGER.debug(f"{modelname} is offline") return modelname
def zap(session, service, **kwargs): errormsg = None if service and "http" in service.toString(): url = service.toString() url = url.split(":") if len(url) > 9: url = url[10] if Streamlink and url.startswith("streamlink%3a//"): url = url.replace("streamlink%3a//", "") url = url.replace("%3a", ":") try: streams = streamlink.streams(url) if streams: url = streams["best"].to_url() print("[ChannelSelection] zap / streamlink result url %s" % url) return (url, errormsg) else: errormsg = "No Link found!" print("[ChannelSelection] zap / streamlink no streams") except Exception as e: errormsg = str(e) print("[ChannelSelection] zap / streamlink failed %s" % str(e)) pass return (None, errormsg)
r = requests.get(videosUrl, headers={ 'Content-Type': "application/json", 'Client-ID': "xrept5ig71a868gn7hgte55ky8nbsa" }) videos = r.json()['data'] user_clips = [] for v in videos: stream_duration = get_video_duration(v['duration']) stream_id = int(v['id']) print("stream_id", stream_id) try: twitch_stream_url = f"https://twitch.tv/videos/{stream_id}" twitch_streams = streamlink.streams(twitch_stream_url) twitch_stream = twitch_streams['best'] except Exception as e: print("error", str(e)) continue for i in range(1, 6): random_time = random.randint(0, stream_duration) random_duration = random.randint(1, 10) time_in = random_time - random_duration time_out = random_time + random_duration if time_in < 0: time_in = 0 if time_out > stream_duration: time_out = stream_duration
import cv2 import time import streamlink import threading import twitchBot from clickRequest import clickRequest #Get URL of stream streams = streamlink.streams("http://twitch.tv/trophywagers") stream = streams['480p'] #Get first-place image to compare to frame of stream img1 = cv2.imread('img/large1stplace.PNG', 0) #Get stream cap = cv2.VideoCapture(stream.url) orb = cv2.ORB_create() kp1, des1 = orb.detectAndCompute(img1, None) checkCount = 0 def wagersWinner(): global checkCount while True: ret, frame = cap.read() img2 = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if cv2.waitKey(1) & 0xFF == ord('q'): break
import cv2 import numpy as np import datetime import streamlink import time from collections import deque from datetime import datetime import json import time filename = 'E:\\masters_Video_cap\\test.AVI' #set video file name streams = streamlink.streams( "http://46.4.36.73/hls/bundoransurfco/playlist.m3u8" ) #"https://youtu.be/bNLy-XXYxcw") quality = 'best' image = cv2.VideoCapture(streams[quality].to_url()) # fps = image.get(cv2.CAP_PROP_FPS) length = image.get(cv2.CAP_PROP_FRAME_WIDTH) hight = image.get(cv2.CAP_PROP_FRAME_HEIGHT) res = (length, hight) roi_base = 180 abv_avg = False blw_avg = False maxline_ary = [] base_cut = 99 dsp_array = deque([]) max_base = 0 min_h_ary = deque([])
def get_stream_info(live: Live): streams = streamlink.streams(live.get_url()) return { quality: serialize_stream(stream) for quality, stream in streams.items() }
def watch(self): curr_time = datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S") file_name = curr_time + " - " + self.streamer + " - " + get_valid_filename( self.stream_title) + ".ts" directory = self._formatted_download_folder( self.streamer_login) + os.path.sep if not os.path.exists(directory): os.makedirs(directory) output_filepath = directory + file_name self.streamer_dict.update({'output_filepath': output_filepath}) streams = streamlink.streams('https://www.twitch.tv/' + self.streamer_login) # Occurs when already recording another stream and new streamer (that is already live) is added # not sure why this error is thrown.. # Traceback (most recent call last): # File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner # self.run() # File "E:\Downloads\automatic-twitch-recorder\venv\lib\site-packages\streamlink\stream\segmented.py", line 59, in run # for segment in self.iter_segments(): # File "E:\Downloads\automatic-twitch-recorder\venv\lib\site-packages\streamlink\stream\hls.py", line 307, in iter_segments # self.reload_playlist() # File "E:\Downloads\automatic-twitch-recorder\venv\lib\site-packages\streamlink\stream\hls.py", line 235, in reload_playlist # self.process_sequences(playlist, sequences) # File "E:\Downloads\automatic-twitch-recorder\venv\lib\site-packages\streamlink\plugins\twitch.py", line 210, in process_sequences # return super(TwitchHLSStreamWorker, self).process_sequences(playlist, sequences) # TypeError: super(type, obj): obj must be an instance or subtype of type try: stream = streams[self.stream_quality] except KeyError: temp_quality = self.stream_quality if len(streams) > 0: # False => stream is probably offline if self.stream_quality in streams.keys(): self.stream_quality = StreamQualities.BEST.value else: self.stream_quality = list(streams.keys())[ -1] # best not in streams? choose best effort quality else: self.cleanup = True if not self.cleanup: print('Invalid stream quality: ' + '\'' + temp_quality + '\'') print('Falling back to default case: ' + self.stream_quality) self.streamer_dict['preferred_quality'] = self.stream_quality stream = streams[self.stream_quality] else: stream = None if not self.kill and not self.cleanup and stream: print(self.streamer + ' is live. Saving stream in ' + self.stream_quality + ' quality to ' + output_filepath + '.') try: with open( output_filepath, "ab") as out_file: # open for [a]ppending as [b]inary fd = stream.open() while not self.kill and not self.cleanup: data = fd.read(1024) # If data is empty the stream has ended if not data: fd.close() out_file.close() break out_file.write(data) except streamlink.StreamError as err: print('StreamError: {0}'.format( err)) # TODO: test when this happens except IOError as err: # If file validation fails this error gets triggered. print('Failed to write data to file: {0}'.format(err)) self.streamer_dict.update({'kill': self.kill}) self.streamer_dict.update({'cleanup': self.cleanup}) return self.streamer_dict
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 streams(stream_url): streamlink.streams(stream_url)
def com_net_streamlink_streams(stream_url): """ List possible streams """ return streamlink.streams(stream_url)
def build_GUI(): OptionList = [ "Laptop webcam", "IP webcam", "Local video", "Link to stream" ] app = tk.Tk() app.title("Social Distancing Detector") app.geometry('575x480') optionVar = tk.StringVar() optionVar.set(OptionList[0]) optionFrame = tk.LabelFrame(app, text="Stream type", width=550, height=80) optionFrame.place(x=10, y=10) optionFrame.pack_propagate(False) optionLabel = tk.Label(optionFrame, text="Select input video stream: ", font=20) optionLabel.place(x=15, y=13) opt = tk.OptionMenu(optionFrame, optionVar, *OptionList) opt.config(width=20, font=15) opt.place(x=255, y=9) sourceFrame = tk.LabelFrame(app, text="Source", width=550, height=140) sourceFrame.place(x=10, y=110) sourceFrame.pack_propagate(False) sourceLabel = tk.Label(sourceFrame, text="Don't worry about this", font=20) sourceLabel.place(x=15, y=15) sourceVar = tk.StringVar() sourceVar.set("0") sourceEntry = tk.Entry(sourceFrame, width=55, textvariable=sourceVar, state="disabled") sourceEntry.place(x=15, y=65) calibrationFrame = tk.LabelFrame(app, text="Calibration", width=550, height=140) calibrationFrame.place(x=10, y=270) calibrationFrame.pack_propagate(False) calibrationLabel = tk.Label( calibrationFrame, text="Insert calibration matrix path (leave empty for no calibration)", font=20) calibrationLabel.place(x=15, y=15) calibrationVar = tk.StringVar() calibrationVar.set("webcam_calibration_matrix.yml") calibrationEntry = tk.Entry(calibrationFrame, width=50, textvariable=calibrationVar) calibrationEntry.place(x=15, y=65) def continue_callback(): app.destroy() continueButton = tk.Button(app, text="Continue", font=20, fg="blue", command=continue_callback) continueButton.place(x=460, y=428) def option_callback(*args): sourceEntry.configure(state="normal") selectedOption = optionVar.get() if selectedOption == "Laptop webcam": sourceLabel.configure(text="Don't worry about this") sourceVar.set("0") sourceEntry.configure(state="disabled") calibrationVar.set("webcam_calibration_matrix.yml") elif selectedOption == "IP webcam": sourceLabel.configure(text="Insert the webcam IP") sourceVar.set("https://192.168.1.37:8080/video") calibrationVar.set("phone_calibration_matrix.yml") elif selectedOption == "Local video": sourceLabel.configure(text="Insert the path to the local video") sourceVar.set("video/pedestrians.mp4") calibrationVar.set("") elif selectedOption == "Link to stream": sourceLabel.configure(text="Insert the link to the stream") sourceVar.set("https://www.youtube.com/watch?v=srlpC5tmhYs") calibrationVar.set("") optionVar.trace("w", option_callback) app.mainloop() final_selected_option = optionVar.get() calibration_path = calibrationVar.get() stream_source = sourceVar.get() video_getter = "" if final_selected_option == "Laptop webcam": stream_source = int(stream_source) video_getter = VideoGet(stream_source, True) elif final_selected_option == "IP webcam": video_getter = VideoGet(stream_source, True) elif final_selected_option == "Local video": video_getter = VideoGet(stream_source, False) elif final_selected_option == "Link to stream": stream_source = streamlink.streams(stream_source)['best'].url video_getter = VideoGet(stream_source, False) return video_getter, calibration_path
import queue import sys import ffmpeg import sounddevice as sd import streamlink twitch_id = "gothamchess" streams = streamlink.streams(f"https://twitch.tv/{twitch_id}") print(f"Streams: {list(streams.keys())}") stream = streams['audio_only'] print(f"URL: {stream.url}") stream_info = ffmpeg.probe(stream.url, cmd=r'ffmpeg\ffprobe.exe') print(f"{stream_info=}") audio_streams = [ _stream for _stream in stream_info['streams'] if _stream.get('codec_type') == 'audio' ] assert len(audio_streams) == 1, f"{len(audio_streams)} stream found." audio_stream = audio_streams[0] print(f"{audio_stream=}") stream_codec_type = audio_stream.get('codec_type') assert stream_codec_type == 'audio', f"Stream must be audio, not {stream_codec_type}"
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(dst1Outputs: dict) -> str: logging.info("DownloadVideo started") ## Get all streams of the video allStreams = streamlink.streams(dst1Outputs["url"]) logging.info(f"allStreams: {len(allStreams)}") nonEmptyStreams = { k: v for k, v in allStreams.items() if not isinstance(v, MuxedStream) } logging.info(f"allStreams: {len(nonEmptyStreams)}") quals = [ 'best', '1080p', '720p', '480p', '360p', '240p', '144p', ] ## Raise error if there are no suitable video qualities if all([x not in nonEmptyStreams for x in quals]): raise ValueError("No suitable video qualities available") ## Otherwise, identify the best one while True: for q in quals: if q in nonEmptyStreams: qualToUse = q break break logging.info(f"qualToUse: {qualToUse}") stream = nonEmptyStreams[qualToUse] # outBBS = BlockBlobService( # connection_string=os.getenv("fsevideoCS") # ) blobName = f"{dst1Outputs['vidName']}.mp4" blobClient = BlobClient.from_connection_string( conn_str=os.getenv("fsevideoCS"), container_name="video-from-stream", blob_name=blobName) ## Create blob in "video-from-stream" container initially logging.info("about to create blob") fd = stream.open() blobClient.upload_blob( data=fd, overwrite=True, content_settings=ContentSettings(content_type="video/mp4")) # outBBS.create_blob_from_stream( # container_name="video-from-stream", # blob_name=blobName, # stream=fd, # max_connections=1, # # use_byte_buffer=True, # content_settings=ContentSettings( # content_type="video/mp4" # ) # ) ## Then copy blob over to "azure-video-to-image-import" container ## - this is to stop the event grid trigger firing before the whole ## blob has been created initially ## - this early triggering is just a theory, hasn't been tested but ## due to requirements to get the tool built, it was assumed this would ## cause issues copySource = f"https://fsevideos.blob.core.windows.net/video-from-stream/{blobName}" logging.info(f"copySource: {copySource}") # outBBS.copy_blob( # container_name="azure-video-to-image-import", # blob_name=blobName, # copy_source=copySource # ) blobClientCopy = BlobClient.from_connection_string( conn_str=os.getenv("fsevideoCS"), container_name="azure-video-to-image-import", blob_name=blobName) blobClientCopy.start_copy_from_url(source_url=copySource) ## Wait until copy is complete logging.info("copying started") _ = wait_for_copy(blobClientCopy) return "done"
0, 0, ]) upper_white_val = np.array([30, 15, 255]) #deep blueFor HSV, Hue range is [0,179], Saturation range is [0,255] and Value range is [0,255]. Different softwares use different scales. So if you are comparing OpenCV values with them, you need to normalize these ranges. lower_blk_val = np.array([ (155 / 255) * 179, 255 * .30, 255 * .001, ]) upper_blk_val = np.array([179, 255 * .99, 255 * .99]) # lower_Per_val=np.array([0, 200, 0,]) #upper_Per_val= np.array([100,255, 100]) streams = streamlink.streams("https://youtu.be/bNLy-XXYxcw") quality = 'best' cap = cv2.VideoCapture( 0 ) #'E:\\Utube_stock\\My Video.MP4')#'E:\\masters_Video_cap\\Pipeline.mp4')#'E:\\masters_Video_cap\\19_1_2019_5.mp4')#(streams[quality].to_url())# frame_time = int((1.0 / 30) * 1000.0) while True: try: ret, frame = cap.read() if ret: # cv2.imshow('frame', frame) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #hugh saturation value Wmask = cv2.inRange(hsv, lower_white_val, upper_white_val)
import cv2 # for image processing import time # for FPS import numpy as np import argparse # for 인자 import streamlink # for video streaming (python library) import datetime # for recording -txt file url = 'https://youtu.be/myWD76xcp5g' # using live stream video -> use url to get the video file streams = streamlink.streams( url) # live stream video is saved in this 'streams' # 인자 parser = argparse.ArgumentParser(description='Run keypoint detection') parser.add_argument("--device", default="cpu", help="Device to inference on") # 거의 픽스해서 사용 side = 1 # left:1 / right:2 -> 앉는 자세별로 위치 조정 args = parser.parse_args() MODE = "MPI" # 모드 픽스하기 if MODE is "COCO": protoFile = "pose/coco/pose_deploy_linevec.prototxt" weightsFile = "pose/coco/pose_iter_440000.caffemodel" nPoints = 18 POSE_PAIRS = [[1, 0], [1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [8, 9], [9, 10], [1, 11], [11, 12], [12, 13], [0, 14], [0, 15], [14, 16], [15, 17]] # MODE elif MODE is "MPI": protoFile = "pose/mpi/pose_deploy_linevec_faster_4_stages.prototxt"
def create_pipe(self): streamer_name = self.twitch_url.split("/")[3] try: streams = streamlink.streams(self.twitch_url) except streamlink.exceptions.NoPluginError: print("NO STREAM AVAILABLE for " + streamer_name) return False except: print("NO STREAM AVAILABLE no exception " + streamer_name) return False #print("available streams: "+ str(streams)) resolutions = { '360p': { "byte_lenght": 640, "byte_width": 360 }, '480p': { "byte_lenght": 854, "byte_width": 480 }, '720p': { "byte_lenght": 1280, "byte_width": 720 }, '1080p': { "byte_lenght": 1920, "byte_width": 1080 } } if self.res in streams: finalRes = self.res else: for key in resolutions: if key != self.res and key in streams: print("USED FALL BACK " + key) finalRes = key break else: # das else gehört zur foor loop! wenn sie nicht breaked dann wird der teil ausgeführt https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops print("COULD NOT FIND STREAM " + streamer_name) return False self.byte_lenght = resolutions[finalRes]["byte_lenght"] self.byte_width = resolutions[finalRes]["byte_width"] print("FINAL RES " + finalRes + " " + streamer_name) stream = streams[finalRes] self.stream_url = stream.url self.pipe = sp.Popen( [ 'C:/Users/ADMINS/Desktop/stream/ffmpeg-20191106-fc7b6d5-win64-static/bin/ffmpeg', "-i", self.stream_url, "-loglevel", "quiet", # no text output "-an", # disable audio "-f", "image2pipe", "-pix_fmt", "bgr24", "-vcodec", "rawvideo", "-" ], stdin=sp.PIPE, stdout=sp.PIPE) return True
from __future__ import print_function import sys import cv2 from random import randint import track_funcs as tfs import streamlink # Create a video capture object to read videos url = "https://youtu.be/9Auq9mYxFEE" # Get all possible stream qualities streams = streamlink.streams(url) #print(streams) cap = cv2.VideoCapture(streams["360p"].url) while True: ret, frame = cap.read() print(frame) cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xff == ord('q'): break cap.release() cv2.destroyAllWindows() # Read first frame success, frame = cap.read() # quit if unable to read the video file
import streamlink import cv2 import time import datetime as dt url2 = "https://www.youtube.com/watch?v=ifqYuTn_6MI" #explorer North Carolina url1 = 'https://www.youtube.com/watch?v=PbzrnUW70gU' #deerfield timeSpam = dt.datetime.now() streams = streamlink.streams(test) cap = cv2.VideoCapture(streams["best"].url) i = 0 while True: time.sleep(1) ret, frame = cap.read() if ret: cv2.imwrite("Photo%d.jpg" % i, frame) print("saving Photo%d.jpg" % i) i = i + 1 print("nothing to Save")
import streamlink from subprocess import Popen from time import sleep # get the URL of .m3u8 file that represents the stream stream_url = streamlink.streams('https://www.twitch.tv/breccoli')['best'].url print(stream_url) # now we start a new subprocess that runs ffmpeg and downloads the stream ffmpeg_process = Popen( ["ffmpeg", "-i", stream_url, "-c", "copy", 'stream.mkv']) # we wait 60 seconds sleep(120) # terminate the process, we now have ~1 minute video of the stream ffmpeg_process.kill()
def stream_downloader(name1): stream_url = streamlink.streams(streamer_link)['best'].url print(stream_url) ffmpeg_process = Popen(["ffmpeg", "-i", stream_url, "-c", "copy", name1]) time.sleep(30) ffmpeg_process.kill()
import streamlink import os.path from matplotlib import pyplot as plt def sketch_transform(image): image_grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image_grayscale_blurred = cv2.GaussianBlur(image_grayscale, (7, 7), 0) image_canny = cv2.Canny(image_grayscale_blurred, 10, 80) _, mask = image_canny_inverted = cv2.threshold(image_canny, 30, 255, cv2.THRESH_BINARY_INV) return mask streams = streamlink.streams( "https://youtu.be/DY5RYp4sxYc") #("https://youtu.be/F3Q1n_DpA9o') cam_capture = cv2.VideoCapture('C:\\Users\\RUAIRI\\Downloads\\Pipeline.mp4') cv2.destroyAllWindows() while True: _, image_frame = cam_capture.read() #cv2.imshow('stream',streams ) # upper_left = (0, 250)#works # bottom_right = (1080, 1080)#works b_upper_left = (0, 600) #works b_bottom_right = (1920, 2000) #works #Rectangle marker r = cv2.rectangle(image_frame, b_upper_left, b_bottom_right, (250, 0, 250),