Example usage for org.opencv.android BaseLoaderCallback BaseLoaderCallback

List of usage examples for org.opencv.android BaseLoaderCallback BaseLoaderCallback

Introduction

In this page you can find the example usage for org.opencv.android BaseLoaderCallback BaseLoaderCallback.

Prototype

public BaseLoaderCallback(Context AppContext) 

Source Link

Usage

From source file:alicrow.opencvtour.FollowTourActivity.java

License:Open Source License

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getIntent().getData() != null) {
        /// FollowTourActivity was launched directly, with a Tour archive. Must initialize OpenCV and load the Tour before we can set up the Activity.
        /// This happens when another app calls our app to open a tour archive.

        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, new BaseLoaderCallback(this) {
            @Override//  w w  w.  j  ava2  s .c o  m
            public void onManagerConnected(int status) {
                switch (status) {
                case LoaderCallbackInterface.SUCCESS: {
                    Log.i(TAG, "OpenCV loaded successfully");

                    /// Load the tour file
                    Uri data = getIntent().getData();
                    String scheme = data.getScheme();
                    File extracted_folder = null;
                    if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
                        /// content uri
                        try {
                            /// Try to retrieve the filename so we know what to name our extracted folder.
                            String folder_name;
                            Cursor cursor = getContentResolver().query(data, new String[] { "_display_name" },
                                    null, null, null);
                            cursor.moveToFirst();
                            int nameIndex = cursor.getColumnIndex("_display_name");
                            if (nameIndex >= 0) {
                                folder_name = cursor.getString(nameIndex);
                            } else {
                                folder_name = "imported-folder.zip.tour";
                            }
                            cursor.close();

                            folder_name = folder_name.substring(0, folder_name.length() - ".zip.tour".length());
                            extracted_folder = new File(Tour.getImportedToursDirectory(FollowTourActivity.this),
                                    folder_name);
                            Utilities.extractFolder(getContentResolver().openInputStream(data),
                                    extracted_folder.getPath());
                        } catch (FileNotFoundException ex) {
                            Log.e(TAG, ex.getMessage());
                            /// Import failed. Exit the activity.
                            FollowTourActivity.this.finish();
                        }
                    } else {
                        /// regular file uri
                        String filepath = data.getPath();
                        String folder_name = data.getLastPathSegment();
                        folder_name = folder_name.substring(0, folder_name.length() - ".zip.tour".length());
                        extracted_folder = new File(Tour.getImportedToursDirectory(FollowTourActivity.this),
                                folder_name);
                        Utilities.extractFolder(filepath, extracted_folder.getPath());
                    }
                    Tour.setSelectedTour(new Tour(new File(extracted_folder, "tour.yaml")));
                    load(savedInstanceState);
                    break;
                }
                default: {
                    super.onManagerConnected(status);
                    break;
                }
                }
            }
        });
    } else
        load(savedInstanceState);
}

From source file:alicrow.opencvtour.TourListFragment.java

License:Open Source License

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    /// Must wait until OpenCV is initialized before loading the tours (since we load image descriptors).
    BaseLoaderCallback _loader_callback = new BaseLoaderCallback(getActivity()) {
        @Override//from  ww  w. j  a  va 2s  .co m
        public void onManagerConnected(int status) {
            switch (status) {
            case LoaderCallbackInterface.SUCCESS: {
                Log.i(TAG, "OpenCV loaded successfully");

                /// Add footer so the floating action button doesn't cover up the list.
                _adapter = new TourAdapter(Tour.getTours(getActivity()));
                WrapAdapter wrap_adapter = new WrapAdapter(_adapter);
                wrap_adapter.addFooter(getActivity().getLayoutInflater().inflate(R.layout.empty_list_footer,
                        _recycler_view, false));
                _recycler_view.setAdapter(wrap_adapter);
            }
                break;
            default: {
                super.onManagerConnected(status);
            }
                break;
            }
        }
    };

    _recycler_view = (RecyclerView) getActivity().findViewById(R.id.recycler_view);
    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, getActivity(), _loader_callback);
    _recycler_view.setLayoutManager(new LinearLayoutManager(getActivity()));

    getActivity().findViewById(R.id.fab).setOnClickListener(this);
    getActivity().findViewById(R.id.help_button).setOnClickListener(this);
}

From source file:com.android.cts.verifier.sensors.helpers.OpenCVLibrary.java

License:Apache License

