简体   繁体   中英

Open OpenCV Camera via Button on Android Studio

My main activity has a button and I want that button to redirect me to the opencv camera. I have this code below and my app won't open anymore.

MainActivity.java

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import nerds.thesis.clartips.adapter.ListProductAdapter;
import nerds.thesis.clartips.database.DatabaseHelper;
import nerds.thesis.clartips.model.Product;

public class CLARTIPS_Home extends AppCompatActivity {

    private ListView lvProduct;
    private ListProductAdapter adapter;
    private List<Product> mProductList;
    private DatabaseHelper mDBHelper;

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

        lvProduct = (ListView) findViewById(R.id.listview_product);
        mDBHelper = new DatabaseHelper(this);

        Button tryMe = (Button) findViewById(R.id.tryMe);

        tryMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCam();
            }
        });

        //Check exists database
        File database = getApplicationContext().getDatabasePath(DatabaseHelper.DBNAME);
        if(false==database.exists()) {
            mDBHelper.getReadableDatabase();
            //Copy db
            if (copyDatabase(this)) {
                Toast.makeText(this, "Success Copying Database", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Error Copying Database", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        //Get product list in db when db exists
        mProductList = mDBHelper.getListProduct();
        //Init adapter
        adapter = new ListProductAdapter(this,mProductList);
        //Set adapter for listview
        lvProduct.setAdapter(adapter);
    }

    private boolean copyDatabase(Context context) {
        try {
            InputStream inputStream = context.getAssets().open(DatabaseHelper.DBNAME);
            String outFileName = DatabaseHelper.DBLOCATION + DatabaseHelper.DBNAME;
            OutputStream outputStream = new FileOutputStream(outFileName);
            byte[]buff = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buff)) > 0) {
                outputStream.write(buff, 0, length);
            }
            outputStream.flush();
            outputStream.close();
            Log.w("MainActivity","DB copied");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected (MenuItem item){
        switch (item.getItemId()) {
            case R.id.about:
                Intent aboutIntent = new Intent(CLARTIPS_Home.this, About.class);
                startActivity(aboutIntent);
        }
        return super.onOptionsItemSelected(item);
    }

    private void showCam(){
        Intent intent = new Intent(this, MA_show_camera.class);

        startActivity(intent);
    }
}

MA_show_camera.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.WindowManager;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

//OpenCV Classes

public class MA_show_camera extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {
    //Used for logging success or failure messages
    private static final String TAG = "OCVSample::Activity";

    //Loads camera view of OpenCV for us to use. This lets us to see using OpenCV
    private CameraBridgeViewBase mOpenCvCameraView;

    //Used in Camera selection from menu (when implemented)
    private boolean mIsJavaCamera = true;
    private MenuItem mItemSwitchCamera = null;

    //These variables are used (at the moment) to fix camera orientation form 270degree to 0degree
    Mat mRgba;
    Mat mRgbaF;
    Mat mRgbaT;

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status){
                case LoaderCallbackInterface.SUCCESS:
                {
                    Log.i(TAG, "OpenCV loaded successfully");
                    mOpenCvCameraView.enableView();
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };

    public  MA_show_camera(){
        Log.i(TAG, "Instantiated new " + this.getClass());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "called onCreate");
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.show_camera);

        mOpenCvCameraView = (JavaCameraView) findViewById(R.id.show_camera_activity_java_surface_view);

        mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);

        mOpenCvCameraView.setCvCameraViewListener(this);
    }

    @Override
    public void onPause(){
        super.onPause();
        if(mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }

    @Override
    public void onResume(){
        super.onResume();
        if(!OpenCVLoader.initDebug()){
            Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for Initialization");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_4_0, this, mLoaderCallback);
        } else{
            Log.d(TAG, "Internal OpenCV found inside package. Using it!");
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }
    }

    public void onDestroy(){
        super.onDestroy();
        if(mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }


    @Override
    public void onCameraViewStarted(int width, int height) {
        mRgba = new Mat(height, width, CvType.CV_8UC4);
        mRgbaF = new Mat(height, width, CvType.CV_8UC4);
        mRgbaT = new Mat(height, width, CvType.CV_8UC4);
    }

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

    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
        //TODO Auto-generated method sub
        mRgba = inputFrame.rgba();
        //Rotate mRgba 90 degrees
        Core.transpose(mRgba, mRgbaT);
        Imgproc.resize(mRgbaT, mRgbaF, mRgbaF.size(), 0,0, 0);
        Core.flip(mRgbaF, mRgba, 1);

        return mRgba; //This function must return
    }
}

I found a tutorial on how to open the camera (the code I used above) but it opens right when you open the app and I wanted it to open via button so I used intent. I'm a beginner so I only know a little about opencv and android development.

you need to pass an extra parameter in the

 void startActivityForResult (Intent intent, int requestCode) ; 

You can look at the docs for more information. https://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent,int)

hope this helps

In your main activity , in the onTouch() , you can replace openCam() with

Intent myIntent = new Intent(CLARTIPS_Home.this, MA_show_camera.class);
CLARTIPS_Home.this.startActivity(myIntent);

The in your camera Activity you can get a handle on it like so

@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM