Boto3 Kinesis Video GetMedia and OpenCV - python

I'm trying to use Boto3 to get a video stream from kinesis and then use OpenCV to display the feed and save it to a file at the same time.
The process of getting the signed URL and then the Getmedia request seems to work perfectly it's just when I'm trying to render it using OpenCV it doesn't seem to work.
Data is defiantly going to the stream
import boto3
import numpy as np
import cv2
kinesis_client = boto3.client('kinesisvideo',
region_name='eu-west-1',
aws_access_key_id='ACC',
aws_secret_access_key='KEY'
)
response = kinesis_client.get_data_endpoint(
StreamARN='ARN',
APIName='GET_MEDIA'
)
video_client = boto3.client('kinesis-video-media',
endpoint_url=response['DataEndpoint']
)
stream = video_client.get_media(
StreamARN='ARN',
StartSelector={'StartSelectorType': 'NOW'}
)
# print(stream)
datafeed = stream['Payload'].read()
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(True):
ret, frame = stream['Payload'].read()
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()

To finally answer this I found a basic solution using the HLS Output available form kineses video streams. Which became available JUL 2018
Blog post: https://aws.amazon.com/blogs/aws/amazon-kinesis-video-streams-adds-support-for-hls-output-streams/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+AmazonWebServicesBlog+%28Amazon+Web+Services+Blog%29
Ive pasted the working version of my code below.
Im using AWS ENV varables for the BOTO3 authtication.
import boto3
import cv2
STREAM_NAME = "test-stream"
kvs = boto3.client("kinesisvideo")
# Grab the endpoint from GetDataEndpoint
endpoint = kvs.get_data_endpoint(
APIName="GET_HLS_STREAMING_SESSION_URL",
StreamName=STREAM_NAME
)['DataEndpoint']
print(endpoint)
# # Grab the HLS Stream URL from the endpoint
kvam = boto3.client("kinesis-video-archived-media", endpoint_url=endpoint)
url = kvam.get_hls_streaming_session_url(
StreamName=STREAM_NAME,
PlaybackMode="LIVE"
)['HLSStreamingSessionURL']
vcap = cv2.VideoCapture(url)
while True:
# Capture frame-by-frame
ret, frame = vcap.read()
if frame is not None:
# Display the resulting frame
cv2.imshow('frame',frame)
# Press q to close the video windows before it ends if you want
if cv2.waitKey(22) & 0xFF == ord('q'):
break
else:
print("Frame is None")
break
# When everything done, release the capture
vcap.release()
cv2.destroyAllWindows()
print("Video stop")

Related

Occurred error : CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638

I'm a beginner for python.
as below code. I need to record vedio,but after run code. it not show the image.
please help me
python 3.9
opencv 4.6
import cv2
cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
result = cv2.VideoWriter('Output.avi', fourcc, 60.0,(640,480))
while (cap.isOpened()): # check Video
check , frame = cap.read()
if check == True :
cv2.imshow("Output", frame)
result.write(frame)
if cv2.waitKey(1) & 0xFF == ord("e"):
break
result.release()
cap.release()
cv2.destroyAllWindows()
I try to check camera device. so i open them by application. it can work normally

How to make pyttsx3 stop talking in real-time video capturing in python

The code below shows the face and produces an output using voices. The problem is I'm unable to stop the voices, I want it to say it only once not for each frame taken
P.S I've tried using a timer but it didn't work.
import cv2
import pyttsx3
cap = cv2.VideoCapture(0)
voiceEngine = pyttsx3.init()
while(True):
# Capture frame-by-frame
success, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if success:
voiceEngine.say("hello there")
voiceEngine.runAndWait()
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == 27:
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
This is what flags are for.
said = False
while True:
...
if success and not said:
voiceEngine.say("hello there")
voiceEngine.runAndWait()
said = True

Opencv read function not able to read some mp4 videos but can read other mp4 videos

I have two different MP4 videos, I can read one of them through cv2.read but can't read the other video.
I have tried storing both the videos at same location.
import numpy as np
import cv2
# Capture video from file
cap = cv2.VideoCapture('GP190763.MP4')
print(cap.get(3))
print(cap.isOpened())
while True:
ret, frame = cap.read()
print(frame)
print(ret)
if ret == True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#cv2.imshow('frame',gray)
if cv2.waitKey(30) & 0xFF == ord('q'):
break
else:
break
cap.release()
"ret" variable is false for one of the videos and True for the other video.
I have double checked that both videos are MP4 videos.
Any other properties of video I should be comparing ?

OpenCV video not getting saved

