12

I want to get image from video and store it in '.jpeg' or '.png' format please help me how to do this with opencv My code is

import cv2
vidcap = cv2.VideoCapture('video1.mp4')
success,image = vidcap.read()
count = 0;
print "I am in success"
while success:
  success,image = vidcap.read()
  cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file
  if cv2.waitKey(10) == 27:                     # exit if Escape is hit
      break
  count += 1

Here i am trying to get the image from video frame by frame and save it as frame1,frame2,frame3

programminglover
  • 753
  • 3
  • 10
  • 20
  • Your code, as shown, works for me. – John1024 May 09 '15 at 05:24
  • actually i am new to python it's just generating python py.bak file for me is there any other dependency other than open cv like 'ffmpeg' – programminglover May 09 '15 at 05:49
  • Python does not generate `.bak` files. Your editor must be doing that. There are no other dependencies. From the command line, just run `python script.py` where you should replace `script.py` with whatever is the name of the file that has your code in it. OpenCV is quite verbose so don't be surprised if the code produces a lot of output on the terminal. If something were to go wrong, python will produce a stack trace. In that case, copy and paste the stack trace, in its entirety, into your question. – John1024 May 09 '15 at 07:22

2 Answers2

16

This is what I use to read in a video and save off the frames:

import cv2
import os

def video_to_frames(video, path_output_dir):
    # extract frames from a video and save to directory as 'x.png' where 
    # x is the frame index
    vidcap = cv2.VideoCapture(video)
    count = 0
    while vidcap.isOpened():
        success, image = vidcap.read()
        if success:
            cv2.imwrite(os.path.join(path_output_dir, '%d.png') % count, image)
            count += 1
        else:
            break
    cv2.destroyAllWindows()
    vidcap.release()

video_to_frames('../somepath/myvid.mp4', '../somepath/out')
Scott
  • 6,089
  • 4
  • 34
  • 51
2

This is my code for get image from video with opencv

import cv2
print(cv2.__version__)
vidcap = cv2.VideoCapture("Malar.mp4")
print vidcap.read()
success,image = vidcap.read()
count = 0
success = True
while success:
  success,image = vidcap.read()
  print 'Read a new frame: ', success
  cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file
  count += 1
Manivannan Murugavel
  • 1,476
  • 17
  • 14