2

I'm trying to resize a video input using OpenCV and export it as .avi or .mp4 file. For some unknown reason, the result file outcomes corrupted and refuses to be played.

I have tried several different combinations of video formats and codec types, such as: avi-MJPG, avi-XVID, avi-h264, avi-x264, mp4-mp4v and mp4-avc3. None of them seems to be working correctly.

import cv2

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

out = cv2.VideoWriter(
    'output.avi',
    cv2.VideoWriter_fourcc(*'XVID'),
    cap.get(cv2.CAP_PROP_FPS),
    (640, 480)
)

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    frame = cv2.resize(frame, (640, 480))
    out.write(frame)

    # cv2.imshow("video", frame)
    # cv2.waitKey(1)

cap.release()
out.release()
# cv2.destroyAllWindows()

UPD: Running this code on Windows 10 machine with Python 3.11.1, using pre-built opencv-python (4.7.0.68) and opencv-contrib-python (4.7.0.68).

As mentioned below this code works perfectly fine in another runtime environment, so probably this issue is related with OS.

4
  • 1
    The above code is working perfectly in my machine. What is the version of OpenCV, in what OS? Are you using a custom build of OpenCV? What is the Python version? For video resizing, you better use FFmpeg in command line (unless you are practicing OpenCV). You may also try different video players.
    – Rotem
    Commented Jan 7, 2023 at 9:41
  • @Rotem I was using latest pre-built opencv-python (4.7.0.68) package + opencv-contrib-python (4.7.0.68) with Python 3.11.1, running on a Windows 10 machine. Also downloaded openh264-1.8.0-win64.dll codec and put it in the working directory. This particular task requires the usage of OpenCV, not the standalone FFmpeg. Commented Jan 7, 2023 at 18:30
  • 1
    I guess this version is not ready yet... You may try using FFmpeg CLI with pipe, as in my following answer.
    – Rotem
    Commented Jan 7, 2023 at 21:24
  • @Rotem tried to run this code on another Windows machine with the same Python and OpenCV versions, and, for some reason, everything works fine and the video opens. Seems actually pretty weird for me; not really sure, but I'm guessing it's a codec issue. Can't repeat the experiment any time soon on this particular problematic platform, so the question is temporarily frozen. Thank you for your help, much appreciated. Commented Jan 10, 2023 at 21:58

0

Browse other questions tagged or ask your own question.