Is there a way in Python / OpenCV to quickly scroll through frames of a video, letting the user select the start and end frames to process?

In preparation for processing the video, I want the user to be able to select the first and last frames to be processed in the video. The trackbard seems like a useful tool for this, but can I use it to read and display specific frames from a video?

Usually I read the video frame by frame and run my processing algorithm on it using the while loop:

cap = cv2.VideoCapture('myvideo.mp4')
while(cap.isOpened()):
    ret, frame = cap.read()
    # ....

This is not conducive to the user quickly checking the video to find a good frame interval for processing.

The trackbard is great for adjusting image processing settings, but if there is a better tool you might think about, please suggest. Below you can see the code for setting the threshold level variable using the track panel.

def onTrackbarChange(trackbarValue):
    pass

cv2.createTrackbar( 'threshold level', 'mywindow', 100, 255, onTrackbarChange )

thresholdlevel = cv2.getTrackbarPos('thresh','mywindow')

Is there a way to do something like this?

start_frame = cv2.getTrackbarPos('start-frame','mywindow')
ret, frame = cap.read(start_frame) #don't think this is possible
cv2.imshow('window', frame)

Ideally, there should be two window panels, one s start_frameand one s stop_frame, each of which is controlled by a track bar.

+3
source share
1 answer

First of all, you can set the position of the video with:

cap.set(cv2.CAP_PROP_POS_FRAMES,pos)

then it just stacks the pieces, allows them to play with the trackballs, when the key is pressed, play the interval:

import cv2
cap = cv2.VideoCapture('david.mpg')
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

def onChange(trackbarValue):
    cap.set(cv2.CAP_PROP_POS_FRAMES,trackbarValue)
    err,img = cap.read()
    cv2.imshow("mywindow", img)
    pass

cv2.namedWindow('mywindow')
cv2.createTrackbar( 'start', 'mywindow', 0, length, onChange )
cv2.createTrackbar( 'end'  , 'mywindow', 100, length, onChange )

onChange(0)
cv2.waitKey()

start = cv2.getTrackbarPos('start','mywindow')
end   = cv2.getTrackbarPos('end','mywindow')
if start >= end:
    raise Exception("start must be less than end")

cap.set(cv2.CAP_PROP_POS_FRAMES,start)
while cap.isOpened():
    err,img = cap.read()
    if cap.get(cv2.CAP_PROP_POS_FRAMES) >= end:
        break
    cv2.imshow("mywindow", img)
    k = cv2.waitKey(10) & 0xff
    if k==27:
        break
+7
source

All Articles