get frame from video with CV_CAP_PROP_POS_FRAMES in opencv python

5.1k Views Asked by At

I am trying to detect a (photography) flash in a video using OpenCV.

I detected the frame in which the flash occurs (average brightness above a threshold) and now I'd like to get the frame number.

I tried using CV_CAP_PROP_POS_FRAMES from the OpenCV docs without any success.

import numpy as np 
import cv2

cap = cv2.VideoCapture('file.MOV')

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

    BW = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    h,s,v = cv2.split(hsv)
    average = np.average(v) #computes the average brightness

    if average > 200: #flash is detected
        cv2.imshow('frame',BW)
        frameid = cap.get(CV_CAP_PROP_POS_FRAMES) # <--- this line does not work 
        print(frameid)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Any tips ?

2

There are 2 best solutions below

1
On BEST ANSWER

From opencv-doc:

When querying a property that is not supported by the backend used by the VideoCapture class, value 0 is returned

Probably it is not supported. In that case you have to count the frame number yourself.

0
On

You can either:

  1. Use cap.get(cv2.CAP_PROP_POS_FRAMES) (see here, also), or
  2. increment a variable at each iteration: its current value is the current frame number