Python OpenCv: How to Write text on video? output .mp4 empty - python

I would like to insert a text in a video dynamically. When I run the code below it displays a window with the text inside the video, but the .mp4 output generated file is empty (0kb)
EDIT: problem persists after right indentation
path = r'C:\\Users\\semnome\\Desktop\\automatizacoes\\m\\'
video_file = 'a.mp4'
x = True
cap = cv.VideoCapture(video_file) #cap for "Video Capture Object"
fourcc = cv.VideoWriter_fourcc(*'mp4v')
out = cv.VideoWriter('outpu2t.mp4', fourcc, 20.0, (640,480))
try:
while(True):
# Capture frames in the video
ret, frame = cap.read()
font = cv.FONT_HERSHEY_SIMPLEX
cv.putText(frame,
'TEXT ON VIDEO',
(50, 50),
font, 1,
(0, 640, 480),
2,
cv.LINE_4)
out.write(frame)
cv.imshow('video', frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()
except:
print("Video has ended.")
cap.release()
cv.destroyAllWindows()

this is simply an indentation error. (and it's got nothing to do with writing text !)
you want out.write(frame) inside the loop, not after it (currently it only writes a single frame)

Related

Failed to save video using OpenCV

Using OpenCV, I have been extracting the frames from a video and after working on the frames, I have been trying to save them to a new video file. But the new video file is not being saved properly. It gets saved as 0 KB in size and throws the following error when I try to open it.
OpenCV Error
My code is as follows:
import cv2
cap = cv2.VideoCapture("Path to source video")
out = cv2.VideoWriter("Path to save video", cv2.VideoWriter_fourcc(*"VIDX"), 5, (1000, 1200))
print(cap.isOpened())
while True:
# Capture frame-by-frame
ret, frame = cap.read()
# Write the video
out.write(frame)
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
I tried to follow the solution Can't save a video in opencv but it did not help in my case.
when saving the file, your width and height should match with frame's width and height, so in order to get the width and height of the frame automatically, use
import cv2
cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # to get width of the frame
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # to get height of the frame
out = cv2.VideoWriter("dummy_video.mp4", cv2.VideoWriter_fourcc(*"VIDX"), 5, (width, height))
print(cap.isOpened())
while True:
# Capture frame-by-frame
ret, frame = cap.read()
# Write the video
out.write(frame)
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()

cv2 video not showing using imshow, while being processed

There is a video, that is being processed. The process can be seen in console as frame processing 1/1000, 2/1000 etc. The output video has done ok, but if i want to see the results during the run, there is a grey screen - not responding (screenshot of program running).
Code, where movi is loaded:
input_movie = cv2.VideoCapture(r"test.mp4")
length = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))
fourcc = cv2.VideoWriter_fourcc(*'XVID')
output_movie = cv2.VideoWriter('myoutput_01.avi', fourcc, 29.97, (480, 360))
Code to show video duriing the run:
cv2.imshow('Video', frame)
How to see the process?
UPDATE
I used the while cycle, i just didn't want to include much code.
But here it is:
while True:
ret, frame = input_movie.read()
frame_number += 1
if not ret:
break
cv2.imshow('Video', frame)
rgb_frame = frame[:, :, ::-1]
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
Looking at what you have here; I'm not sure you understood how to deal with videos in opencv-python.
input_movie = cv2.VideoCapture(r"test.mp4")
here will open the test.mp4 video (as maybe you understood).
But now, you'll need to tell to opencv to read each frame of this video using a while function and read input_movie
In general, this is how we do:
input_movie = cv2.VideoCapture(r"test.mp4")
while (input_movie.isOpened()):
ret, frame = input_movie.read() # here we extract the frame
cv2.imshow('Video',frame) # here we display it
if cv2.waitKey(1) & 0xFF == ord('q'): # by press 'q' you quit the process
break
input_movie.release() # remove input_movie from memory
cv2.destroyAllWindows() # destroy all opencv windows
more informations here https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html

OpenCv - output video is not playing

