title: Slow camera and app close within less than minute
body: <p>I'm developing an android application which detect text using OpenCV's MSER algorithm. The application is working just fine and doing what it should do, but it closes after less than 1 minute! note that there is no errors or something. I think the problem is with the memory, I monitored the memory of my device while the application was running and there was memory left in my device still it stop working and return me to my phone's home page and close the music if I'm listening to something. I think that the application is very heavy and doing so much work that why the camera became slow and it close suddenly. </p>
  
  <p>I don't know how to solve this problem.. can someone tell me how to solve this?</p>
  
  <p>My code:</p>
  
  <p>xml:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;android.support.constraint.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.example.lama.myapplication.MainActivity"&gt;
  
  
  
  &lt;org.opencv.android.JavaCameraView
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:layout_alignParentRight="true"
      android:layout_alignParentLeft="true"
      android:gravity="center"
      android:layout_marginLeft="10dp"
      android:layout_marginRight="10dp"
      android:layout_marginTop="10dp"
      android:layout_marginBottom="10dp"
      android:id="@+id/java_camera_view"
      /&gt;
  
  
  &lt;/android.support.constraint.ConstraintLayout&gt;
  </code></pre>
  
  <p>java class:</p>
  
  <pre><code>  public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {
  
  
  private static final String TAG = "MainActivity";
  JavaCameraView javaCameraView;
  Mat mRgba;
  //imgGray, imgCanny;
  private Mat mGrey,mIntermediateMat;
  
  
  BaseLoaderCallback mLoaderCallBack = new BaseLoaderCallback(this) {
      @Override
      public void onManagerConnected(int status) {
          switch(status){
              case BaseLoaderCallback.SUCCESS:{
                  javaCameraView.enableView();
                  break;
              }
              default:{
                  super.onManagerConnected(status);
                  break;
              }
          }
      }
  };
  
  static {
  
  }
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
  
      getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,      WindowManager.LayoutParams.FLAG_FULLSCREEN);
      getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  
      //camera permission
      String[] perms = {"android.permission.CAMERA"};
      int permsRequestCode = 200;
      requestPermissions(perms, permsRequestCode);
  
      javaCameraView=(JavaCameraView) findViewById(R.id.java_camera_view);
      javaCameraView.setVisibility(SurfaceView.VISIBLE);
      javaCameraView.setCvCameraViewListener(this);
  
  
  }
  
  @Override
  protected void onPause(){
      super.onPause();
      if (javaCameraView!=null)
          javaCameraView.disableView();
  }
  
  @Override
  protected void onDestroy(){
      super.onDestroy();
      if (javaCameraView!=null)
          javaCameraView.disableView();
      System.gc();
  
  }
  
  @Override
  protected void onResume(){
      super.onResume();
      if(!OpenCVLoader.initDebug()){
          Log.d(TAG, "OpenCV not loaded");
          mLoaderCallBack.onManagerConnected(LoaderCallbackInterface.SUCCESS);
  
      } else {
          Log.d(TAG, "OpenCV loaded");
          OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9,this,mLoaderCallBack);
      }
  }
  
  /**
   * A native method that is implemented by the 'native-lib' native library,
   * which is packaged with this application.
   */
  public native String stringFromJNI();
  
  // Used to load the 'native-lib' library on application startup.
  static {
      System.loadLibrary("native-lib");
  }
  
  @Override
  public void onCameraViewStarted(int width, int height) {
      /*mRgba=new Mat(height,width, CvType.CV_8UC4);
      imgGray=new Mat(height,width, CvType.CV_8UC1);
      imgCanny=new Mat(height,width, CvType.CV_8UC1);*/
      mIntermediateMat = new Mat();
      mGrey = new Mat(height, width, CvType.CV_8UC4);
      mRgba = new Mat(height, width, CvType.CV_8UC4);
  }
  
  @Override
  public void onCameraViewStopped() {
      mRgba.release();
  }
  
  @Override
  public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
      //  mRgba=inputFrame.rgba();
  
     /* Imgproc.cvtColor(mRgba,imgGray,Imgproc.COLOR_RGB2GRAY);
     return imgGray;
  
      Imgproc.Canny(imgGray,imgCanny, 50,150);
      return imgCanny;*/
  
      // return mRgba;
  
      mGrey = inputFrame.gray();
      mRgba = inputFrame.rgba();
  
      detectText();
      return mRgba;
  }
  
  private void detectText() {
      Scalar CONTOUR_COLOR = new Scalar(255);
      MatOfKeyPoint keypoint = new MatOfKeyPoint();
      List&lt;KeyPoint&gt; listpoint;
      KeyPoint kpoint;
      Mat mask = Mat.zeros(mGrey.size(), CvType.CV_8UC1);
      int rectanx1;
      int rectany1;
      int rectanx2;
      int rectany2;
      int imgsize = mGrey.height() * mGrey.width();
      Scalar zeos = new Scalar(0, 0, 0);
  
      List&lt;MatOfPoint&gt; contour2 = new ArrayList&lt;MatOfPoint&gt;();
      Mat kernel = new Mat(1, 50, CvType.CV_8UC1, Scalar.all(255));
      Mat morbyte = new Mat();
      Mat hierarchy = new Mat();
  
  
  
      Rect rectan3;
      //
      FeatureDetector detector = FeatureDetector.create(FeatureDetector.MSER);
      detector.detect(mGrey, keypoint);
      listpoint = keypoint.toList();
      //
      for (int ind = 0; ind &lt; listpoint.size(); ind++) {
          kpoint = listpoint.get(ind);
          rectanx1 = (int) (kpoint.pt.x - 0.5 * kpoint.size);
          rectany1 = (int) (kpoint.pt.y - 0.5 * kpoint.size);
          rectanx2 = (int) (kpoint.size);
          rectany2 = (int) (kpoint.size);
          if (rectanx1 &lt;= 0)
              rectanx1 = 1;
          if (rectany1 &lt;= 0)
              rectany1 = 1;
          if ((rectanx1 + rectanx2) &gt; mGrey.width())
              rectanx2 = mGrey.width() - rectanx1;
          if ((rectany1 + rectany2) &gt; mGrey.height())
              rectany2 = mGrey.height() - rectany1;
          Rect rectant = new Rect(rectanx1, rectany1, rectanx2, rectany2);
          try {
              Mat roi = new Mat(mask, rectant);
              roi.setTo(CONTOUR_COLOR);
              roi.release();
          } catch (Exception ex) {
              Log.d("mylog", "mat roi error " + ex.getMessage());
          }
      }
  
      Imgproc.morphologyEx(mask, morbyte, Imgproc.MORPH_DILATE, kernel);
      Imgproc.findContours(morbyte, contour2, hierarchy,
              Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);
      for (int ind = 0; ind &lt; contour2.size(); ind++) {
          // rectan3 = Imgproc.boundingRect(contour2.get(ind));
          rectan3 = Imgproc.boundingRect(contour2.get(ind));
          if (rectan3.area() &gt; 0.5 * imgsize || rectan3.area() &lt; 100
                  || rectan3.width / rectan3.height &lt; 2) {
              Mat roi = new Mat(morbyte, rectan3);
              roi.setTo(zeos);
  
          } else
              Imgproc.rectangle(mRgba, rectan3.br(), rectan3.tl(), CONTOUR_COLOR);
      }
  
  }
  
  
  //camera permission cont.
  @Override
  public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){
      switch(permsRequestCode){
          case 200:
              boolean cameraAccepted = grantResults[0]==PackageManager.PERMISSION_GRANTED;
              break;
      }
  }
  
  
  }
  </code></pre>
  
  <p>Can someone tell me how can I optimize my application and solve this problem?</p>
  
  <p><strong>EDIT:</strong>
  I tried to release all of the Mat objects as follow:</p>
  
  <pre><code>@Override
  public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
      if(mRgba != null){
          mRgba.release();
      }
  
      mRgba = inputFrame.rgba().clone();
  
      mGrey = inputFrame.gray();
      mRgba = inputFrame.rgba();
  
      detectText();
      return mRgba;
  
  }
  
  private void detectText() {
      Scalar CONTOUR_COLOR = new Scalar(255);
      MatOfKeyPoint keypoint = new MatOfKeyPoint();
      List&lt;KeyPoint&gt; listpoint;
      KeyPoint kpoint;
      Mat mask = Mat.zeros(mGrey.size(), CvType.CV_8UC1);
      int rectanx1;
      int rectany1;
      int rectanx2;
      int rectany2;
      int imgsize = mGrey.height() * mGrey.width();
      Scalar zeos = new Scalar(0, 0, 0);
  
      List&lt;MatOfPoint&gt; contour2 = new ArrayList&lt;MatOfPoint&gt;();
      Mat kernel = new Mat(1, 50, CvType.CV_8UC1, Scalar.all(255));
      Mat morbyte = new Mat();
      Mat hierarchy = new Mat();
  
  
      Rect rectan3;
      //
      FeatureDetector detector = FeatureDetector.create(FeatureDetector.MSER);
      detector.detect(mGrey, keypoint);
      listpoint = keypoint.toList();
      //
      for (int ind = 0; ind &lt; listpoint.size(); ind++) {
          kpoint = listpoint.get(ind);
          rectanx1 = (int) (kpoint.pt.x - 0.5 * kpoint.size);
          rectany1 = (int) (kpoint.pt.y - 0.5 * kpoint.size);
          rectanx2 = (int) (kpoint.size);
          rectany2 = (int) (kpoint.size);
          if (rectanx1 &lt;= 0)
              rectanx1 = 1;
          if (rectany1 &lt;= 0)
              rectany1 = 1;
          if ((rectanx1 + rectanx2) &gt; mGrey.width())
              rectanx2 = mGrey.width() - rectanx1;
          if ((rectany1 + rectany2) &gt; mGrey.height())
              rectany2 = mGrey.height() - rectany1;
          Rect rectant = new Rect(rectanx1, rectany1, rectanx2, rectany2);
          try {
              Mat roi = new Mat(mask, rectant);
              roi.setTo(CONTOUR_COLOR);
              roi.release();
          } catch (Exception ex) {
              Log.d("mylog", "mat roi error " + ex.getMessage());
          }
      }
  
      Imgproc.morphologyEx(mask, morbyte, Imgproc.MORPH_DILATE, kernel);
      Imgproc.findContours(morbyte, contour2, hierarchy,
              Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);
      for (int ind = 0; ind &lt; contour2.size(); ind++) {
          // rectan3 = Imgproc.boundingRect(contour2.get(ind));
          rectan3 = Imgproc.boundingRect(contour2.get(ind));
          if (rectan3.area() &gt; 0.5 * imgsize || rectan3.area() &lt; 100
                  || rectan3.width / rectan3.height &lt; 2) {
              Mat roi = new Mat(morbyte, rectan3);
              roi.setTo(zeos);
              roi.release();
          } else
              Imgproc.rectangle(mRgba, rectan3.br(), rectan3.tl(), CONTOUR_COLOR);
      }
  
      mask.release();
      kernel.release();
      morbyte.release();
      hierarchy.release();
      mGrey.release();
      mIntermediateMat.release();
  
  }
  </code></pre>
  
  <p>Yet still I'm having the same problem!
  Can someone please help me solve this?</p>