Ask Your Question

Extracting Frames Opencv Java [closed]

asked 2018-06-04 03:41:13 -0500

Borny gravatar image


i am trying to extract all frames out of a video with opencv java.

The code seems to work so far in giving me the correct number of all frames and the fps, but i just get the same first frame 4000 times.

public class VideoCap {
public static void main (String args[]){

VideoCapture cap = new VideoCapture();

    String input = "/Users/Jan/Desktop/Video/Java.mp4";
    String output = "/Users/Jan/Desktop/Video/Output";;

    int video_length = (int) cap.get(Videoio.CAP_PROP_FRAME_COUNT);
    int frames_per_second = (int) cap.get(Videoio.CAP_PROP_FPS);
    int frame_number = (int) cap.get(Videoio.CAP_PROP_POS_FRAMES);

Mat frame = new Mat();

if (cap.isOpened())
        System.out.println("Video is opened");
        System.out.println("Number of Frames: " + video_length);
        System.out.println(frames_per_second + " Frames per Second");
        System.out.println("Converting Video...");;

    while(frame_number <= video_length)
        Imgcodecs.imwrite(output + "/" + frame_number +".jpg", frame);

        System.out.println(video_length + " Frames extracted");


} }
edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by Borny
close date 2018-06-04 05:07:35.069759


you're reading only one frame ;)

berak gravatar imageberak ( 2018-06-04 03:51:29 -0500 )edit

Could you elaborate on how to get the other frames? As far as i understood it, would iterate over the frames and give me one after the other. I am not really used to java but my teacher wants it that way.

Borny gravatar imageBorny ( 2018-06-04 04:15:05 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2018-06-04 04:27:00 -0500

berak gravatar image

you have to call once for each image you want to read from the video, not only once.

also, you probably should not rely on values from CAP_PROP_POS_FRAMES or CAP_PROP_FRAME_COUNT, those might not be correct (or even supported), depending on the codec. then, while(frame_number <= video_length) is one too many. so:

int frame_number=0;
if (cap.isOpened())
    while( //the last frame of the movie will be invalid. check for it !
        Imgcodecs.imwrite(output + "/" + frame_number +".jpg", frame);
edit flag offensive delete link more

Question Tools

1 follower


Asked: 2018-06-04 03:41:13 -0500

Seen: 3,481 times

Last updated: Jun 04 '18