The following script reads a video with OpenCV, applies a transformation to each frame and attempts to write it with ffmpeg. My problem is, that I don't get ffmpeg working with the subprocess
module. I always get the error BrokenPipeError: [Errno 32] Broken pipe
in the line where I try to write to stdin. Why is that, what am I doing wrong?
# Open input video with OpenCV
video_in = cv.VideoCapture(src_video_path)
frame_width = int(video_in.get(cv.CAP_PROP_FRAME_WIDTH))
frame_height = int(video_in.get(cv.CAP_PROP_FRAME_HEIGHT))
fps = video_in.get(cv.CAP_PROP_FPS)
frame_count = int(video_in.get(cv.CAP_PROP_FRAME_COUNT))
bitrate = bitrate * 4096 * 2160 / (frame_width * frame_height)
# Process video in ffmpeg pipe
# See http://zulko.github.io/blog/2013/09/27/read-and-write-video-frames-in-python-using-ffmpeg/
command = ['ffmpeg',
'-loglevel', 'error',
'-y',
# Input
'-f', 'rawvideo',
'-vcodec', 'rawvideo'
'-pix_fmt', 'bgr24',
'-s', str(frame_width) + 'x' + str(frame_height),
'-r', str(fps),
# Output
'-i', '-',
'-an',
'-vcodec', 'h264',
'-r', str(fps),
'-b:v', str(bitrate) + 'M',
'-pix_fmt', 'bgr24',
dst_video_path
]
pipe = sp.Popen(command, stdin=sp.PIPE)
for i_frame in range(frame_count):
ret, frame = video_in.read()
if ret:
warped_frame = cv.warpPerspective(frame, homography, (frame_width, frame_height))
pipe.stdin.write(warped_frame.astype(np.uint8).tobytes())
else:
print('Stopped early.')
break
print('Done!')
There is a missing comma after '-vcodec', 'rawvideo'
!!!
Took me about an hour to notice...
You should also close stdin
and wait before print('Done!')
:
pipe.stdin.close()
pipe.wait()