3

I am trying to initialize some blank frames of video and write it to a file using opencv and python in ubuntu linux. I am planning to later append in smaller video segments over the blank canvas. The typical examples only show reading a frame from some input source but I am trying to generate my own frame. Here is my code so far:

import numpy as np
import cv2
xsp=640
ysp=480
chan=3
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (xsp,ysp))
numframes = 20
videoout = []
for i in range(1,numframes):   # init frames
    frame = np.zeros((xsp,ysp,chan),np.uint8)
    videoout.append(frame)
for frame in videoout:
    out.write(frame)
out.release()

Using the code above, the video is not playable. Opening it within a video player gives an error about not being able to demultiplex content.

However, if I initialize the video frame by opening a video file and taking an existing video frame + put a black rectangle over it I am able to get valid video.

def initVideoFrame(videofile):
    cap = cv2.VideoCapture(videofile)
    ret, frame = cap.read()
    ysp,xsp,chan = frame.shape
    cv2.rectangle( frame, ( 0,0 ), ( xsp, ysp), ( 0,0,0 ), -1, 8 )
    cap.release()
    return frame

frame = initVideoFrame('s.mp4') 
ysp,xsp,chan = frame.shape
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (xsp,ysp))
numframes = 100
videoout = []
for i in range(1,numframes):   # init frames
    frame = initVideoFrame('s.mp4')
    videoout.append(frame)
for frame in videoout:
    out.write(frame)
out.release()

It seems that the frames made of array of uint8 zeros is not enough to write a valid video. I am still missing something.

user3133475
  • 2,951
  • 3
  • 13
  • 11
  • 3
    blank_image = np.zeros((height,width,3), np.uint8) – Miki Nov 27 '15 at 19:27
  • Possible duplicate of [Create a new RGB OpenCV image using Python?](http://stackoverflow.com/questions/12881926/create-a-new-rgb-opencv-image-using-python) – Miki Nov 27 '15 at 19:27
  • You need to normalize the numpy array. There is an example here : https://stackoverflow.com/questions/51914683/how-to-make-video-from-an-updating-numpy-array-in-python – juangocc Apr 03 '22 at 19:17

0 Answers0