4.4读取视频并显示
代码如下:
package imageIO;
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.videoio.VideoCapture;
import tool.mat2BufferedImage;
import java.awt.BorderLayout;
public class VideoPlay {
static{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
private JFrame frame;
private static JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VideoPlay window = new VideoPlay();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//我们的操作
VideoCapture capture=new VideoCapture("F://2.avi");//读取视频
if (!capture.isOpened()) {
System.out.println("Error");
} else {
Mat webcam_image = new Mat();
capture.read(webcam_image);
while (true) {
capture.read(webcam_image);
if( !webcam_image.empty() ){
BufferedImage b=mat2BufferedImage.matToBufferedImage(webcam_image);
lblNewLabel.setIcon(new ImageIcon(b));
}else{
System.out.println("视频已结束!");
capture.release();
break;
}
}
}
}
/**
* Create the application.
*/
public VideoPlay() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(0, 0, 1000, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
lblNewLabel = new JLabel("");
lblNewLabel.setBounds(0, 0, 1000, 800);
frame.getContentPane().add(lblNewLabel);
}
}
注意:要运行该程序,必须将opencv目录下build/bin目录下的ffmpeg那个dll文件(有2个,一个是32位,另一个是64位,看你计算机位数进行选择)复制到C:windows/system32。或者另一种办法是将bin目录添加到系统环境变量path中去。
运行结果:播放视频成功!
Bug:再次运行程序会报错
将ffmpeg重新复制又能成功一次,我想应该是opencv中的bug吧,欢迎解决的朋友留下解决方案!
CommissarMa 2017年3月30日10:14:20