How to to play videos from the web using Opencv and python - python

am looking devolop something simply with opencv.Am looking to play videos from the web using opencv the way you can play videos from your laptop by passing the location path now a trying to pass the video url and get it to play.so far am getting error any suggestion would be nice.
import cv2
import numpy as np
import urllib3
http = urllib3.PoolManager()
r = http.request('Get','https://www.youtube.com/watch?v=NWdrO4BoCu8&list=RDNWdrO4BoCu8&start_radio=1')
cap = cv2.VideoCapture('https://www.youtube.com/watch?v=NWdrO4BoCu8&list=RDNWdrO4BoCu8&start_radio=1')
if (cap.isOpened()== False):
print("Error opening video file")
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
cv2.imshow('Frame', frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
else:
break
cap.release()
cv2.destroyAllWindows()

Here you can use pafy to download the video, then use OpenCV to play the video.
url = 'https://youtu.be/W1yKqFZ34y4'
vPafy = pafy.new(url)
play = vPafy.getbest(preftype="webm")
#start the video
cap = cv2.VideoCapture(play.url)
while (True):
ret,frame = cap.read()
"""
your code here
"""
cv2.imshow('frame',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
resources for installation:
https://pypi.org/project/pafy/

Related

How to Convert Open-CV frames to m3u8 streams?

I am reading an rtsp(local rtsp link) stream from my cctv camera connected on LAN.
My Main Goal :-
I want to perform some processing on the frames and want to display via m3u8 in real time or nearly real time so that i can display in the frontend using hls.js.
Currently i am trying to create video in realtime so that using ffmpeg i can create the m3u8 .
Sharing my code below.
import cv2
from moviepy.editor import *
import numpy as np
import time
url = "rtsp://username:password#192.168.1.100:10554/Streaming/channels/401"
cap = cv2.VideoCapture(url)
def make_video_file(clips):
try:
print(f"clips = {clips}")
video_clip = concatenate_videoclips(clips,method='compose')
video_clip.write_videofile("video-output.mp4",fps=30)
except Exception as e:
print(e)
FRAME_COUNTER = 0
NUMBER_OF_FRAMES = 30
CLIPS = [0 for i in range(NUMBER_OF_FRAMES)]
while True:
ret, frame = cap.read()
# print(frame)
if not ret:
continue
CLIPS.pop(0)
CLIPS.append(ImageClip(frame).set_duration(1))
if FRAME_COUNTER == NUMBER_OF_FRAMES:
try:
FRAME_COUNTER = 0
make_video_file(CLIPS)
except:
pass
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
NUMBER_OF_FRAMES += 1
cap.release()
cv2.destroyAllWindows()

Making a sequential playlist of videos in python

I'm trying to run a visual behaviour experiment where a whole heap of videos in a folder play one after another. I need to do this in python because I have a TTL pulse generator which I need to run at the start and end of each video.
I'm using cv2 and to try and play the videos but for reasons I can't figure out, I can't get them to play sequentially
Attached is my code
import cv2
import os
import random
videofolderPath = '/folderwithfiles'
videos = []
playlist = []
for file in os.listdir(videofolderPath):
if file.lower().endswith(".mp4"):
path=os.path.join('/folderwithfiles/',file)
playlist.append(path)
random.shuffle(playlist)
for i in range (3):
i += 1
cap = cv2.VideoCapture(playlist[i])
print(playlist[i])
while(True):
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q') or ret==False :
cap.release()
cv2.destroyAllWindows()
break
cv2.imshow('frame',frame)
cap.release()
cv2.destroyAllWindows()
The issue I'm having is I think they're all playing at once. When I press q I do see another video behind it but am struggling to get them to play one after another.
It looks like you have an error because you try to show the video before testing if ret == False.
Also, you should update i at the end of the loop as python indexing is zero based
The fix would look like this: (note that I changed the video folder path to test your code)
import cv2
import os
import random
videofolderPath = './videos'
videos = []
playlist = []
for file in os.listdir(videofolderPath):
if file.lower().endswith(".mp4"):
path = os.path.join(videofolderPath, file)
playlist.append(path)
random.shuffle(playlist)
for i in range(3):
cap = cv2.VideoCapture(playlist[i])
print(playlist[i])
while True:
ret, frame = cap.read()
# REMOVE cv2.imshow(f'frame_{i}', frame)
if cv2.waitKey(1) & 0xFF == ord('q') or ret == False:
cap.release()
cv2.destroyAllWindows()
break
cv2.imshow('frame', frame)
cap.release()
cv2.destroyAllWindows()
i += 1 # UPDATE INDEX AT THE END
A better way of writing your code would be something like this:
import cv2
import os
if __name__ == '__main__':
video_folder = "./videos"
for video_name in os.listdir(video_folder):
if not video_name.endswith(".mp4"):
continue
video_path = os.path.join(video_folder, video_name)
video = cv2.VideoCapture(video_path)
while True:
ret, frame = video.read()
if not ret:
break
cv2.imshow("video", frame)
cv2.waitKey(1)
video.release()
cv2.destroyAllWindows()
Also, I would recommend you to look at threading to load your video in "parallel" as it is very cpu intensive

Python: Panasonic network stream not recognized using OpenCV

I am trying to read a stream from a Panasonic network camera (WV SFV481) using Python and openCV. However the stream does not seem to be recognized since cap.isOpened() returns False. Here is what I tried (The turned off lines are the different adresses I tried to capture the stream):
import cv2
#cap = cv2.VideoCapture('http://169.254.5.128:581/1')
#cap = cv2.VideoCapture('admin:12345#169.254.5.128:581/1')
#cap = cv2.VideoCapture('admin:12345#http://169.254.5.128:581/1')
#cap = cv2.VideoCapture('http://169.254.5.128:581/live/index.html?Language=9')
#cap = cv2.VideoCapture('admin:12345#169.254.5.128:581/live/index.html?Language=9')
#cap = cv2.VideoCapture('admin:12345#http://169.254.5.128:581/live/index.html?Language=9')
if cap.isOpened() == False:
print("Error File Not Found")
while cap.isOpened():
ret, frame = cap.read()
if ret == True:
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF ==ord('q'):
break
else:
break
cap.release()
cv2.destroyAllWindows()
Thanks in adnvance, I really appreciate any help!
This is how it finally worked: cap_1 = cv2.VideoCapture('http://169.254.5.128:581/cgi-bin/camera'). Here you can check what extensions you need to use in the link to acces your network camera: https://www.ispyconnect.com/

Why can't I capture with my webcam more than once with OpenCV in Python?

I tried to write a small Python program which would allow me to start the webcam and capture and save the image to a .png file:
import cv2
cap = cv2.VideoCapture(0)
for i in range(3):
ret, frame = cap.read()
cap.release()
if ret == True:
cv2.imwrite(str(i) + 'image.png', frame)
else:
print("Webcam not working")
print(ret)
but when I execute it it would only save the image once under 0image.png and then display this in the console:
Webcam not working
False
Webcam not working
False
What am I doing wrong?
The cap.release() functions helps you to free up your system , i.e. , the camera device resource, and if not done so , then it will raise errors like Device or resource busy if you try to create a new instance .
So , you need to remove the cap.release() from your loop and place it at the end of your program .
This should work .
import cv2
cap = cv2.VideoCapture(0)
for i in range(3):
ret, frame = cap.read()
if ret == True:
cv2.imwrite(str(i) + 'image.png', frame)
else:
print("Webcam not working")
print(ret)`
cap.release()

How to grayscale video stream using keyboard?

I need a python script that live stream cam and I wanna grayscale the stream using keyboard, but I can't, every time I run the blow code stream change to grayscale but after a second it return to normal, please help me to fix this
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
c = cv2.waitKey(1)
if c & 0xFF == ord('q'):
break
elif c & 0xFF == ord('3'):
frame=gray
cv2.imshow('a',frame)
cap.release()
cv2.destroyAllWindows()
I need to change it using keyboard
Your problem is with the keyboard capture. The code waits for a keyboard input every iteration of the loop, if it gets none then none is passed to the code i.e. it doesnt remember what you typed last time so your elif is not entered the next time around.
Try the following to see what is happening...
import cv2
cap = cv2.VideoCapture(0)
gray_flag = False
while True:
ret, frame = cap.read()
gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
c = cv2.waitKey(1) # only waits for 1 millisecond!!!
if c & 0xFF == ord('q'):
break
elif c & 0xFF == ord('3'):
gray_flag = True
elif c & 0xFF == ord('4'):
gray_flag = False
if gray_flag:
cv2.imshow('a', gray)
else:
cv2.imshow('a', frame)
cap.release()
cv2.destroyAllWindows()
The gray_flag ensures that your choice is remembered

Categories

Resources