Reputation: 403
I am trying to get a very simple example of copying a video before I start modifying frames in the video. However, the output.avi video is a 5kb corrupted file compared to the 2.8 mb barriers.avi video. I am using OpenCV version 4.2.0 and Python version 3.7.7.
Here is the code:
import cv2
input = cv2.VideoCapture("../video/barriers.avi")
height = int(input.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(input.get(cv2.CAP_PROP_FRAME_WIDTH))
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter('../video/output5.avi', fourcc, 30, (height, width), isColor=True)
while input.isOpened():
# get validity boolean and current frame
ret, frame = input.read()
# if valid tag is false, loop back to start
if not ret:
break
else:
out.write(frame)
input.release()
out.release()
If I printed the frame shape, I get:
(480, 640, 3)
Note: None of the other stack overflow solutions have helped.
Edit: All frames display fine if cv2.imshow() is used.
Upvotes: 6
Views: 5550
Reputation: 7995
I would like to address two issues in your code:
Issue#1:: You want to create a .avi
video file. Therefore you need to initialize your fourcc as MJPG
:
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
There are certain combinations for creating a video file. For instance, if you want to create a .mp4
you initialize your fourcc as *'mp4v'
.
Issue#2: Make sure the size of the output video is the same as the input frame. For instance: you declared your Videowriter object size (height, width)
. Then your frame must be the same size:
frame = cv2.resize(frame, (height, width))
Code:
import cv2
cap = cv2.VideoCapture("output.mp4")
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter('output5.avi', fourcc, 30, (width, height), isColor=True)
while cap.isOpened():
# get validity boolean and current frame
ret, frame = cap.read()
# if valid tag is false, loop back to start
if not ret:
break
else:
frame = cv2.resize(frame, (width, height))
out.write(frame)
cap.release()
out.release()
Upvotes: 9