网上关于 OpenCV Java 的资料特别少,记录下自己的学习过程,读取摄像头并画出框来。
环境
1 | OS: macOS 10.13.3 |
步骤
第一步:加载 OpenCV 的库
项目创建好后,参考前面的 OpenCV 安装里面的 “IntelliJ 使用 OpenCV”,添加启动参数和包,然后加载 OpenCV 的库如下(重要记笔记)
一定要先加载,不然会报错,这里写在主方法第一条1
2
3
4
5
6public static void main(String[] args) {
//加载 OpenCV 库
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
//省略代码
.....
}
第二步:读取摄像头
读取摄像头使用 OpenCV 的 VideoCapture
类相关方法如下:
1 | VideoCapture(int index) |
Imgcodecs.imwrite()
把 Mat 存成图片 Imgcodecs.imread()
把图片读取为 Mat
简单的读取本机的摄像头,存到桌面文件夹,代码如下:
1 | // 读取摄像头 |
第三步:检测人脸
有了图片就可以测人脸了,这里使用官方训练好的模型, MAC 路径:/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/
下 haarcascade_frontalface_alt.xml
为检测人脸的模型,要识别的图片路径 /Users/limbang/Desktop/img/img.jpg
,代码如下:
1 | // 创建分类器 |
原图
检测后
注意:在摄像头连续读取并实时检测显示,使用detectMultiScale
检测人脸,如果不加那个最大最小尺寸,会使 CPU 起飞,视频掉帧
官方文档 detectMultiScale
参数详解1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16void detectMultiScale(Mat image, MatOfRect objects)
void detectMultiScale(Mat image, MatOfRect objects, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize)
Detects objects of different sizes in the input image. The detected objects are returned as a list of rectangles.
Parameters:
image Matrix of the type CV_8U containing an image where objects are detected.
objects Vector of rectangles where each rectangle contains the detected object, the rectangles may be partially outside the original image.
scaleFactor Parameter specifying how much the image size is reduced at each image scale.
minNeighbors Parameter specifying how many neighbors each candidate rectangle should have to retain it.
flags Parameter with the same meaning for an old cascade as in the function cvHaarDetectObjects. It is not used for a new cascade.
minSize Minimum possible object size. Objects smaller than that are ignored.
maxSize Maximum possible object size. Objects larger than that are ignored. If maxSize == minSize model is evaluated on single scale.
The function is parallelized with the TBB library.