通过javacv对视频每隔1秒钟截取1张图片

之前每一秒钟截取一张图片,发现有些图片报了“[mpeg4 @ 05938aa0] warning: first frame is no keyframe”这个警告,而且截出的图片都是灰屏,根本没有图片。后来在网上找了很久,终于弄明白了,原来是ffmpeg它有“关键帧”这个说法,所以如果设置的帧的位置不是关键帧的位置的话,就可能截出的图片有问题。后来经过改进,终于搞定了。

	public static void main(String[] args) {
		System.out.println(System.getProperty("java.library.path"));
//		 System.out.println("Welcome to OpenCV " + Core.VERSION);
//		 System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
//		 Mat m = Mat.eye(3, 3, CvType.CV_8UC1);
//		 System.out.println("m = " + m.dump());

		// 加载本地的OpenCV库,这样就可以用它来调用Java API
		System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
		Test t = new Test();
//		t.test();
//		t.run();
//		t.run2();
		t.run3();
//		System.out.println(t.CmpPic("d:/img/219.jpg"));
	}

	public void run3() {
		CvCapture capture = opencv_highgui.cvCreateFileCapture("D:/085402.crf");
		
		//帧率
		int fps = (int) opencv_highgui.cvGetCaptureProperty(capture, opencv_highgui.CV_CAP_PROP_FPS);
		System.out.println("帧率:"+fps);
		
		IplImage frame = null;
		double pos1 = 0;
		
		int rootCount = 0;

		while (true) {
			
			//读取关键帧
			frame = opencv_highgui.cvQueryFrame(capture);
			
			rootCount = fps;
			while(rootCount > 0 ){
				//这一段的目的是跳过每一秒钟的帧数,也就是说fps是帧率(一秒钟有多少帧),在读取一帧后,跳过fps数量的帧就相当于跳过了1秒钟。
				frame = opencv_highgui.cvQueryFrame(capture);
				rootCount--;
			}

			//获取当前帧的位置
			pos1 = opencv_highgui.cvGetCaptureProperty(capture,opencv_highgui.CV_CAP_PROP_POS_FRAMES);
			System.out.println(pos1);

			if (null == frame)
				break;
			
			opencv_highgui.cvSaveImage("d:/img/" + pos1 + ".jpg",frame);
			
		}

		opencv_highgui.cvReleaseCapture(capture);
	}


你可能感兴趣的:(java,opencv)