Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How Get Frame from Youtube Live Stream #73

Closed
fspider opened this issue Nov 22, 2019 · 12 comments
Closed

How Get Frame from Youtube Live Stream #73

fspider opened this issue Nov 22, 2019 · 12 comments
Labels
INVALID 🛑 This doesn't seem right or non-applicable or missing information QUESTION ❓ User asked about the working/usage of VidGear APIs. SOLVED 🏁 This issue/PR is resolved now. Goal Achieved!

Comments

@fspider
Copy link

fspider commented Nov 22, 2019

Hello
With some youtube videos,this code works.
But this code not works with these youtube live stream.

https://www.youtube.com/watch?v=17Deeq8N2e4
https://www.youtube.com/watch?v=1y5dcfnv-Ss
https://www.youtube.com/watch?v=tbLXWVhu8-Q

  1. Method
    vPafy = pafy.new(videoUrl)
    play = vPafy.getbest(preftype="mp4")
    return play.url

  2. Method
    streams = streamlink.streams(videoUrl)
    return streams["best"].url

cap = cv.VideoCapture(videoUrl)

All 2 Method not works.

The error screen like this

[ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (116) cv::VideoCapture::open VIDEOIO(CV_IMAGES): raised OpenCV exception:

OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cpp:235: error: (-5:Bad argument) CAP_IMAGES: error, expected '0?[1-9][du]' pattern, got: https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1574433696/ei/QJ_XXfqBHNOTgQOBqpGwBw/ip/222.112.215.2/id/1EiC9bvVGnk.1/itag/96/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D137/hls_chunk_host/r5---sn-3u-bh2ll.googlevideo.com/playlist_type/DVR/initcwndbps/7760/mm/44/mn/sn-3u-bh2ll/ms/lva/mv/m/mvi/4/pl/23/dover/11/keepalive/yes/fexp/23842630/mt/1574412027/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_type/sig/ALgxI2wwRAIgG6xA4SgrD4PZGAfyup1jpL003-U3CQomrURDSKrCbZQCIElX0iQYvSGuZK-aoDsbY9Zv6SVTCNHOXGoUXhPCj0bN/lsparams/hls_chunk_host,initcwndbps,mm,mn,ms,mv,mvi,pl/lsig/AHylml4wRQIhAO1AS0iv1JaOu9igx-i3uGV-52UNCvd1Kd4Fu9SSC6OqAiAVjNjYYdr37w4Id111zdRsu8csAkIAfynBOk4SEO9f3w%3D%3D/playlist/index.m3u8 in function 'cv::icvExtractPattern'

Traceback (most recent call last):
File "D:/VideoFeedProcessing/VideoFeed/main.py", line 226, in
out = cv.VideoWriter('_output.avi', fourcc, 15, (ori_wid, ori_hei))
TypeError: must be real number, not tuple
[tcp @ 000001601c64fbc0] Connection to tcp://manifest.googlevideo.com:443 failed: Error number -138 occurred

@abhiTronix abhiTronix added INVALID 🛑 This doesn't seem right or non-applicable or missing information QUESTION ❓ User asked about the working/usage of VidGear APIs. labels Nov 23, 2019
@abhiTronix
Copy link
Owner

abhiTronix commented Nov 23, 2019

@fspider All these YouTube live video URLs are working fine with vidgear, Kindly install and test testing branch by strictly following steps:


⚠️ This requires latest opencv-python or opencv-contrib-python binaries ( i.e. 4.1.1.26+)
installed on your machine. Install it from pypi as follows:

sudo pip install -U opencv-python  

For more info., see issue #14 ⚠️


 

  1. Firstly, Kindly clone and install the testing branch as follows:
git clone https://github.com/abhiTronix/vidgear.git
cd vidgear
git checkout testing
sudo pip install .
cd
  1. Then use this example code with your URLs (https://www.youtube.com/watch?v=17Deeq8N2e4) as follows:
# import libraries
from vidgear.gears import CamGear
import cv2

stream = CamGear(source='https://youtu.be/17Deeq8N2e4', y_tube = True, logging=True).start() # YouTube Video URL as input

# infinite loop
while True:
	
	frame = stream.read()
	# read frames

	# check if frame is None
	if frame is None:
		#if True break the infinite loop
		break
	
	# do something with frame here
	
	cv2.imshow("Output Frame", frame)
	# Show output window

	key = cv2.waitKey(1) & 0xFF
	# check for 'q' key-press
	if key == ord("q"):
		#if 'q' key-pressed break out
		break

cv2.destroyAllWindows()
# close output window

stream.stop()
# safely close video stream.

and see if it works, if not, then report here. Goodluck

@abhiTronix abhiTronix added the WAITING TO TEST ⏲️ Asked user to test the suggested example/binary/solution label Nov 23, 2019
@fspider
Copy link
Author

fspider commented Nov 23, 2019

C:\Users\Codem>pip install vidgear
Collecting vidgear
Using cached https://files.pythonhosted.org/packages/b4/b0/fd845d973cd15f38e1b479009bf0a005677a0375722cb0de3130bcf34c6c/vidgear-0.1.5-py2.py3-none-any.whl
Requirement already satisfied: requests in c:\python36\lib\site-packages (from vidgear) (2.22.0)
Requirement already satisfied: mss in c:\python36\lib\site-packages (from vidgear) (4.0.3)
Requirement already satisfied: pafy in c:\python36\lib\site-packages (from vidgear) (0.5.5)
Requirement already satisfied: pyzmq in c:\python36\lib\site-packages (from vidgear) (18.1.1)
Requirement already satisfied: youtube-dl in c:\python36\lib\site-packages (from vidgear) (2019.11.5)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\python36\lib\site-packages (from requests->vidgear) (3.0.4)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\python36\lib\site-packages (from requests->vidgear) (1.25.6)
Requirement already satisfied: certifi>=2017.4.17 in c:\python36\lib\site-packages (from requests->vidgear) (2019.9.11)
Requirement already satisfied: idna<2.9,>=2.5 in c:\python36\lib\site-packages (from requests->vidgear) (2.8)
Installing collected packages: vidgear
Successfully installed vidgear-0.1.5

After above install, i ran your code then i got this error

PS D:\VideoFeedProcessing\age-gender-detect> python .\c.py
ERROR: Unable to download webpage: <urlopen error [Errno 11001] getaddrinfo failed> (caused by URLError(gaierror(11001, 'getaddrinfo failed'),))
ERROR: Unable to download webpage: <urlopen error [Errno 11001] getaddrinfo failed> (caused by URLError(gaierror(11001, 'getaddrinfo failed'),))
Traceback (most recent call last):
File "C:\Python36\lib\urllib\request.py", line 1318, in do_open
encode_chunked=req.has_header('Transfer-encoding'))
File "C:\Python36\lib\http\client.py", line 1239, in request
self._send_request(method, url, body, headers, encode_chunked)
File "C:\Python36\lib\http\client.py", line 1285, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "C:\Python36\lib\http\client.py", line 1234, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "C:\Python36\lib\http\client.py", line 1026, in _send_output
self.send(msg)
File "C:\Python36\lib\http\client.py", line 964, in send
self.connect()
File "C:\Python36\lib\http\client.py", line 1392, in connect
super().connect()
File "C:\Python36\lib\http\client.py", line 936, in connect
(self.host,self.port), self.timeout, self.source_address)
File "C:\Python36\lib\socket.py", line 704, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "C:\Python36\lib\socket.py", line 745, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python36\lib\site-packages\youtube_dl\extractor\common.py", line 627, in _request_webpage
return self._downloader.urlopen(url_or_request)
File "C:\Python36\lib\site-packages\youtube_dl\YoutubeDL.py", line 2237, in urlopen
return self._opener.open(req, timeout=self._socket_timeout)
File "C:\Python36\lib\urllib\request.py", line 526, in open
response = self._open(req, data)
File "C:\Python36\lib\urllib\request.py", line 544, in _open
'_open', req)
File "C:\Python36\lib\urllib\request.py", line 504, in _call_chain
result = func(*args)
File "C:\Python36\lib\site-packages\youtube_dl\utils.py", line 2724, in https_open
req, **kwargs)
File "C:\Python36\lib\urllib\request.py", line 1320, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python36\lib\site-packages\youtube_dl\YoutubeDL.py", line 796, in extract_info
ie_result = ie.extract(url)
File "C:\Python36\lib\site-packages\youtube_dl\extractor\common.py", line 530, in extract
ie_result = self._real_extract(url)
File "C:\Python36\lib\site-packages\youtube_dl\extractor\youtube.py", line 1677, in _real_extract
video_webpage = self._download_webpage(url, video_id)
File "C:\Python36\lib\site-packages\youtube_dl\extractor\common.py", line 794, in _download_webpage
expected_status=expected_status)
File "C:\Python36\lib\site-packages\youtube_dl\extractor\youtube.py", line 273, in _download_webpage_handle
*args, **compat_kwargs(kwargs))
File "C:\Python36\lib\site-packages\youtube_dl\extractor\common.py", line 660, in _download_webpage_handle
urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal, data=data, headers=headers, query=query, expected_status=expected_status)
File "C:\Python36\lib\site-packages\youtube_dl\extractor\common.py", line 645, in _request_webpage
raise ExtractorError(errmsg, sys.exc_info()[2], cause=err)
youtube_dl.utils.ExtractorError: Unable to download webpage: <urlopen error [Errno 11001] getaddrinfo failed> (caused by URLError(gaierror(11001, 'getaddrinfo failed'),))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python36\lib\site-packages\pafy\backend_youtube_dl.py", line 40, in _fetch_basic
self._ydl_info = ydl.extract_info(self.videoid, download=False)
File "C:\Python36\lib\site-packages\youtube_dl\YoutubeDL.py", line 819, in extract_info
self.report_error(compat_str(e), e.format_traceback())
File "C:\Python36\lib\site-packages\youtube_dl\YoutubeDL.py", line 624, in report_error
self.trouble(error_message, tb)
File "C:\Python36\lib\site-packages\youtube_dl\YoutubeDL.py", line 594, in trouble
raise DownloadError(message, exc_info)
youtube_dl.utils.DownloadError: ERROR: Unable to download webpage: <urlopen error [Errno 11001] getaddrinfo failed> (caused by URLError(gaierror(11001, 'getaddrinfo failed'),))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python36\lib\site-packages\vidgear\gears\camgear.py", line 131, in init
source_object = pafy.new(url)
File "C:\Python36\lib\site-packages\pafy\pafy.py", line 124, in new
return Pafy(url, basic, gdata, size, callback, ydl_opts=ydl_opts)
File "C:\Python36\lib\site-packages\pafy\backend_youtube_dl.py", line 31, in init
super(YtdlPafy, self).init(*args, **kwargs)
File "C:\Python36\lib\site-packages\pafy\backend_shared.py", line 97, in init
self._fetch_basic()
File "C:\Python36\lib\site-packages\pafy\backend_youtube_dl.py", line 43, in _fetch_basic
raise IOError(str(e).replace('YouTube said', 'Youtube says'))
OSError: ERROR: Unable to download webpage: <urlopen error [Errno 11001] getaddrinfo failed> (caused by URLError(gaierror(11001, 'getaddrinfo failed'),))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File ".\c.py", line 4, in
stream = CamGear(source='https://youtu.be/17Deeq8N2e4', y_tube = True, logging=True).start() # YouTube Video URL as input
File "C:\Python36\lib\site-packages\vidgear\gears\camgear.py", line 143, in init
raise ValueError('YouTube Mode is enabled and the input YouTube Url is invalid!')
ValueError: YouTube Mode is enabled and the input YouTube Url is invalid!

