Ask Your Question
0

Extracting Frames Opencv Java [closed]

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

Borny gravatar image

Hello,

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[]){
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

VideoCapture cap = new VideoCapture();

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

cap.open(input);

    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...");

    cap.read(frame);

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

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

}

    else
    {
        System.out.println("Fail");
    }
} }
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

Comments

you're reading only one frame ;)

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

Could you elaborate on how to get the other frames? As far as i understood it, cap.read(frame) 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 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
1

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

berak gravatar image

you have to call cap.read() 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(cap.read(frame)) //the last frame of the movie will be invalid. check for it !
    {
        Imgcodecs.imwrite(output + "/" + frame_number +".jpg", frame);
        frame_number++;
    }
    cap.release();
}
edit flag offensive delete link more

Question Tools

1 follower

Stats

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

Seen: 6,063 times

Last updated: Jun 04 '18