我的应用程序无法存储使用OpenCV Library拍摄的图像

时间:2016-04-15 13:54:41

标签: android opencv android-camera

我正在开发一个用于人脸识别的Android应用程序,当我按下按钮存储图片时,我的应用程序停止了!! 这是我的代码活动添加图片:

      public class Add_Picture extends FragmentActivity implements CvCameraViewListener2 {

static {
    if (!OpenCVLoader.initDebug()) {
        // Handle initialization error
        Log.e("no","no");
    }
    else {
        Log.e("ok","ok");
    }
}

static
{
    // If you use opencv 2.4, System.loadLibrary("opencv_java")
    System.loadLibrary("opencv_java3");
}

private static final String    TAG = "Reconnaissance Faciale";


public static final int      VIEW_MODE_LISTFRAMES= 1;

private MenuItem listframes;

public static int viewMode;

private Mat mRgba;
private CameraBridgeViewBase   mOpenCvCameraView;
private DBhelper dbhelper;

private Button store;
private Button back;
private EditText text;
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 Add_Picture() {
    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(com.example.opencv_java_androidstudio.R.layout.activity_add__picture);
//  setContentView(R.layout.activity_add__picture);
    //setContentView(R.layout.activity_add__picture);
    //mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.camera);
    mOpenCvCameraView = (CameraBridgeViewBase) findViewById(com.example.opencv_java_androidstudio.R.id.camera);

    mOpenCvCameraView.setCvCameraViewListener(this);

    mOpenCvCameraView.setCameraIndex(1);
    mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
    //mOpenCvCameraView.setRotation(90);

    //store= (Button) findViewById(R.id.store);
    store= (Button) findViewById(com.example.opencv_java_androidstudio.R.id.store);

    store.setRotation(90);



    Mat test = new Mat(200, 200, CvType.CV_8UC1);
    Imgproc.equalizeHist(test, test);




    //mOpenCvCameraView.getDisplay();
}


     @Override
public boolean onCreateOptionsMenu(Menu menu) {
    listframes = menu.add("Faces list");

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item == listframes){
        viewMode = VIEW_MODE_LISTFRAMES;
        // Intent intent = new Intent(AjoutframeActivity.this, ListframeActivity.class);
        // startActivity(intent);
    }


    return true;
}

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

@Override
public void onResume()
{
    super.onResume();
    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
}

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

public void onCameraViewStarted(int width, int height) {
    mRgba = new Mat(height, width, CvType.CV_8UC4);


}

public void onCameraViewStopped() {
    mRgba.release();

}

public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    mRgba=inputFrame.rgba();

    store.setOnClickListener(new OnClickListener() {



        @Override
        public void onClick(View v1){


            storeframesiDB(mRgba);


        }
    });


    return mRgba;
}





public void storeframesiDB(Mat mat){

    MatOfKeyPoint points = new MatOfKeyPoint();
    FeatureDetector surf = FeatureDetector.create(FeatureDetector.ORB);
    DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.BRIEF);

    surf.detect(mat, points);

    Mat descriptors = new Mat();
    extractor.compute(mat, points, descriptors);
    int rows=descriptors.rows();

    String str=Frametraitement.matToJson(descriptors);


    dbhelper = new DBhelper(this);
    //text= (EditText) findViewById(R.id.storage);
    text= (EditText) findViewById(com.example.opencv_java_androidstudio.R.id.storage);


    String textstore= text.getText().toString();

    Frameclass fr = new Frameclass(textstore,str,rows);
    text.setText("");
    dbhelper.open();
    dbhelper.insertframeDetails(fr);
    dbhelper.close();




}
    }

My Logcat向我显示:无法为OpenCV加载信息库。

