1、安装opencv
先引用包和资源,自行安装opencv
官网下载地址: https://opencv.org/releases/.
代码中先加载资源
/*
* @Description //加载opencv资源
* @Param null
* @Date 2021/9/15
* @Author zxq
* @return
**/
static {
//判断运行系统
String osName = System.getProperties().getProperty("os.name").toLowerCase();
//linux环境下
if (osName.contains("linux")) {
log.info("运行环境:linux");
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
//window环境下
if (osName.contains("win")) {
log.info("运行环境:windows");
System.loadLibrary("opencv_java453");
System.loadLibrary("opencv_videoio_ffmpeg453_64");
}
}
2、加载摄像头或视频流
加载摄像头
//打开本机摄像头
VideoCapture videoCapture = new VideoCapture(0);
或者加载视频流
//这里加载的是rtmp视频流
VideoCapture videoCapture = new VideoCapture(param.getRtmpUrl());
判断是否打开
if (!videoCapture.isOpened()) {
log.error(" 当前视频流打开失败 fail");
videoCapture.release();
continue;
}
没有打开的原因,windows下一般是没引入步骤一中的dll资源或者opencv没安装成功
linux下可能是ffmpeg和opencv没有编译安装成功。
linux安装opencv和ffmpeg参考这篇文章 https://blog.csdn.net/qq_42528520/article/details/120487457.
3、加载图像进行播放
在while循环中读取
while(true){
Mat img = new Mat();
if (!videoCapture.read(img)) {
log.error("===读取失败");
img.release();
continue;
}
//加载图像播放
HighGui.imshow("VideoCapture", img);
//刷新帧
HighGui.waitKey(10);
//释放当前帧 不然会内存溢出
img.release();
}
//最后关闭摄像头
videoCapture.release();
4、若需要截图
在while循环体中加入
//上述的Mat对象
Image image = HighGui.toBufferedImage(img);
//转换图片
BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_3BYTE_BGR);
Graphics g = bi.getGraphics();
g.drawImage(image, 0, 0, null);
//将BufferedImage变量写入临时文件中。保存到本地
File file = new File("C:\\home\\admin\\zxq\\" +System.currentTimeMillis() + ".jpg");
ImageIO.write(bi, "jpg", file);