Skip to content
Advertisement

opencv cant write video from camera on python

im trying to save a video i get from a facetime camera on mac, i manage to show the video and flip it, but when i try to save it i get no file at all, and it wont show me any error, it did use to show me an error CAP_IMAGES: can’t find starting number (in the name of file): that it was a codec error related, i installed ffmpeg as sugested on other post and i did set the codec to mp4v, still i cant write the file, i do want to write it to a file and then broadcast via web (security camera)

any idea what might be wrong? i paste my code below, thanks

here is the code im using

import cv2
import numpy as np
#import PyQt5
#from matplotlib import pyplot as pl

#hog = cv2.HOGDescriptor()
#hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
#cv2.startWindowThread()

def inc_brig(cuadro, value):
    hsv = cv2.cvtColor(cuadro, cv2.COLOR_BGR2HSV)
    h,s,v = cv2.split(hsv)
    lim = 255 - value
    v[v > lim ] = 255
    v[v <= lim] += value
    #cv2.add(hsv[:,:,2], value, hsv[:,:,2])
    final_hsv = cv2.merge((h,s,v))
    cuadro = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
    return cuadro


i = 0
for i in range(4):
    cap = cv2.VideoCapture(i)  # start the camera
    if not cap:
        pass
    else:
        print('found at ' + str(i))
        break
    
#check if the camera has been initialized
if cap.isOpened():
    pass
else:
    cap.open()
    
videocodec = cv2.VideoWriter_fourcc(*'mp4v')
salida = cv2.VideoWriter('prueba_video.mp4', videocodec, 24.0, (int(cap.get(3)), int(cap.get(4)) ) )#(int(cap.get(3)), int((cap.get(4)))))

while(cap.isOpened()):
    ret, frame = cap.read()
    if frame is None:
        print ('no frame')
    else:
        if ret == True:
            frame = cv2.flip(frame, 1)
            frame = inc_brig(frame, 40)            
            #detect people
#            boxes, weight = hog.detectMultiScale(frame, winStride=(8,8))
            #return coordinates for people boxes
#            boxes = np.array( [[x, y, x+w, y+h] for (x, y, w, h) in boxes ])
            
#            for (xA, yA, xB, yB) in boxes:
                #display boxes in color picture
