我正在尝试开发一个图像识别Android应用程序...我正在使用表面视图的自定义相机.... As Here在android中捕获图像...我想使用处理捕获的图像opencv,我怎样才能获得捕获的图像并将其转换为mat?还有一种方法可以保存捕获的图像临时吗?提前谢谢
答案 0 :(得分:2)
我假设您已成功将opencv库添加到项目中。
以下是使用OpenCV4android的示例代码。
public class SampleCameraFrameAccessActivity extends Activity implements CvCameraViewListener2, OnTouchListener{
private static final String TAG = "SampleCameraFrameAccessActivity";
protected CameraBridgeViewBase cameraPreview;
protected Mat mRgba;
protected BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
// mOpenCvCameraView.enableView();
// mOpenCvCameraView.setOnTouchListener(ColorRegionDetectionActivity.this);
cameraPreview.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_sample_layout);
cameraPreview = (CameraBridgeViewBase) findViewById(R.id.sample_test_camera_view);
cameraPreview.setCvCameraViewListener(this);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(cameraPreview != null){
cameraPreview.disableView();
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
}
@Override
public void onCameraViewStarted(int width, int height) {
// TODO Auto-generated method stub
mRgba = new Mat(height, width, CvType.CV_8UC4);
}
@Override
public void onCameraViewStopped() {
// TODO Auto-generated method stub
mRgba.release();
}
@Override
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
// TODO Auto-generated method stub
mRgba = inputFrame.rgba();
return mRgba;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
XML Layout文件是:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/sample_test_layout" >
<org.opencv.android.JavaCameraView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/sample_test_camera_view" />
</RelativeLayout>
在onCameraFrame方法中,您可以从相机的帧缓冲区访问每一帧。如果要捕获图像,可以添加按钮并从缓冲区中获取特定帧并进行处理。默认情况下,框架以Mat对象的形式给出。所以你不必转换它。处理完后,如果需要将其转换为位图, 你可以调用Utils.matToBitmap(mat,bmp);这样做的方法。