R.Zane
R.Zane

Reputation: 340

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.

Upvotes: 7

Views: 19388

Answers (3)

I had the same problem with OpenCV C++ in Ubuntu ubuntu 18.04. I was processing a video (converting to grayscale and then generating a "paint" effect).

I solved the problem successfully doing the following steps:

  1. Use the VideoWriter with the following line:
    VideoWriter videoWriter("effect.avi", VideoWriter::fourcc('m','p','4','v'), 15.0, Size(ancho, alto), true);
  1. Convert the image (in my case was in grayscale) to BGR (do the same in case that your image is in RGB color space):
    Mat finalImage;
    cvtColor(imgEffect,finalImage,COLOR_GRAY2BGR);
    videoWriter.write(finalImage);

After the execution, the code generates the video without problems.

You can found my code in the following link: Example Code in C++

Upvotes: 1

Peyman habibi
Peyman habibi

Reputation: 820

Try this sample code : it works for me:

from __future__ import print_function
import numpy as np
import imutils
import time
import cv2




output = 'example.avi'
video = 'output.mp4'
fps = 33
codec ='MJPG'


vs = cv2.VideoCapture(video)
time.sleep(2.0)
# initialize the FourCC, video writer, dimensions of the frame, and
# zeros array
fourcc = cv2.VideoWriter_fourcc(*codec)
writer = None
(h, w) = (None, None)
zeros = None

while True:

    ret, frame = vs.read()
    if ret==True:
        frame = imutils.resize(frame, width=300)
    # check if the writer is None
    else:
        break
    if writer is None:

        (h, w) = frame.shape[:2]
        writer = cv2.VideoWriter(output, fourcc, fps,
            (w * 2, h * 2), True)
        zeros = np.zeros((h, w), dtype="uint8")

    (B, G, R) = cv2.split(frame)
    R = cv2.merge([zeros, zeros, R])
    G = cv2.merge([zeros, G, zeros])
    B = cv2.merge([B, zeros, zeros])

    output = np.zeros((h * 2, w * 2, 3), dtype="uint8")
    output[0:h, 0:w] = frame
    output[0:h, w:w * 2] = R
    output[h:h * 2, w:w * 2] = G
    output[h:h * 2, 0:w] = B

    writer.write(output)

    (B, G, R) = cv2.split(frame)
    R = cv2.merge([zeros, zeros, R])
    G = cv2.merge([zeros, G, zeros])
    B = cv2.merge([B, zeros, zeros])

    output = np.zeros((h * 2, w * 2, 3), dtype="uint8")
    output[0:h, 0:w] = frame
    output[0:h, w:w * 2] = R
    output[h:h * 2, w:w * 2] = G
    output[h:h * 2, 0:w] = B

    writer.write(output)

    cv2.imshow("Frame", frame)
    cv2.imshow("Output", output)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("q"):
        break

print("[INFO] cleaning up...")
cv2.destroyAllWindows()
vs.release()
writer.release()

Upvotes: 1

Ha Bom
Ha Bom

Reputation: 2917

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))

Upvotes: 7

Related Questions