慢速相机和应用程序在不到一分钟内关闭

时间:2017-04-11 12:54:25

标签: java android opencv

我正在开发一个使用OpenCV的MSER算法检测文本的Android应用程序。该应用程序正常工作并做它应该做的事情,但它在不到1分钟后关闭!请注意,没有错误或其他内容。我认为问题在于内存,我在应用程序运行时监视设备的内存,我的设备中还有内存,它仍然停止工作并返回我手机的主页并关闭音乐如果我在听某事。我认为应用程序非常繁重并且做了很多工作,为什么相机变得缓慢而且突然关闭。

我不知道如何解决这个问题..谁能告诉我如何解决这个问题?

我的代码:

的xml:

<?xml version="1.0" encoding="utf-8"?>
<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">



<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"
    />


</android.support.constraint.ConstraintLayout>

java class:

  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<KeyPoint> 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<MatOfPoint> contour2 = new ArrayList<MatOfPoint>();
    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 < 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 <= 0)
            rectanx1 = 1;
        if (rectany1 <= 0)
            rectany1 = 1;
        if ((rectanx1 + rectanx2) > mGrey.width())
            rectanx2 = mGrey.width() - rectanx1;
        if ((rectany1 + rectany2) > 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 < contour2.size(); ind++) {
        // rectan3 = Imgproc.boundingRect(contour2.get(ind));
        rectan3 = Imgproc.boundingRect(contour2.get(ind));
        if (rectan3.area() > 0.5 * imgsize || rectan3.area() < 100
                || rectan3.width / rectan3.height < 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;
    }
}


}

有人能告诉我如何优化我的应用程序并解决这个问题?

修改 我尝试释放所有Mat对象,如下所示:

@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<KeyPoint> 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<MatOfPoint> contour2 = new ArrayList<MatOfPoint>();
    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 < 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 <= 0)
            rectanx1 = 1;
        if (rectany1 <= 0)
            rectany1 = 1;
        if ((rectanx1 + rectanx2) > mGrey.width())
            rectanx2 = mGrey.width() - rectanx1;
        if ((rectany1 + rectany2) > 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 < contour2.size(); ind++) {
        // rectan3 = Imgproc.boundingRect(contour2.get(ind));
        rectan3 = Imgproc.boundingRect(contour2.get(ind));
        if (rectan3.area() > 0.5 * imgsize || rectan3.area() < 100
                || rectan3.width / rectan3.height < 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();

}

但我仍然遇到同样的问题! 有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

由于内存问题,应用程序关闭。

  1. 首先,您必须在函数末尾释放所有已分配的Mat对象** detectText()**
  2. forCameraFrame(...)函数在重新分配之前释放内存。
  3. 您可以尝试

    的示例
     @Override
    public Mat onCameraFrame(final CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
    
        if(mRgba != null){
            mRgba.release();
        }
    
        mRgba = inputFrame.rgba().clone();
    
       //your code here
    }
    

    //编辑:12/04/2017

    您的代码应为

    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) 
    {
    if(mRgba != null){
        mRgba.release();
    }
    
     if(mGrey != null){
        mGrey.release();
    }
    
    mRgba = inputFrame.rgba().clone();
    mGrey = inputFrame.gray().clone();
    
    detectText();
    return mRgba;
    
    }
    
    private void detectText() {
    Scalar CONTOUR_COLOR = new Scalar(255);
    MatOfKeyPoint keypoint = new MatOfKeyPoint();
    List<KeyPoint> 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<MatOfPoint> contour2 = new ArrayList<MatOfPoint>();
    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 < 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 <= 0)
            rectanx1 = 1;
        if (rectany1 <= 0)
            rectany1 = 1;
        if ((rectanx1 + rectanx2) > mGrey.width())
            rectanx2 = mGrey.width() - rectanx1;
        if ((rectany1 + rectany2) > 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 < contour2.size(); ind++) {
        // rectan3 = Imgproc.boundingRect(contour2.get(ind));
        rectan3 = Imgproc.boundingRect(contour2.get(ind));
        if (rectan3.area() > 0.5 * imgsize || rectan3.area() < 100
                || rectan3.width / rectan3.height < 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();
    mIntermediateMat.release();
    
    }