0

Here are my goals.

  1. Capture video continuously until 'q; is pressed
  2. Every ten seconds save the video in created directory file
  3. Continue step two until 'q' is pressed

I am executing the following code. But when creating files it's creating 6kb files and saying cannot play. I am fairly new to opencv and python. Not sure what I am missing. Running this code on pycharm with Python 3.6. Also the

cv2.imshow('frame',frame)

stops after ten seconds but recording is happening in background and files are created.

import numpy as np
import cv2
import time
import os
import random
import sys


fps=24
width=864
height=640
video_codec=cv2.VideoWriter_fourcc('D','I','V','X')

name = random.randint(0,1000)
print (name)
if (os.path.isdir(str(name)) is False):
    name = random.randint(0,1000)
    name=str(name)

name = os.path.join(os.getcwd(), str(name))
print('ALl logs saved in dir:', name)
os.mkdir(name)


cap = cv2.VideoCapture(0)
ret=cap.set(3, 864)
ret=cap.set(4, 480)
cur_dir = os.path.dirname(os.path.abspath(sys.argv[0]))


start=time.time()
video_file_count = 1
video_file = os.path.join(name, str(video_file_count) + ".avi")
print('Capture video saved location : {}'.format(video_file))


while(cap.isOpened()):
    start_time = time.time()
    ret, frame = cap.read()
    if ret==True:
        cv2.imshow('frame',frame)
        if (time.time() - start > 10):
            start = time.time()
            video_file_count += 1
            video_file = os.path.join(name, str(video_file_count) + ".avi")
            video_writer = cv2.VideoWriter(video_file,video_codec, fps,(int(cap.get(3)),int(cap.get(4))))
            time.sleep(10)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
cv2.destroyAllWindows()

I want files with the recorded videos. Files are generated but size 6kb and nothing is being recorded.

Teja8484
  • 69
  • 2
  • 10
  • See nathancy's answer at https://stackoverflow.com/questions/56759785/how-to-maintain-constant-fps-when-grabbing-frames-with-opencv-and-python/59506735 – fmw42 Dec 30 '19 at 23:24

2 Answers2

3

You're almost there! Given that I understood what your goal is, and with minimal change to your code, here is what worked for me.

This writes a new video file every ten seconds while recording each frame into the current video.

import numpy as np
import cv2
import time
import os
import random
import sys


fps = 24
width = 864
height = 640
video_codec = cv2.VideoWriter_fourcc("D", "I", "V", "X")

name = random.randint(0, 1000)
print(name)
if os.path.isdir(str(name)) is False:
    name = random.randint(0, 1000)
    name = str(name)

name = os.path.join(os.getcwd(), str(name))
print("ALl logs saved in dir:", name)
os.mkdir(name)


cap = cv2.VideoCapture(0)
ret = cap.set(3, 864)
ret = cap.set(4, 480)
cur_dir = os.path.dirname(os.path.abspath(sys.argv[0]))


start = time.time()
video_file_count = 1
video_file = os.path.join(name, str(video_file_count) + ".avi")
print("Capture video saved location : {}".format(video_file))

# Create a video write before entering the loop
video_writer = cv2.VideoWriter(
    video_file, video_codec, fps, (int(cap.get(3)), int(cap.get(4)))
)

while cap.isOpened():
    start_time = time.time()
    ret, frame = cap.read()
    if ret == True:
        cv2.imshow("frame", frame)
        if time.time() - start > 10:
            start = time.time()
            video_file_count += 1
            video_file = os.path.join(name, str(video_file_count) + ".avi")
            video_writer = cv2.VideoWriter(
                video_file, video_codec, fps, (int(cap.get(3)), int(cap.get(4)))
            )
            # No sleeping! We don't want to sleep, we want to write
            # time.sleep(10)

        # Write the frame to the current video writer
        video_writer.write(frame)
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        break
cap.release()
cv2.destroyAllWindows()
Andreas
  • 455
  • 3
  • 7
  • Thanks a lot. Got this code to work and now found the issue too. Much appreciated! – Teja8484 Mar 29 '19 at 07:02
  • I have used this code. And I only want to save the latest 30 sec of the video. Lets say if the video is 31 seconds long, then it should save only sec2 to sec 31 of the video. How can i achieve this. @Andreas – MUK Sep 09 '20 at 12:05
1

A sign that the videos are being received at 6 kb, an error with the codec. You need to download opencv_ffmpeg.dll and place it in the Python3.2.1 folder and renamed to opencv_ffmpeg321.dll

This solved the problem for me, and before that, 5.6 kb videos were created, regardless of what I do. But the problem is deeper than it seems, it can still be connected with a mismatch in the resolution of the stream and the recording.

For OpenCV version X.Y.Z opencv_ffmpeg.dll ==> opencv_ffmpegXYZ.dll

For 64-bit version of OpenCV X.Y.Z opencv_ffmpeg.dll ==> opencv_ffmpegXYZ_64.dll

Mons
  • 36
  • 4