/**
 * Load OpenCV Library in async mode//from ww w  .jav a2 s.co m
 *
 * @param context Activity context.
 * @param allowStatic Allow trying load from local package.
 * @param allowInstall Allow installing package from play store.
 *
 * @return if load succeed return true. Return false otherwise.
 */
public static boolean load(Context context, boolean allowLocal, boolean allowPackage, boolean allowInstall) {
    // only need to load once
    if (!sLoaded) {
        // Try static load first
        if (allowLocal && OpenCVLoader.initDebug()) {
            sLoaded = true;
        } else if (allowPackage) {
            if (allowInstall || probePackage(context)) {
                final CountDownLatch done = new CountDownLatch(1);
                // Load the library through async loader
                OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, context,
                        new BaseLoaderCallback(context) {
                            @Override
                            public void onManagerConnected(int status) {
                                Log.v(TAG, "New Loading status: " + status);
                                switch (status) {
                                case LoaderCallbackInterface.SUCCESS: {
                                    sLoaded = true;
                                }
                                    break;
                                default: {
                                    Log.e(TAG, "Connecting OpenCV Manager failed");
                                }
                                    break;
                                }
                                done.countDown();
                            }
                        });
                try {
                    if (!done.await(ASYNC_LOAD_TIMEOUT_SEC, TimeUnit.SECONDS)) {
                        Log.e(TAG, "Time out when attempt async load");
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
    return sLoaded;
}

From source file:com.davidmiguel.gobees.monitoring.MonitoringFragment.java

License:Open Source License

@Nullable
@Override//from w w w .  j  a  va  2s  . co  m
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.monitoring_frag, container, false);

    // Configure OpenCV callback
    loaderCallback = new BaseLoaderCallback(getContext()) {
        @Override
        public void onManagerConnected(final int status) {
            if (status == LoaderCallbackInterface.SUCCESS) {
                presenter.onOpenCvConnected();
            } else {
                super.onManagerConnected(status);
            }
        }
    };

    // Don't switch off screen
    getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    // Configure camera
    cameraView = (CameraView) root.findViewById(R.id.camera_view);
    cameraView.setCameraIndex(CameraBridgeViewBase.CAMERA_ID_BACK);
    cameraView.setMaxFrameSize(MAX_WIDTH, MAX_HEIGHT);
    // Configure view
    numBeesTV = (TextView) root.findViewById(R.id.num_bees);
    settingsLayout = (RelativeLayout) getActivity().findViewById(R.id.settings);
    chronometer = (Chronometer) root.findViewById(R.id.chronometer);

    // Configure icons
    settingsIcon = (ImageView) root.findViewById(R.id.settings_icon);
    settingsIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            presenter.openSettings();
        }
    });
    recordIcon = (ImageView) root.findViewById(R.id.record_icon);
    recordIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            presenter.startMonitoring();
        }
    });

    // Configure service connection
    mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            MonitoringBinder binder = (MonitoringBinder) service;
            mService = binder.getService(new GoBeesDataSource.SaveRecordingCallback() {
                @Override
                public void onRecordingTooShort() {
                    // Finish activity with error
                    Intent intent = new Intent();
                    intent.putExtra(HiveRecordingsFragment.ARGUMENT_MONITORING_ERROR,
                            HiveRecordingsFragment.ERROR_RECORDING_TOO_SHORT);
                    getActivity().setResult(Activity.RESULT_CANCELED, intent);
                    getActivity().finish();

                }

                @Override
                public void onSuccess() {
                    // Finish activity with OK
                    getActivity().setResult(Activity.RESULT_OK);
                    getActivity().finish();
                }

                @Override
                public void onFailure() {
                    // Finish activity with error
                    Intent intent = new Intent();
                    intent.putExtra(HiveRecordingsFragment.ARGUMENT_MONITORING_ERROR,
                            HiveRecordingsFragment.ERROR_SAVING_RECORDING);
                    getActivity().setResult(Activity.RESULT_CANCELED, intent);
                    getActivity().finish();
                }
            });
            // Set chronometer
            chronometer.setBase(mService.getStartTime());
            chronometer.setVisibility(View.VISIBLE);
            chronometer.start();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mService = null;
        }
    };
    return root;
}

From source file:com.davidmiguel.gobees.monitoring.MonitoringService.java

License:Open Source License

/**
 * Config OpenCV (config callback and init OpenCV).
 * When OpenCV is ready, it starts monitoring.
 *//*w w  w.j ava2  s.c  o  m*/
