Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV VideoWriter Not Writing to Output.avi

I'm attempting to write a simple bit of code that takes a video, crops it, and writes to an output file.

System Setup:

OS: Windows 10
Conda Environment Python Version: 3.7
OpenCV Version: 3.4.2
ffmpeg Version: 2.7.0

File Input Specs:

Codec: H264 - MPEG-4 AVC (part 10)(avc1)
Type: Video
Video resolution: 640x360
Frame rate: 5.056860

Code failing to produce output (it creates the file but doesn't write to it):

import numpy as np
import cv2

cap = cv2.VideoCapture('croptest1.mp4')

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc('F', 'M', 'P', '4')
out = cv2.VideoWriter('output.avi', fourcc, 20.0,
                      (int(cap.get(3)), int(cap.get(4))))

# Verify input shape
width = cap.get(3)
height = cap.get(4)
fps = cap.get(5)
print(width, height, fps)

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret == True:
        # from top left =frame[y0:y1, x0:x1]
        cropped_frame = frame[20:360, 0:640]

        # write the clipped frames
        out.write(cropped_frame)

        # show the clipped video
        cv2.imshow('cropped_frame', cropped_frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

Variations to fourcc and out variables tried to get codec to work:

fourcc = cv2.cv.CV_FOURCC(*'DIVX')
fourcc = cv2.VideoWriter_fourcc(*'DIVX')

out = cv2.VideoWriter('ditch_effort.avi', -1, 20.0, (640, 360))

Based on this link I should be able to refer to this fourcc reference list to determine the appropriate fourcc compression code to use. I have tried a bunch of variations, but cannot get the output file to be written. When I run the code, the #verify input shape variables print the corresponding 640, 360 and correct Frame Rate.

Can any one tell me what my issue is...would be much appreciated.

like image 431
R.Zane Avatar asked Feb 17 '19 23:02

R.Zane


1 Answers

The reason of error is the differences between the dimension of the cropped_frame (640,340) and the dimension declared in the writer (640,360).

So the writer should be:

out = cv2.VideoWriter('output.avi', fourcc, 20.0,(640,340))
like image 135
Ha Bom Avatar answered Sep 22 '22 18:09

Ha Bom