Python Forum
OpenCV - extract 1st frame out of a video file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: OpenCV - extract 1st frame out of a video file (/thread-13999.html)



OpenCV - extract 1st frame out of a video file - kerzol81 - Nov-10-2018

Hi All,

I'm trying to extract the first frame of a sample video file with OpenCV however it doesnt work:

import cv2

f = cv2.VideoCapture('1.mkv')

rval, frame = f.read()
cv2.imwrite('first_frame.jpg', frame)
f.release()
Could you help me out, what do I do wrong, the jpeg file is empty after running the code

Thanks

Zoli


RE: OpenCV - extract 1st frame out of a video file - Daredevil - Nov-10-2018

import cv2
import numpy as np
vidcap = cv2.VideoCapture('http://Desktop/SampleVideo_1280x720_1mb.mp4')
success,image = vidcap.read()
count = 0
while success:
  cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file      
  success,image = vidcap.read()
  print('Read a new frame: ', success)
  count += 1



RE: OpenCV - extract 1st frame out of a video file - kerzol81 - Nov-12-2018

Hi, I think it's gonna extract ALL the frames from the video file. I just need the first frame so I modified it this way:

def getFirstFrame(videofile):
    vidcap = cv2.VideoCapture(videofile)
    success, image = vidcap.read()
    if success:
        cv2.imwrite("first_frame.jpg", image)  # save frame as JPEG file
Thanks for the hint!