@abhiTronix
Copy link
Owner

abhiTronix commented Nov 23, 2019

C:\Users\Codem>pip install vidgear

@fspider you are still installing and using old vidgear binaries on your windows machine. Kindly run following commands in your Powershell to install latest vidgear binaries:

wget https://github.com/abhiTronix/vidgear/archive/testing.zip -O testing.zip
Expand-Archive testing.zip
cd  testing/vidgear-testing
pip install .
cd

Or install it on Command Prompt with following command:

powershell
wget https://github.com/abhiTronix/vidgear/archive/testing.zip -O testing.zip
Expand-Archive testing.zip
cd  testing/vidgear-testing
pip install .
cd

and also install latest youtube-dl and pafy libraries as follows:

pip install -U youtube-dl pafy

Then run the example code, it must work and revert the results here.

@fspider
Copy link
Author

fspider commented Nov 23, 2019

Thanks it works well.
And then let me test on ubuntu 18.04 again.

And can you tell me if it is possible to set parameters(resolution, frame rate) like this
And about getting parameters.

CamGear(source='https://youtu.be/17Deeq8N2e4', y_tube = True, logging=True, resolution=(320, 240), framerate=20).start()

I have just tried but it not work

@abhiTronix
Copy link
Owner

@fspider Thanks for confirming.

