Black video capture with openCv

0

According to a tutorial this code helps me to capture video, also pass it in gray scale.

However, when I run it, the video display comes out in black and also the video that is saved has almost no weight (4kb).

Could someone give me a hand?

info sistema: Python 2.7 en IDE spyder. 64bits
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 21 13:22:58 2017

@author: 
"""

import cv2
import numpy as np

    cap=cv2.VideoCapture(0);
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out=cv2.VideoWriter('output.avi',fourcc,20.0,(640,480))
    while True: 
          ret , frame = cap.read()
          gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
          out.write(frame)
          cv2.imshow('frame',frame)
          try:
              out.write(frame)
          except:
              print ('ERROR - Not writting to file')
              cv2.imshow('gray',gray)
          if cv2.waitKey(0):
              break
    cap.release()
    out.release()
    cv2.destroyAllWindows()
    del(cap)
    
asked by Cristian Picon Calderon 24.07.2017 в 16:56
source

1 answer

2

The only problem that exists in the code (besides the indentation) is that you only capture one frame, wait for a key to be pressed, and when you press it, you exit the program. Your video will be a single frame.

The line in question is:

if cv2.waitKey(0):

The parameter passed to waitKey is the delay, the time in milliseconds that you must wait to see if you press a key before continuing. A value of 0 indicates that you wait forever.

The following code is perfectly functional using OpenCv 3:

import cv2

cap = cv2.VideoCapture(0);
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

while True: 
      ret, frame = cap.read()

      try:
          cv2.imshow('frame', frame)
          out.write(frame)

      except:
          print ('ERROR - Not writting to file')
          gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
          cv2.imshow('frame', gray)

      if cv2.waitKey(1) & 0xFF == ord('q'):
          break

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

Note: What this script does is capture and record the video in color, if for some reason it can not save, then it shows the video but in grayscale. The program ends when you press q .

    
answered by 24.07.2017 в 17:53