Search code examples
opencvmachine-learninggoogle-colaboratoryvideo-capture

Loop Iterate correctly but with video frames it work only for first four indexes


count = 1
for i in real_videonames_index:
  videofile = filed[i]
  success = True
  vidcap = cv2.VideoCapture(videofile)
  while success:
    if (count%one_frame_each == 0):
      success,image = vidcap.read()
      image_gray = rgb2gray(image)
      if image.shape[1]>640:
        tmp = resize(image_gray,(math.floor(640 / image_gray.shape[1] * image_gray.shape[0]), 640),mode='constant')
      name = '/content/drive/MyDrive/Training/REAL/' + str(count) + '.jpg'
      print('Creating ....' + name)
      cv2.imwrite(name, image)
      print ('*', end="")
    else:
      success,image = vidcap.read()                                 
    count += 1  
  print('/n/n/n/n{} video completed successfully/n/n/n'.format(i))
  i += 1

in Simple iteration for loop work correctly but while extracting frames it work only for first three indexes?

Error After 1st videos frame capturing is below. enter image description here I am using google colab. THanks in advance.


Solution

  • Actually Error is in last frame cv2 got None values so its can be resolved by again getting frame. the correct code is.

    count = 0
    face_cascade = cv2.CascadeClassifier('/content/drive/MyDrive/Training/haarcascade_frontalface_default.xml')
    for i in real_videonames_index[51:76]:
      videofile = videonames_list[i]
      vidcap = cv2.VideoCapture(videofile)
      success,image = vidcap.read()
      while success:
        if (count%one_frame_each == 0):
          name = '/content/drive/MyDrive/Training/Validation Data/REAL/'+names[i]+ "_" + str(count) + '.jpg'
          image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
          facesBase = face_cascade.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5)
          for f in facesBase:
            x, y, w, h = [ v for v in f ]
            cv2.rectangle(image, (x,y), (x+w, y+h), (255,0,0), 3)
            face_crop = image[y:y+h, x:x+w]
            cv2.imwrite(name, face_crop)
          success,image = vidcap.read()
          print('Read a new frame: {} and with name {}'.format(success,count))
        else:      
          success,image = vidcap.read()
          print('Read a new frame: {} and with name {}'.format(success,count))
        count += 1
      print('{} Real Video Extracted Successfully'.format(i))
      i += 1