And can you tell me if it is possible to set parameters(resolution, frame rate) like this
And about getting parameters.

CamGear(source='https://youtu.be/17Deeq8N2e4', y_tube = True, logging=True, resolution=(320, 240), framerate=20).start()

Not possible is yet. I can surely add support for changing resolution directly but we cannot change framerate of a youtube video directly as it is not possible within pafy itself. But you can certainly use vidgear's powerful WriteGear API for saving video at desired resolution and framerate easily. Read it's Wiki Documentation for example code and other details. Goodluck.

@abhiTronix abhiTronix added SOLVED 🏁 This issue/PR is resolved now. Goal Achieved! INVALID 🛑 This doesn't seem right or non-applicable or missing information and removed INVALID 🛑 This doesn't seem right or non-applicable or missing information WAITING TO TEST ⏲️ Asked user to test the suggested example/binary/solution labels Nov 23, 2019
@fspider
Copy link
Author

fspider commented Nov 23, 2019

Thanks for your kindness.
I will use this in future for writing.
But i have to reading with fps, resolution change.
Can you tell me if you know other modules similar this one....

@abhiTronix
Copy link
Owner

abhiTronix commented Nov 23, 2019

But i have to reading with fps, resolution change.

Not possible to change framerate of a YouTube video directly while reading with any python module available on the internet since Official YouTube API do not allow us to do this.

