Find frame when contour was detected and trim video

Frame from video file

I am new to opencv, really appreciate your help. I am trying to detect the frame number in video file when the contour was detected and trim the video file based on frame [2 frame before the contour was detected and 2 frame after contour].

mask = object_detector.apply(frame)
_, mask  = cv2.threshold(mask,254,255,cv2.THRESH_BINARY)        #mask the backgroubd to the color ratio of 255 for complete black color
contours,_ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
res = cv2.bitwise_and(frame,frame,mask=mask)

for cnt in contours:
    area = cv2.contourArea(cnt)
    if area>100:    #detect for the flashes above 1000pixel
        cv2.drawContours(frame, [cnt], -1, (0,255,0),2)

When you step through the video frame by frame, just always keep the frame two frames back from current frame. Now yiu can use that too after detection (you’ll always have two frames in memory).

That way you don’t need to know frame numbers. But if you want frame numbers, just increment a counter when you step through the video frame by frame…

Update: I am able to extract the frame number and save each frame in jpg format. Is there a way to again stitch those frame together to make the video file?