- 说在前面
Android Studio版本:3.2
操作系统(AS):Windows10
Android版本:5.0.2
摄像头:USB摄像头(640*480
贼辣鸡)
- 运行截图
帧率有点感人(我胡多帅啊)
- 导入文件
这里要导入一个xml文件,放在这里;我放到了github对应位置,当然在官方samples里也有。
- 代码
代码直接放在上一篇(包含github项目地址)的opencv处理那部分,把灰度图那部分改一下;
改成下面的:
Mat image = new Mat();
InputStream is = getResources().openRawResource(R.raw.lbpcascade_frontalface);
File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
File mCascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml");
Utils.bitmapToMat(srcBitmap,image);
try {
FileOutputStream os = new FileOutputStream(mCascadeFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
}catch (Exception e){
Log.v(TAG,e.getMessage());
}
CascadeClassifier mJavaDetector = new CascadeClassifier(mCascadeFile.getAbsolutePath());
MatOfRect faceDetections = new MatOfRect();
try {
mJavaDetector.detectMultiScale(image, faceDetections);
System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
// Draw a bounding box around each face.
for (Rect rect : faceDetections.toArray()) {
Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
}
}catch (Exception e){
Log.v(TAG,e.getMessage());
}
Utils.matToBitmap(image,bitmap);
参考:
OpenCV-android-SDK提供的samples-face-detection,github上有,下载的官方SDK里面也有;