#                cv2.rectangle(frame, (xA, yA), (xB, yB), (255,0,0), 2)
            #frame = cv2.line(frame,(200,20),(511,511),(220,0,0),5)  # draw lines
            #fuente = cv2.FONT_HERSHEY_COMPLEX
            #cv2.putText(frame,'Prueba motherfucker', (300,90), fuente, 1, (255,255,255), 2, cv2.LINE_AA)
            #frame = cv2.rectangle(frame, (300,100), (800,600), (200,0,0), 3)
            salida.write(frame)     #write to file
            
            cv2.imshow('Camara opencv', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            break

cap.release()
salida.release()
cv2.destroyAllWindows()

# show image using matplot
# imagen = cv2.imread('Test_Xv.jpg',0)
# pl.imshow(imagen, cmap='gray', interpolation='bicubic')
# pl.xticks([]), pl.yticks([])
# pl.show()

# show image using standart opencv window
# cv2.imshow('image',imagen)
# k = cv2.waitKey(0) & 0xFF
# if k == 27:
#     cv2.destroyAllWindows()
# else:
#     cv2.imwrite('Test_Gray.jpg', imagen)
#     cv2.destroyAllWindows()

Edit1: i did follow Christof advice and be more especific when opening the device, still i get the same behaivior i would try also using a debugger and see where the problem is, below is my new code

#check if the camera has been initialized
i = 0
for i in range(4):
    cap = cv2.VideoCapture(i)  # start the camera
    if cap.isOpened():
        print('found at ' + str(i))
        break
    if cap.isOpened() == False:
        cap.open()
        print('opening camera ' + str(i))
        break

Edit2: simplyfied the code and set only first device i only get 0 anyway, heres my code using if not cap.isOpened()

cap = cv2.VideoCapture(0)  # start the camera
videocodec = cv2.VideoWriter_fourcc(*'MP4V')
salida = cv2.VideoWriter('prueba_video.mp4', videocodec, 24.0, (int(cap.get(3)), int(cap.get(4)) ) )#(int(cap.get(3)), int((cap.get(4)))))

if not cap.isOpened():
    print('not open')
else:
    while(cap.isOpened()):
        ret, frame = cap.read()
        if frame is None:
            print ('no frame')
        else:
            if ret == True:
                frame = cv2.flip(frame, 1)
                frame = inc_brig(frame, 30)   
                salida.write(frame)     #write to file
                cv2.imshow('Camara opencv', frame)
                if cv2.waitKey(1) & 0xFF == ord('q'):
                   break
            else:
                break

    cap.release()
    salida.release()
    cv2.destroyAllWindows()

Edit3: posting the general config for opencv on my machine, i did installed using pip command from terminal but before that i updated homebrew, for some reason homebrew erased all previuos stuff i had installed via pip so i had to reinstall opencv, wheels and all other stuff, im posting my modules as well

General configuration for OpenCV 4.6.0 =====================================
  Version control:               unknown

  Platform:
    Timestamp:                   2022-08-16T23:32:48Z
    Host:                        Darwin 17.7.0 x86_64
    CMake:                       3.24.0
    CMake generator:             Ninja
    CMake build tool:            /usr/local/bin/ninja
    Configuration:               Release

  CPU/HW features:
    Baseline:                    SSE SSE2 SSE3 SSSE3 SSE4_1
      requested:                 DETECT
    Dispatched code generation:  SSE4_2 FP16 AVX AVX2 AVX512_SKX
      requested:                 SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX
      SSE4_2 (1 files):          + POPCNT SSE4_2
      FP16 (0 files):            + POPCNT SSE4_2 FP16 AVX
      AVX (4 files):             + POPCNT SSE4_2 AVX
      AVX2 (31 files):           + POPCNT SSE4_2 FP16 FMA3 AVX AVX2
      AVX512_SKX (5 files):      + POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX

  C/C++:
    Built as dynamic libs?:      NO
    C++ standard:                11
    C++ Compiler:                /Library/Developer/CommandLineTools/usr/bin/c++  (ver 10.0.0.10001044)
    C++ flags (Release):         -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Wno-long-long -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections  -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
    C++ flags (Debug):           -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Wno-long-long -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections  -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
    C Compiler:                  /Library/Developer/CommandLineTools/usr/bin/cc
    C flags (Release):           -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Wno-long-long -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections  -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
    C flags (Debug):             -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Wno-long-long -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections  -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
    Linker flags (Release):      -Wl,-dead_strip  
    Linker flags (Debug):        -Wl,-dead_strip  
    ccache:                      NO
    Precompiled headers:         NO
    Extra dependencies:          -framework OpenCL /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Accelerate.framework -lm -ldl -framework Cocoa -framework AppKit
    3rdparty dependencies:       libprotobuf ade ittnotify libjpeg-turbo libwebp libpng libtiff libopenjp2 IlmImf zlib quirc ippiw ippicv

  OpenCV modules:
    To be built:                 calib3d core dnn features2d flann gapi highgui imgcodecs imgproc ml objdetect photo python3 stitching video videoio
    Disabled:                    world
    Disabled by dependency:      -
    Unavailable:                 java python2 ts
    Applications:                -
    Documentation:               NO
    Non-free algorithms:         NO

  GUI:                           COCOA
    Cocoa:                       YES
    VTK support:                 NO

  Media I/O: 
    ZLib:                        build (ver 1.2.12)
    JPEG:                        build-libjpeg-turbo (ver 2.1.2-62)
    WEBP:                        build (ver encoder: 0x020f)
    PNG:                         build (ver 1.6.37)
    TIFF:                        build (ver 42 - 4.2.0)
    JPEG 2000:                   build (ver 2.4.0)
    OpenEXR:                     build (ver 2.3.0)
    HDR:                         YES
    SUNRASTER:                   YES
    PXM:                         YES
    PFM:                         YES

  Video I/O:
    DC1394:                      NO
    FFMPEG:                      NO
      avcodec:                   NO
      avformat:                  NO
      avutil:                    NO
      swscale:                   NO
      avresample:                NO
    GStreamer:                   NO
    AVFoundation:                YES

  Parallel framework:            GCD

  Trace:                         YES (with Intel ITT)

  Other third-party libraries:
    Intel IPP:                   2020.0.0 Gold [2020.0.0]
           at:                   /private/var/folders/l9/04v9rl9d67q6pyg1n0jyjj9r0000gn/T/pip-install-mkqzz7zw/opencv-python_36a66675c7174c558792570d56da2f92/_skbuild/macosx-10.13-x86_64-3.10/cmake-build/3rdparty/ippicv/ippicv_mac/icv
    Intel IPP IW:                sources (2020.0.0)
              at:                /private/var/folders/l9/04v9rl9d67q6pyg1n0jyjj9r0000gn/T/pip-install-mkqzz7zw/opencv-python_36a66675c7174c558792570d56da2f92/_skbuild/macosx-10.13-x86_64-3.10/cmake-build/3rdparty/ippicv/ippicv_mac/iw
    Lapack:                      YES (/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Accelerate.framework -lm -ldl)
    Eigen:                       YES (ver 3.4.0)
    Custom HAL:                  NO
    Protobuf:                    build (3.19.1)

  OpenCL:                        YES (no extra features)
    Include path:                NO
    Link libraries:              -framework OpenCL

  Python 3:
    Interpreter:                 /usr/local/Cellar/python@3.10/3.10.6_1/bin/python3.10 (ver 3.10.6)
    Libraries:                   /usr/local/opt/python@3.10/Frameworks/Python.framework/Versions/3.10/lib/libpython3.10.dylib (ver 3.10.6)
    numpy:                       /usr/local/Cellar/python@3.10/3.10.6_1/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/include (ver 1.23.2)
    install path:                python/cv2/python-3

  Python (for build):            /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7

  Java:                          
    ant:                         NO
    JNI:                         /Library/Java/JavaVirtualMachines/jdk-13.0.2.jdk/Contents/Home/include /Library/Java/JavaVirtualMachines/jdk-13.0.2.jdk/Contents/Home/include/darwin /Library/Java/JavaVirtualMachines/jdk-13.0.2.jdk/Contents/Home/include
    Java wrappers:               NO
    Java tests:                  NO

  Install to:                    /private/var/folders/l9/04v9rl9d67q6pyg1n0jyjj9r0000gn/T/pip-install-mkqzz7zw/opencv-python_36a66675c7174c558792570d56da2f92/_skbuild/macosx-10.13-x86_64-3.10/cmake-install
-----------------------------------------------------------------

this are the modules installed by python via terminal

Package         Version
--------------- --------
cmake           3.24.0
cycler          0.11.0
Cython          0.29.32
distro          1.7.0
ffmpeg          1.4
ffmpeg-python   0.2.0
fonttools       4.35.0
future          0.18.2
kiwisolver      1.4.4
matplotlib      3.5.3
numpy           1.23.2
opencv-python   4.6.0.66
packaging       21.3
Pillow          9.2.0
pip             22.2.2
protobuf        4.21.5
pyparsing       3.0.9
python-dateutil 2.8.2
scikit-build    0.15.0
setuptools      63.4.3
six             1.16.0
TBB             0.2
wheel           0.37.1

Advertisement

Answer

Instantiation of a VideoWriter appears to have failed. You say salida.isOpened() returns False.

VideoWriter usually requires that OpenCV was built with support for ffmpeg. Other backends, such as AVFoundation, commonly are only used to access video cameras.

Since your OpenCV was built without support for ffmpeg, your only option is to use the .avi video container format and the MJPG codec/fourcc. Those two are built into OpenCV and always available.

If you haven’t already got OpenCV for Python from PyPI, via the opencv-python package (or one of its variants), then you should try that. It’s the official OpenCV package for Python.

If you are willing to build OpenCV yourself, you can enable and disable features, and third-party dependencies, in the CMake configuration stage.

Advertisement