in android studio doing face detection using opencv. E/AndroidRuntime: FATAL EXCEPTION: main

Issue

I am doing face detection application using opencv.the app is installed in the phone but due to fatal error it get closed suddenly. this is my MainActivity.java

package com.example.oc2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraActivity;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;

import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2{
    JavaCameraView javaCameraView;
    File cascfile;
    CascadeClassifier facedetector;
    private Mat mRgba,mGrey;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(!OpenCVLoader.initDebug())
        {
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_4_0,this, baseCallback);
        }
            else
        {
            try {
                baseCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
            javaCameraView.setCvCameraViewListener(this);
    }

    @Override
    public void onCameraViewStarted(int width, int height) {
        mRgba=new Mat();
        mGrey=new Mat();

    }

    @Override
    public void onCameraViewStopped() {
        mGrey.release();
        mRgba.release();

    }

    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
        mRgba=inputFrame.rgba();
        mGrey=inputFrame.gray();
        MatOfRect facedetection= new MatOfRect();
        facedetector.detectMultiScale(mRgba,facedetection);
        for(Rect rect: facedetection.toArray())
        {
            Imgproc.rectangle(mRgba,new Point(rect.x,rect.y),new Point(rect.x+rect.width,rect.y+rect.height),new Scalar(255,0,0));
        }
        return mRgba;
    }

    private final BaseLoaderCallback baseCallback=new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) throws IOException {
            switch (status)
            {
                case LoaderCallbackInterface.SUCCESS:
                {
                    InputStream is = getResources().openRawResource(R.raw.haarcascade_frontalface_alt2);
                    File cascadedir=getDir( "cascade" , Context.MODE_PRIVATE);
                    cascfile= new File(cascadedir, "haarcascade_frontalface_alt2.xml" );
                    FileOutputStream fos= new FileOutputStream(cascfile);

                    byte[] buffer=new byte[4096];
                    int bytesread;
                    while((bytesread = is.read(buffer))!=-1)
                    {
                        fos.write(buffer,0,bytesread);
                    }
                    is.close();
                    fos.close();
                    facedetector=new CascadeClassifier(cascfile.getAbsolutePath());
                    if(facedetector.empty())
                    {
                        facedetector=null;
                    }
                    else
                    {
                        cascadedir.delete();
                    }
                    javaCameraView.enableView();

                }
                break;

                default:
                    {
                    super.onManagerConnected(status);
                    }
                    break;

            }

        }
    };
}

this are my errors can anyone help?

D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION:
main
Process: com.example.oc2, PID: 19468
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.oc2/com.example.oc2.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method ‘void
org.opencv.android.JavaCameraView.enableView()’ on a null object
reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3119)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6864)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void org.opencv.android.JavaCameraView.enableView()’
on a null object reference
at com.example.oc2.MainActivity$1.onManagerConnected(MainActivity.java:116)
at com.example.oc2.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:7232)
at android.app.Activity.performCreate(Activity.java:7221)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2964)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3119) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6864) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
I/Process: Sending signal. PID: 19468 SIG: 9

if anyone could give steps to resolving the errors it would be very helpful.

Solution

I have two feelings about your code:

1 – in your onCreate activity you are missing a line as:

javaCameraView = (CameraBridgeViewBase) findViewById(R.id.java_camera_view);

2 – you are not checking if the camera permission was granted, which may cause you another error later ["it seems that your device does not support camera or it is locked - application will be closed"]

So have a test with this snippet but consider that in order to have it working you will need to enable the camera permission for the app before launching the app [Settings->Apps->YourApp->Permissions->Camera]. The permission part must be rewritten properly, this is just for a quick test

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    javaCameraView = (CameraBridgeViewBase) findViewById(R.id.java_camera_view);

    // added for black screen
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            == PackageManager.PERMISSION_GRANTED) {
        Log.d(TAG, "Permissions granted");
        javaCameraView.setCameraPermissionGranted();    
        javaCameraView.setCameraIndex(CameraBridgeViewBase.CAMERA_ID_FRONT);    
        javaCameraView.setVisibility(CameraBridgeViewBase.VISIBLE);
        javaCameraView.setCvCameraViewListener(this);
    } else {
        Log.d(TAG, "Troubles");
    }   
}

Answered By – Antonino

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published