Python Forum

Full Version: OpenCV - extract 1st frame out of a video file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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
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!