I want to write a video using OpenCv and process every frames in different seconds.
I am using cv2.VideoWriter, but the output file shows only the first frame of my video and it is not playing. I wanted to add text on the first frame and it did it, but it doesn't continue with the rest of the video.
As you can see from the code below, it creates a new output file for the new processed video.
It does create the mp4 file, but only showing first frame with the added text and it is not playing.
Any suggestion why this is happening?
Here is my code, I am using Spyder and windows.
fps = int(round(cap.get(5)))
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_video_file,fourcc,fps,(frame_width,frame_height))
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
if ret:
if cv2.waitKey(28) & 0xFF == ord('q'):
break
if between(cap, 0, 10000):
font = cv2.FONT_HERSHEY_COMPLEX_SMALL
cv2.putText(frame,'hello',org=(10,600),fontFace=font,fontScale=10,color=(255,0,0),thickness=4)
pass
# Our operations on the frame come here
out.write(frame)
# Display the resulting frame
cv2.imshow('frame',frame)
Exactly I could not find the problem in your code because you did not give the between function. However you may try following snippet:
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
if (cap.isOpened() == False):
print("Unable to read camera feed")
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
fps = int(round(cap.get(5)))
out = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (frame_width, frame_height))
while (True):
ret, frame = cap.read()
if ret == True:
cv2.putText(frame, 'hello',
org=(10, 300),
fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=5,
color=(255, 0, 0),
thickness=4)
out.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()

Opencv write Video is running but the saved output.avi file is 0KB

I have tried different methods but none of them works.
As video is running but and file output.avi is empty.
Here is code
import cv2
vid=cv2.VideoCapture(0)
if (not vid.isOpened()):
print 'Error'
size = (int(vid.get(3)), int(vid.get(4)))
fourcc = cv2.cv.CV_FOURCC('M','J','P','G')
newVideo=cv2.VideoWriter('output.avi',fourcc,20.0,(640,360))
while(vid.isOpened()):
ret,frame=vid.read()
if ret is True:
frame=cv2.flip(frame,0)
newVideo.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1)& 0xFF==ord('q'):
break
else:
break
vid.release()
newVideo.release()
cv2.destroyAllWindows()
The problem is simple, you are reading frame but you are trying to write them in a different size.
The solution is inside of your code. You defined:
size = (int(vid.get(3)), int(vid.get(4)))
But you didn't use it as like:
newVideo=cv2.VideoWriter('output.avi',fourcc,20.0,size)
You set the sizes as manually(640,360) which is not the size of captured frames.
You need to be sure that the output frame's dimension and initialized VideoWriter dimensions are the same.
cv2.resize(frame, (640, 360))
But, I'm not sure you are using python3. Since print 'Error' and fourcc = cv2.cv.CV_FOURCC('M','J','P','G') are not python3 statements.
For python2 the answer will be:
# Add true at the and of the parameter for specifying the frames are RGB.
newVideo = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 360), True)
.
.
if ret is True:
frame=cv2.flip(frame,0)
frame = cv2.resize(frame, (640, 360)) # missing statement
newVideo.write(frame)
cv2.imshow('frame',frame)
.
.
For python3 the answer will be:
import cv2
vid = cv2.VideoCapture(0)
if not vid.isOpened():
print('Error')
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
newVideo = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 360), True)
while vid.isOpened():
ret, frame = vid.read()
if ret:
frame = cv2.flip(frame, 0)
frame = cv2.resize(frame, (640, 360))
newVideo.write(frame)
cv2.imshow('frame', frame)
if (cv2.waitKey(1) & 0xFF) == ord('q'):
break
else:
break
cv2.destroyAllWindows()
vid.release()
newVideo.release()

How to record and save a video using OpenCV and Python?

I have taken the following code from this website.
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'avc1')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
while cap.isOpened():
ret, frame = cap.read()
if ret:
out.write(frame)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
The problem I am facing is that the video is being stored, but I am not able to open it. The video size is about 6KB, but the duration is 0 seconds. How can I fix this?
I did check the other questions similar to this, but none of them solve the issue I am facing.
I had problem with opening file if I saved frames with wrong size.
If camera gives frame with size ie. (800, 600) then you have to write with the same size (800, 600) or you have to use CV to resize frame to (640, 480) before you save it.
frame = cv2.resize(frame, (640, 480))
Full code
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'avc1') #(*'MP42')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
while cap.isOpened():
ret, frame = cap.read()
if ret:
frame = cv2.resize(frame, (640, 480))
out.write(frame)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
Example on GitHub: furas/python-examples/cv2/record-file
One thing that I found out after much googling was that the VideoWriter fails silently.
In my case, I didn't have a VideoCapture object, but a list of frames. I followed the guide similar to what you have done, but the problem was that I was passing in the shapes of the array according to what img.shape[:2] was giving me. IIRC, OpenCV has a different ordering of the widths and heights than numpy arrays do which was the source of my problem. See below for the comment from here
As have been stated by #pstch, when creating VideoWriter in Python one should pass frame dimensions in form cv.VideoWriter(filename, fourcc, fps, (w, h), ...). And when creating frame itself - in reverse order: frame = np.zeros((h, w), ...)

Categories

Resources