@fspider
Copy link
Author

fspider commented Nov 23, 2019

Thanks.

Then It is good with raw fps,
How can we only change resolution so that it can reduce the communication load

@abhiTronix
Copy link
Owner

abhiTronix commented Nov 23, 2019

How can we only change resolution so that it can reduce the communication load

@fspider I was looking at pafy docs and concluded that we can only set a limited number of pre-defined resolutions with Stream API for example: allstreams. So we cannot manipulate resolution as we desired also.

@fspider
Copy link
Author

fspider commented Nov 23, 2019

Thanks for you help!

@fspider
Copy link
Author

fspider commented Nov 24, 2019

Hello. Please help me one more.
Is it possible to get the FPS, Resolution information? something like this.
cap = CamGear(source='videoUrl', y_tube = True, logging=True).start() # YouTube Video URL as input
fps = cap.get(cv.CAP_PROP_FPS)
ori_wid = cap.get(cv.CAP_PROP_FRAME_WIDTH)
ori_hei = cap.get(cv.CAP_PROP_FRAME_HEIGHT)

@abhiTronix
Copy link
Owner

abhiTronix commented Nov 24, 2019

@fspider

cap = CamGear(source='videoUrl', y_tube = True, logging=True).start() # YouTube Video URL as input

# FPS:
fps = cap.framerate

#Width and height
ori_wid = cap.stream.get(cv2.CAP_PROP_FRAME_WIDTH)
ori_hei = cap.stream.get(cv2.CAP_PROP_FRAME_HEIGHT)

# to check output
print(fps)
print(ori_wid)
print(ori_hei)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
INVALID 🛑 This doesn't seem right or non-applicable or missing information QUESTION ❓ User asked about the working/usage of VidGear APIs. SOLVED 🏁 This issue/PR is resolved now. Goal Achieved!
Projects
None yet
Development

No branches or pull requests

2 participants