How to change mp4 file FPS value 30 to 5 using OpenCV - python

I want to change the framerate of an mp4 file from 30 to 5.I tried set(cv2.CAP_PROP_FPS, 10).But it did not work. I can't find a way to do this with ffmpeg. Please help me to do this.Thank you.
import cv2
cap = cv2.VideoCapture('./data/video/7e2.mp4')
fps = int(cap.get(cv2.CAP_PROP_FPS))
print('fps :'+str(fps))
if (cap.isOpened()== False):
print("Error opening video stream or 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()

If you are reading a file then file will not be modified and FPS of the original file will be unchanged. cv2.VideoCapture( ) opens file in read mode. To save a video file you need to use VideoWriter and then open the output file using
video.open(out_filename,VideoWriter::fourcc('M','P','4','V'),FPS, Size(FRAME_WIDTH,FRAME_HEIGHT),true)
And then finally use write function to enter each frame.
So your code will look like this:
cv::VideoWriter video;
video.open(out_filename,VideoWriter::fourcc('M','P','4','V'),FPS, Size(FRAME_WIDTH,FRAME_HEIGHT),true)
In loop {
... Read Each Frame
video.write(frame);
(I have given C++ code, Python code will be similar)
I am providing you the complete code. It should work.
import cv2
cap = cv2.VideoCapture('./data/video/7e2.mp4')
fps = int(cap.get(cv2.CAP_PROP_FPS))
print('fps :'+str(fps))
# Change the FPS whatever you want
FPS=5;
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
writer = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), FPS, (frame_width,frame_height) )
if (cap.isOpened()== False):
print("Error opening video stream or file")
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
cv2.imshow('Frame',frame)
writer.write( frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
else:
break
writer.release()
cap.release()
cv2.destroyAllWindows()

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

How to rewind a video in OpenCV Python in 2019?

I know there are many similar questions asked in 2012 or something.
It is 2019, and in 2012, the only solution was to store the frames in memory or write them and then read them in reverse order.
But I was wondering, if there is a new function to read OpenCV frames in reverse order.
I am looking for a solution something like this:
if rewind == False:
ret,frame = cap.read()
else:
ret,frame = cap.read(rewind=True)
Any solution similar to this one?
or something like this:
if rewind == False:
ret,frame = cap.read()
else:
cap.goBackOneFrame()
ret,frame = cap.read()
Edit:
I tried
if rewind == False:
ret, frame = cap.read() #Read frame
counter += 1
else:
cap.set(cv2.CAP_PROP_POS_FRAMES, counter-1)
counter -= 1
ret, frame = cap.read()
and it works, but the rewind speed is slow. I think my PC is taking more time in processing it?
import cv2
# Grab the current frame.
my_check , vid = cap.read()
# use counter variable for
# Counting frames
counter = 0
check = True
frame_list = []
while(check == True):
cv2.imwrite("frame%d.jpg" %counter , vid)
check , vid = cap.read()
frame_list.append(vid)
# increment the counter by 1
counter += 1
frame_list.pop()
# looping in the List of frames.
for frame in frame_list:
# show the frame.
cv2.imshow("Frame" , frame)
if cv2.waitKey(25) and 0xFF == ord("q"):
break
cap.release()
# close any open windows
cv2.destroyAllWindows()
frame_list.reverse()
for frame in frame_list:
cv2.imshow("Frame" , frame)
if cv2.waitKey(25) and 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()

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)

Categories