private void configOpenCv() {
    // OpenCV callback
    BaseLoaderCallback loaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(final int status) {
            if (status == LoaderCallbackInterface.SUCCESS) {
                openCvLoaded = true;
                startMonitoring();
            } else {
                super.onManagerConnected(status);
            }
        }
    };
    // Init openCV
    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_2_0, this, loaderCallback);
}

From source file:com.raulh82vlc.face_detection_sample.opencv.presentation.FDOpenCVPresenter.java

License:Apache License

public BaseLoaderCallback getLoader(final Context context, final CameraBridgeViewBase openCvCameraView) {
    return new BaseLoaderCallback(context) {
        @Override//from   w  w  w  .  ja  v  a  2s. c  o  m
        public void onManagerConnected(int status) {
            switch (status) {
            case LoaderCallbackInterface.SUCCESS:
                Log.i(TAG, "OpenCV loaded successfully");
                try {
                    /** load face classificator */
                    File cascadeFileFace = FileHelper.readCascadeFile(context,
                            R.raw.haarcascade_frontalface_alt2, "cascade", "haarcascade_front.xml");
                    detectorFace = initializeJavaDetector(cascadeFileFace);
                    cascadeFileFace.delete();
                    /** load eye classificator */
                    File cascadeFileEye = FileHelper.readCascadeFile(context,
                            R.raw.haarcascade_eye_tree_eyeglasses, "cascadeER", "haarcascade_eye.xml");
                    detectorEye = initializeJavaDetector(cascadeFileEye);
                    cascadeFileEye.delete();
                    setMachineLearningMechanism();
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, "Failed to load cascade. Exception thrown: " + e);
                }

                setCameraParameters(openCvCameraView);

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

From source file:org.lasarobotics.vision.opmode.VisionOpModeCore.java

License:Open Source License

@Override
public void init() {
    //Initialize camera view
    BaseLoaderCallback openCVLoaderCallback = null;
    try {//from  w ww  .  j  ava  2  s . com
        openCVLoaderCallback = new BaseLoaderCallback(hardwareMap.appContext) {
            @Override
            public void onManagerConnected(int status) {
                switch (status) {
                case LoaderCallbackInterface.SUCCESS: {
                    //Woohoo!
                    Log.d("OpenCV", "OpenCV Manager connected!");
                    openCVInitialized = true;
                }
                    break;
                default: {
                    super.onManagerConnected(status);
                }
                    break;
                }
            }
        };
    } catch (NullPointerException e) {
        error("Could not find OpenCV Manager!\r\n" + "Please install the app from the Google Play Store.");
    }

    final Activity activity = (Activity) hardwareMap.appContext;
    final VisionOpModeCore t = this;

    if (!OpenCVLoader.initDebug()) {
        Log.d("OpenCV", "Internal OpenCV library not found. Using OpenCV Manager for initialization");
        boolean success = OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, hardwareMap.appContext,
                openCVLoaderCallback);
        if (!success) {
            Log.e("OpenCV", "Asynchronous initialization failed!");
            error("Could not initialize OpenCV!\r\n"
                    + "Did you install the OpenCV Manager from the Play Store?");
        } else {
            Log.d("OpenCV", "Asynchronous initialization succeeded!");
        }
    } else {
        Log.d("OpenCV", "OpenCV library found inside package. Using it!");
        if (openCVLoaderCallback != null)
            openCVLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        else {
            Log.e("OpenCV", "Failed to load OpenCV from package!");
            return;
        }
    }

    while (!openCVInitialized) {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            LinearLayout layout = new LinearLayout(activity);
            layout.setOrientation(LinearLayout.VERTICAL);

            layout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));

            openCVCamera = new JavaCameraView(hardwareMap.appContext, 0);

            layout.addView(openCVCamera);
            layout.setVisibility(View.VISIBLE);

            openCVCamera.setCvCameraViewListener(t);
            if (openCVCamera != null)
                openCVCamera.disableView();
            openCVCamera.enableView();
            if (!openCVCamera.connectCamera(initialMaxSize, initialMaxSize))
                error("Could not initialize camera!\r\n"
                        + "This may occur because the OpenCV Manager is not installed,\r\n"
                        + "CAMERA permission is not allowed in AndroidManifest.xml,\r\n"
                        + "or because another app is currently locking it.");

            //Initialize FPS counter and sensors
            fps = new FPS();
            sensors = new Sensors();

            //Done!
            width = openCVCamera.getFrameWidth();
            height = openCVCamera.getFrameHeight();
            initialized = true;
        }
    });

    while (!initialized) {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:samples.FtcTestOpenCv.java

License:Open Source License

@Override
public void initRobot() {
    hardwareMap.logDevices();/*  w w  w  .  j  a v a2s . c o m*/
    dashboard = HalDashboard.getInstance();
    activity = (FtcRobotControllerActivity) hardwareMap.appContext;
    loaderCallback = new BaseLoaderCallback(activity) {
        /**
         * This method is called when the OpenCV manager is connected. It loads the
         * OpenCV library and the appropriate CascadeClassifier.
         *
         * @param status specifies the OpenCV connection status.
         */
        @Override
        public void onManagerConnected(int status) {
            final String funcName = "onManagerConnected";

            switch (status) {
            case LoaderCallbackInterface.SUCCESS:
                File cascadeFile = null;
                tracer.traceInfo(funcName, "OpenCV loaded successfully.");
                System.loadLibrary("opencv_java3");
                try {
                    // load cascade file from application resources
                    InputStream is = activity.getResources().openRawResource(classifier);
                    File cascadeDir = activity.getDir("cascade", Context.MODE_PRIVATE);
                    cascadeFile = new File(cascadeDir, "frontalface.xml");
                    FileOutputStream os = new FileOutputStream(cascadeFile);

                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = is.read(buffer)) != -1) {
                        os.write(buffer, 0, bytesRead);
                    }
                    is.close();
                    os.close();

                    faceDetector = new CascadeClassifier(cascadeFile.getAbsolutePath());
                    if (faceDetector.empty()) {
                        tracer.traceErr(funcName, "Failed to load cascade classifier <%s>",
                                cascadeFile.getAbsolutePath());
                        faceDetector = null;
                    } else {
                        tracer.traceInfo(funcName, "Cascade classifier <%s> loaded!",
                                cascadeFile.getAbsolutePath());
                    }
                    cascadeDir.delete();
                } catch (IOException e) {
                    e.printStackTrace();
                    tracer.traceErr(funcName, "Failed to load cascade file <%s>",
                            cascadeFile.getAbsolutePath());
                }
                //                            cameraPreview.onResume();
                cameraView.enableView();
                break;

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

    //        cameraPreview = (GLSurfaceView)activity.findViewById(R.id.CameraPreview);
    //        overlayView = (ImageView)activity.findViewById(R.id.OverlayView);
    cameraView = (CameraBridgeViewBase) activity.findViewById(R.id.ImageView01);
    cameraView.setCameraIndex(1); //use front camera
    if (cameraEnabled) {
        cameraView.setCvCameraViewListener(this);
    }
}

From source file:ve.ucv.ciens.ccg.nxtar.MainActivity.java

License:Apache License

/**
 * <p>Initializes this activity</p>
 * /*ww w .j av a 2s  .  c om*/
 * <p>This method handles the initialization of LibGDX and OpenCV. OpenCV is
 * loaded the asynchronous method if the devices is not an OUYA console.</p>
 * 
 * @param savedInstanceState The application state if it was saved in a previous run.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    cameraCalibrated = false;

    // Set screen orientation. Portrait on mobile devices, landscape on OUYA.
    if (!Ouya.runningOnOuya) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    // Set up the Android related variables.
    uiHandler = new Handler();
    uiContext = this;
    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    // Attempt to initialize OpenCV.
    if (!Ouya.runningOnOuya) {
        // If running on a moble device, use the asynchronous method aided
        // by the OpenCV Manager app.
        loaderCallback = new BaseLoaderCallback(this) {
            @Override
            public void onManagerConnected(int status) {
                switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                    // If successfully initialized then load the native method implementations and
                    // initialize the static matrices.
                    System.loadLibrary("cvproc");
                    ocvOn = true;
                    cameraMatrix = new Mat();
                    distortionCoeffs = new Mat();
                    break;

                default:
                    Toast.makeText(uiContext, R.string.ocv_failed, Toast.LENGTH_LONG).show();
                    ocvOn = false;
                    break;
                }
            }
        };

        // Launch the asynchronous initializer.
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_7, this, loaderCallback);

    } else {
        // If running on an OUYA device.
        if (ocvOn) {
            // If OpenCV loaded successfully then initialize the native matrices.
            cameraMatrix = new Mat();
            distortionCoeffs = new Mat();
        } else {
            Toast.makeText(uiContext, R.string.ocv_failed, Toast.LENGTH_LONG).show();
        }
    }

    // Configure LibGDX.
    AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
    cfg.useAccelerometer = true;
    cfg.useCompass = true;
    cfg.useWakelock = true;

    // Launch the LibGDX core game class.
    initialize(new NxtARCore(this), cfg);
}