OpenCV: Couldn't read video stream from file

hello i’m testing opencv with video. I can normally capture image from camera but i think there is a codec issue cause when i save the stream from camera or when i try to load a video from a file it doesn’t work

i’m using mac os Catalina 10.15.7, python 3.8.5, ffmpeg 4.3.1

this is my code

import cv2
import numpy as np 
vid = cv2.VideoCapture('trailer.mp4')
while(vid.isOpened()):
    ret, frame = vid.read()
    cv2.imshow('frame',frame)

    k = cv2.waitKey(25)
    if k == 27:
        break

vid.release()
cv2.destroyAllWindows()

The error i get is OpenCV: Couldn’t read video stream from file

what’s the problem?? is it a codec error?

that precise string does not occur within OpenCV (edit: I was mistaken. it’s related to AVFoundation, MacOS). nor can it apply to your code. your code reads from a camera device, not a file. your code writes to a file, it doesn’t read.

please be precise and complete in the error messages you get.

sorry, i was so frustrated i pasted the previous test i made. i corrected the post! thanks

what else is printed in the terminal when that error happens?

sadly that’s the only message i get… it just append the filename after that

add this code to your code and run:

import os
print("file exists?", os.path.exists('trailer.mp4'))

ok i’m a damn stupid… i forgot I had moved the path! when i used ur code it gave me false so i realized it…

Thanks a lot…

considering im there, why does code saved from cam won’t open even if the file is saved?

many possibilities.

  • VideoWriter needs .release() at the end to finalize the file
  • the container type (mp4) and codec (XVID??) you specified aren’t possible

opencv seems to pick the avfoundation backend. it may not know what XVID is. try “MP42”, “AVC1”, “HVC1”/“HEVC”, …

import cv2
import numpy as np

cam = cv2.VideoCapture(0) #get the first webcam

####defining the codec and creating the VideoWriter Obj
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out=cv2.VideoWriter('./assets/output.avi',fourcc,20.0,(1280,960))

while(cam.isOpened()):
    ret, frame = cam.read()
    if ret==True:
        out.write(frame)
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

cam.release()
out.release()
cv2.destroyAllWindows()

this is the code (the one i posted by mistake) i can change XVID with MP42 AVC1, but what would be the file extension in the name? is there a way to check which is the right codec? i tried to check the list of codec with ffmpeg -encoders

if you want to be sure to get ffmpeg, you need to pass cv2.CAP_FFMPEG as apiPreference argument to the VideoWriter constructor

if you can get ffmpeg, I’d recommend making “.mkv” files.

A post was split to a new topic: File exists but VideoCapture fails to open