这是我的课堂上的图像的讽刺:

     public class Frametraitement {
private static final String TAG = "RF";

private DBhelper dbhelper;



public static Mat matRetrieve(String filePath, int rows, int cols, int type){
    Log.d(TAG, "matRetrieve - path: " + filePath);

    if(isExternalStorageReadable()){

        File matFile = new File(filePath);

        InputStream in = null;
        try {
            in = new FileInputStream(matFile);

            byte[] data = convertInputStreamToByteArray(in);

            //Mat result = new Mat(320, 212, CvType.CV_8UC1);

            Mat result = new Mat(rows, cols, type);
            result.put(0, 0, data);

            return result;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    } else {
        Log.e(TAG, "External Storage not readable.");
    }

    return null;
}

public static byte[] matStore( Mat mat){
    //Log.d(TAG, "matStore - path: "+filePath);
    byte[] data=null;
    if(isExternalStorageWritable() && mat.isContinuous()){
        int cols = mat.cols();
        int rows = mat.rows();
        int elemSize = (int) mat.elemSize(); // or  mat.channels() ?

        data= new byte[cols * rows * elemSize];

        mat.get(0, 0, data);
        Log.e(TAG, "data"+ data);

        Log.e(TAG, "mat"+ mat);
    } else {
        Log.e(TAG, "External Storage not writable.");
    }
    return data;

}

public static String matToJson(Mat mat){
    Log.i(TAG, "matToJson");

    JsonObject obj = new JsonObject();

    if(mat.isContinuous()){
        int cols = mat.cols();
        int rows = mat.rows();
        int elemSize = (int) mat.elemSize();

        byte[] data = new byte[cols * rows * elemSize];

        mat.get(0, 0, data);

        obj.addProperty("rows", mat.rows());
        obj.addProperty("cols", mat.cols());
        obj.addProperty("type", mat.type());
        String dataString = new String(Base64.encode(data, Base64.DEFAULT));

        Log.d(TAG, "matToJson - boooom: "+dataString);

        obj.addProperty("data", dataString);


        Gson gson = new Gson();
        String json = gson.toJson(obj);


        return json;
    } else {
        Log.e(TAG, "Mat not continuous.");
    }
    return "{}";
}


public static Mat matFromJson(String json){
    Log.d(TAG, "matToJson");

    JsonParser parser = new JsonParser();
    JsonObject JsonObject = parser.parse(json).getAsJsonObject();

    int rows = JsonObject.get("rows").getAsInt();
    int cols = JsonObject.get("cols").getAsInt();
    int type = JsonObject.get("type").getAsInt();

    String dataString = JsonObject.get("data").getAsString();
    byte[] data = Base64.decode(dataString.getBytes(), Base64.DEFAULT);

    Mat mat = new Mat(rows, cols, type);
    mat.put(0, 0, data);
    Log.e(TAG,"matfromjson"+mat);

    return mat;
}








private static byte[] convertInputStreamToByteArray(InputStream inputStream) {
    byte[] bytes= null;

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        byte buff[] = new byte[1024];
        int count;

        while ((count = inputStream.read(buff)) != -1) {
            bos.write(buff, 0, count);
        }

        bos.flush();
        bos.close();
        inputStream.close();

        bytes = bos.toByteArray();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return bytes;
}

/* Checks if external storage is available for read and write */
public static boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

/* Checks if external storage is available to at least read */
public static boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
            Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

public static byte[] getBytes(String ch) {

    Mat mat=matFromJson(ch);
    //Log.e(TAG,"chaine"+ch);
    return matStore(mat);
}



public static Mat getmatfrombyte(byte[] data, int rows, int cols) {

    Mat result = new Mat(rows, cols, CvType.CV_8UC1);
    result.put(0, 0, data);

    return result;


}

public static Mat calculdescriptors(Mat mat){

    MatOfKeyPoint points = new MatOfKeyPoint();
    FeatureDetector surf = FeatureDetector.create(FeatureDetector.ORB);
    DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.BRIEF);

    surf.detect(mat, points);
    int nbrepts=   points.toList().size();

    Mat descriptors = new Mat();
    extractor.compute(mat, points, descriptors);


    return descriptors;
}





public static MatOfDMatch matching(Mat matcour,Mat mattrain){


    DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);

    MatOfDMatch matches = new MatOfDMatch();

    matcher.match(matcour, mattrain, matches);
    matches.toList();
    Log.e(TAG,"matches "+matches.toList());
    return filterMatchesByDistance(matches);
}




public static MatOfDMatch filterMatchesByDistance(MatOfDMatch matches){
    List<org.opencv.core.DMatch> matches_original = matches.toList();
    List<org.opencv.core.DMatch> matches_filtered = new ArrayList<>();

    int DIST_LIMIT = 30;
    // Check all the matches distance and if it passes add to list of filtered matches
    Log.d("DISTFILTER", "ORG SIZE:" + matches_original.size() + "");
    for (int i = 0; i < matches_original.size(); i++) {
        org.opencv.core.DMatch d = matches_original.get(i);
        if (Math.abs(d.distance) <= DIST_LIMIT) {
            matches_filtered.add(d);
        }
    }
    Log.d("DISTFILTER", "FIL SIZE:" + matches_filtered.size() + "");

    MatOfDMatch mat = new MatOfDMatch();
    mat.fromList(matches_filtered);
    return mat;
}
}

0 个答案:

没有答案