I am trying to save a video in OpenCV but i keep getting the error "could not demultiplex stream". I then checked size and found out that it was in kB. I primarily want to save grayscale videos how do i make it possible?
Is there any specific codec i need to use?
mplayer gives the following output
MPlayer 1.1-4.8 (C) 2000-2012 MPlayer Team
mplayer: could not connect to socket
mplayer: No such file or directory
Failed to open LIRC support. You will not be able to use your remote control.
Playing output.avi.
libavformat version 54.20.4 (external)
Mismatching header version 54.20.3
AVI file format detected.
[aviheader] Video stream found, -vid 0
AVI: Missing video stream!? Contact the author, it may be a bug :(
libavformat file format detected.
[lavf] stream 0: video (mpeg4), -vid 0
VIDEO: [MP4V] 1280x720 24bpp -nan fps 0.0 kbps ( 0.0 kbyte/s)
Clip info:
encoder: Lavf54.20.4
Load subtitles in ./
Failed to open VDPAU backend libvdpau_nouveau.so: cannot open shared object file: No such file or directory
[vdpau] Error when calling vdp_device_create_x11: 1
==========================================================================
Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family
libavcodec version 54.35.1 (external)
Mismatching header version 54.35.0
Unsupported AVPixelFormat 53
Selected video codec: [ffodivx] vfm: ffmpeg (FFmpeg MPEG-4)
==========================================================================
Audio: no sound
Starting playback...
V: 0.0 0/ 0 ??% ??% ??,?% 0 0
Exiting... (End of file)
Right now i tried with multiple codec formats
import imutils
import cv2
import numpy as np
interval = 30
outfilename = 'output.avi'
threshold=100.
fps = 10
cap = cv2.VideoCapture("video.mp4")
ret, frame = cap.read()
height, width, nchannels = frame.shape
fourcc = cv2.cv.CV_FOURCC(*'DIVX')
out = cv2.VideoWriter( outfilename,fourcc, fps, (width,height))
ret, frame = cap.read()
frame = imutils.resize(frame, width=500)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
while(True):
frame0 = frame
ret, frame = cap.read()
frame = imutils.resize(frame, width=500)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
if not ret:
deletedcount +=1
break
if np.sum( np.absolute(frame-frame0) )/np.size(frame) > threshold:
out.write(frame)
else:
print "Deleted"
cv2.imshow('Feed - Press "q" to exit',frame)
key = cv2.waitKey(interval) & 0xFF
if key == ord('q'):
print('received key q' )
break
cap.release()
out.release()
print('Successfully completed')
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
out = cv2.VideoWriter('output.avi',-1, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret:
gray = cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2GRAY)
out.write(gray)
cv2.imshow('frame', gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
Try this one
Select Intel iyuv codec.
The out.avi is non working file.
The output.avi is new working file.
If video is not getting saved, possibly the reason may be its capture size which is hardcoded as (640,480).
You can try the below code:
cap = cv2.VideoCapture(0)
fourcc_codec = cv2.VideoWriter_fourcc(*'XVID')
fps = 20.0
capture_size = (int(cap.get(3)), int(cap.get(4)))
out = cv2.VideoWriter("output.avi", fourcc_codec, fps, capture_size)
You can also check if you are passing the correct shape, do it like this:
h, w, _ = frame.shape
size = (w, h)
out = cv2.VideoWriter('video.avi', cv2.VideoWriter_fourcc(*'XVID'), 30, size)

Taking snapshot with a webcam (either external or internal) with python using opencv

am new here and also new to opencv.
I have this project at hand - designing an application that is able to interface with my computer webcam and take snapshot and also record videos.
So far so good this as far as I can go
import cv2 as cv
import numpy
cv.namedWindow ("camera", 1)
capture = cv.VideoCapture (0)
while True:
ret, frame = capture.read ()
img = cv.cvtColor (frame, cv.COLOR_BGR2BGRA)
cv.imshow ("camera", img)
if cv.waitKey(10) & 0XFF == ord ("q")
break
capture.release ()
cv.destroyAllWindows ()
Now I think am suppose to use cv.VideoCapture.grab ()
And cv.VideoCapture.retrieve ()
But honestly I don't know how am gonna use.
Please I need your HELP
There's a great example of how to do that here:
http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html
The example below will take a snapshot every 30 seconds and save it to a file with a unique timestamp:
import cv2 as cv
import time
import datetime
cv.namedWindow("camera", 1)
capture = cv.VideoCapture(0)
while True:
ret, frame = capture.read ()
frame = cv.cvtColor (frame, cv.COLOR_BGR2BGRA)
file = "C:\Python34\CpV\%s.png" % datetime.datetime.now().strftime("%d-%m-%y--%H-%M-%S")
cv.imwrite (file, frame)
#cv.imshow("camera", frame)
time.sleep(30)
capture.release()
cv.destroyAllWindows ()
Use code below to record webcam capture to file :
import cv2
import cv
cap = cv2.VideoCapture(0)
ret,img=cap.read()
height , width , layers = img.shape
fps=20
video = cv2.VideoWriter("rec_out.avi", cv.CV_FOURCC(*'DIVX'), fps, (img.shape[1], img.shape[0]))
while True:
ret,img=cap.read()
height , width , layers = img.shape
video.write(img)
cv2.imshow('Video', img)
#video.write(img)
if(cv2.waitKey(10) & 0xFF == ord('b')):
break
Okay I got to edit my code and it worked
Check it out
import cv2 as cv
import time
cv.namedWindow("camera", 1)
capture = cv.VideoCapture(0)
while True:
ret, frame = capture.read ()
frame = cv.cvtColor (frame, cv.COLOR_BGR2BGRA)
file = "C:\Python34\CpV\test.png"
cv.imwrite (file, frame)
cv.imshow("camera", frame)
#it takes a snapshot when "q" is pressed and closes
the window
if cv.waitKey(10) & 0xFF == ord ('q'):
break
capture.release()
cv.destroyAllWindows ()
This is as far as I have gotten, I need to edit a little to make it short and concise.

Categories