当前位置:   article > 正文

Android使用OpenCV – 4.8.0进行人脸识别(三)_android opencv摄像头 人脸识别

android opencv摄像头 人脸识别

WeChat_20230718173530

6、使用手机前置摄像头进行人脸识别

  1. package com.example.opencv;
  2. import org.opencv.android.BaseLoaderCallback;
  3. import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
  4. import org.opencv.android.LoaderCallbackInterface;
  5. import org.opencv.android.OpenCVLoader;
  6. import org.opencv.core.*;
  7. import org.opencv.android.CameraBridgeViewBase;
  8. import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
  9. import org.opencv.imgproc.Imgproc;
  10. import org.opencv.objdetect.CascadeClassifier;
  11. import android.Manifest;
  12. import android.annotation.SuppressLint;
  13. import android.content.Context;
  14. import android.content.pm.ActivityInfo;
  15. import android.os.Bundle;
  16. import android.util.Log;
  17. import android.widget.Toast;
  18. import androidx.appcompat.app.AppCompatActivity;
  19. import com.tbruyelle.rxpermissions2.RxPermissions;
  20. import java.io.File;
  21. import java.io.FileOutputStream;
  22. import java.io.InputStream;
  23. /**
  24. * 人脸检测
  25. */
  26. public class MainActivity extends AppCompatActivity implements CvCameraViewListener2 {
  27. private static final String TAG = "OCVSample::Activity";
  28. private CameraBridgeViewBase mOpenCvCameraView;
  29. private Mat mIntermediateMat;
  30. private CascadeClassifier classifier;
  31. private Mat mGray;
  32. private Mat mRgba;
  33. private int mAbsoluteFaceSize = 0;
  34. private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
  35. @Override
  36. public void onManagerConnected(int status) {
  37. switch (status) {
  38. case LoaderCallbackInterface.SUCCESS: {
  39. Log.i(TAG, "OpenCV loaded successfully");
  40. getPermission();
  41. mOpenCvCameraView.enableView();
  42. }
  43. break;
  44. default: {
  45. super.onManagerConnected(status);
  46. }
  47. break;
  48. }
  49. }
  50. };
  51. public MainActivity() {
  52. Log.i(TAG, "Instantiated new " + this.getClass());
  53. }
  54. /**
  55. * Called when the activity is first created.
  56. */
  57. @Override
  58. public void onCreate(Bundle savedInstanceState) {
  59. Log.i(TAG, "called onCreate");
  60. super.onCreate(savedInstanceState);
  61. setContentView(R.layout.activity_main);
  62. mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.by);
  63. mOpenCvCameraView.enableView();
  64. mOpenCvCameraView.setCameraIndex(CameraBridgeViewBase.CAMERA_ID_FRONT);//前置摄像头 CameraBridgeViewBase.CAMERA_ID_BACK为后置摄像头
  65. //这里的by也是我的项目中JavaCameraView的id,自己改一下
  66. mOpenCvCameraView.setCvCameraViewListener(this);
  67. }
  68. @Override
  69. public void onPause() {
  70. super.onPause();
  71. if (mOpenCvCameraView != null)
  72. mOpenCvCameraView.disableView();
  73. }
  74. @Override
  75. public void onResume() {
  76. super.onResume();
  77. if (!OpenCVLoader.initDebug()) {
  78. Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
  79. OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION, this, mLoaderCallback);
  80. } else {
  81. Log.d(TAG, "OpenCV library found inside package. Using it!");
  82. mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
  83. }
  84. }
  85. public void onDestroy() {
  86. super.onDestroy();
  87. if (mOpenCvCameraView != null)
  88. mOpenCvCameraView.disableView();
  89. }
  90. public void onCameraViewStarted(int width, int height) {
  91. mGray = new Mat();
  92. mRgba = new Mat();
  93. }
  94. public void onCameraViewStopped() {
  95. // Explicitly deallocate Mats
  96. if (mIntermediateMat != null)
  97. mIntermediateMat.release();
  98. mIntermediateMat = null;
  99. mGray.release();
  100. mRgba.release();
  101. }
  102. public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
  103. // Mat rgba = inputFrame.rgba();
  104. // return rgba;
  105. mRgba = inputFrame.rgba();
  106. mGray = inputFrame.gray();
  107. //判断横竖屏用于进行图像的旋转
  108. if(getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){
  109. Mat rotatedRgbMat = null;
  110. Mat rotatedGrayMat = null;
  111. //厂商把后置摄像头映射成前置摄像头了
  112. Core.flip(mRgba,mRgba,1);//使用了前置摄像头,又设置了drawSource=false需要翻转左不然旋转90度之后会有问题右,
  113. rotatedRgbMat=new Mat(mRgba.cols(), mRgba.rows(), mRgba.type());
  114. Core.rotate(mRgba,rotatedRgbMat, Core.ROTATE_90_CLOCKWISE);//旋转之后得到正确的预览图像
  115. mRgba = rotatedRgbMat;
  116. Core.flip(mGray,mGray,1);//使用了前置摄像头,又设置了drawSource=false,需要翻转左右不然旋转90度之后会有问题
  117. rotatedGrayMat=new Mat(mGray.cols(), mGray.rows(), mGray.type());
  118. Core.rotate(mGray,rotatedGrayMat, Core.ROTATE_90_CLOCKWISE);//旋转之后得到正确的预览图像
  119. mGray=rotatedGrayMat;
  120. }
  121. float mRelativeFaceSize = 0.2f;
  122. if (mAbsoluteFaceSize == 0) {
  123. int height = mGray.rows();
  124. if (Math.round(height * mRelativeFaceSize) > 0) {
  125. mAbsoluteFaceSize = Math.round(height * mRelativeFaceSize);
  126. }
  127. }
  128. MatOfRect faces = new MatOfRect();
  129. if (classifier != null)
  130. classifier.detectMultiScale(mGray, faces, 1.1, 2, 2,
  131. new Size(mAbsoluteFaceSize, mAbsoluteFaceSize), new Size());
  132. Rect[] facesArray = faces.toArray();
  133. Scalar faceRectColor = new Scalar(0, 255, 0, 255);
  134. for (Rect faceRect : facesArray)
  135. Imgproc.rectangle(mRgba, faceRect.tl(), faceRect.br(), faceRectColor, 3);
  136. // Core.flip(mRgba, mRgba, 1);
  137. // Core.flip(mGray, mGray, 1);
  138. Log.e(TAG, "共检测到 " + faces.toArray().length + " 张脸");
  139. return mRgba;
  140. }
  141. // 初始化人脸级联分类器,必须先初始化
  142. private void initClassifier() {
  143. try {
  144. InputStream is = getResources()
  145. .openRawResource(R.raw.lbpcascade_frontalface);
  146. File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
  147. File cascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml");
  148. FileOutputStream os = new FileOutputStream(cascadeFile);
  149. byte[] buffer = new byte[4096];
  150. int bytesRead;
  151. while ((bytesRead = is.read(buffer)) != -1) {
  152. os.write(buffer, 0, bytesRead);
  153. }
  154. is.close();
  155. os.close();
  156. classifier = new CascadeClassifier(cascadeFile.getAbsolutePath());
  157. } catch (Exception e) {
  158. e.printStackTrace();
  159. }
  160. }
  161. @SuppressLint("CheckResult")
  162. private void getPermission(){
  163. RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
  164. rxPermissions.request(Manifest.permission.CAMERA).subscribe(aBoolean -> {
  165. if (aBoolean) {
  166. initClassifier();
  167. mOpenCvCameraView.setCameraPermissionGranted();
  168. } else {
  169. Toast.makeText(MainActivity.this, "您还没有开启相机权限,请前往设置->应用管理->开启", Toast.LENGTH_SHORT).show();
  170. }
  171. });
  172. }
  173. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/566826
推荐阅读
相关标签
  

闽ICP备14008679号