2

My code is meant to loop through an existing video on file frame by frame and add some text to each frame before writing each image frame to a new file, that should be a video. Additionally, I am adding these images within the loop(one image written to file per iteration of while loop) VS writing all the images at one time at the end of the code.

The final video will be the same as the input video but with some text on them. The code as is does not crash but the output mp4 file says QuickTime cannot open it when I try on my mac and it does not appear to be writing correctly. Here is my code:

cap = cv2.VideoCapture('me_ballin.mov')

fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case
out = cv2.VideoWriter('OUTPUT_PLEASE.mp4', fourcc, 20.0, (640, 640))

while cap.isOpened():
     ret, img = cap.read()
     font                   = cv2.FONT_HERSHEY_SIMPLEX
     bottomLeftCornerOfText = (100,250)
     fontScale              = 2
     fontColor              = (255,255,255)
     lineType               = 2
     photo_text = "BALLINNNN"

     cv2.putText(img, photo_text,
                 bottomLeftCornerOfText,
                 font,
                 fontScale,
                 fontColor,
                 lineType)
     out.write(img)

As I said, when I run the code it does not crash but the output file OUTPUT_PLEASE.mp4 cannot be opened. Thoughts?

sometimesiwritecode
  • 2,993
  • 7
  • 31
  • 69

1 Answers1

3

Maybe you should set Output size equal to size of the Input.

#!/usr/bin/python3
import cv2

## opening videocapture
cap = cv2.VideoCapture(0)

## some videowriter props
sz = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))

fps = 20
#fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
#fourcc = cv2.VideoWriter_fourcc('m', 'p', 'e', 'g')
fourcc = cv2.VideoWriter_fourcc(*'mpeg')

## open and set props
vout = cv2.VideoWriter()
vout.open('output.mp4',fourcc,fps,sz,True)

cnt = 0
while cnt<20:
    cnt += 1
    print(cnt)
    _, frame = cap.read()
    cv2.putText(frame, str(cnt), (10, 20), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,0), 1, cv2.LINE_AA)
    vout.write(frame)

vout.release()
cap.release()

The result:

enter image description here

Kinght 金
  • 17,681
  • 4
  • 60
  • 74
  • Thanks! I pasted this code as is and it ran but gave the following warnings in the terminal: OpenCV: FFMPEG: tag 0x6765706d/'mpeg' is not supported with codec id 2 and format 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v' the mp4 ouput still does not open, presumably for a reason to do with this warning. any idea? – sometimesiwritecode Jan 11 '18 at 05:41
  • got it working by changing to cv2.VideoWriter_fourcc(*'mp4v') – sometimesiwritecode Jan 11 '18 at 05:45