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

Question:

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()
Asked By: diegooli

||

Answers:

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)

Answered By: berak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.