3

我一直在开发一个 Android 应用程序,它只需要在相机预览上检索和显示触摸事件的坐标和 RGB 值。我是这种编程语言的初学者,我只是想尝试一下,但应用程序在触摸事件期间不断崩溃。这是我在 Android 中尝试的代码:

    /* When copying this code set Permissions: CAMERA
     * Do this by adding to AndroidManifest.xml:
     * <uses-permission
    android:name="android.permission.CAMERA" />
     */

    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.Color;
    import android.hardware.Camera;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Display;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.MotionEvent;
    import android.widget.FrameLayout;
    import android.widget.TextView;

    @SuppressWarnings("deprecation") 

    public class MainActivity extends Activity {
private static final String TAG = "HDMapp_MainActivity";    //ERROR Log tag
private Camera mCamera = null;
private CameraDisplay mCameraView = null;
static TextView touchView;
private Bitmap bmp;

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

    //try-catch block to try accessing the Android camera
    try {
        mCamera = Camera.open();
    } catch(Exception e) {
        Log.d(TAG, "Failed to get camera" + e.getMessage());
    }

    if (mCamera != null) {
        mCameraView = new CameraDisplay(this, mCamera); //create SurfaceView to show camera data
        FrameLayout camera_view = (FrameLayout)findViewById(R.id.camera_view);
        camera_view.addView(mCameraView); //add the SurfaceView to the layout
    }

    touchView = (TextView)findViewById(R.id.touchView);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

//detects touches on screen
@Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int)event.getX();
    int y = (int)event.getY();

    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();
    int height = display.getHeight();

    int pixelVal = bmp.getPixel(heightC,widthC);
    int r = (pixelVal>>16) & 0xFF;
    int g = Color.green(pixelVal);
    int b = Color.blue(pixelVal);

    touchView.setText("Touch coordinates--> " + "x: " +
            String.valueOf(event.getX()) + " y: " + String.valueOf(event.getY()) + 
            " \n" + r + " \n" + g + " \n" + b);

    return super.onTouchEvent(event);
}
    }

我收到 NullPointerException 错误:

E/MessageQueue-JNI(14476):java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“int android.graphics.Bitmap.getPixel(int, int)”

我也尝试使用OpenCV4Android,但仍然得到相同的结果:

    import org.opencv.android.BaseLoaderCallback;
    import org.opencv.android.CameraBridgeViewBase;
    import org.opencv.android.OpenCVLoader;
    import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
    import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
    import org.opencv.android.LoaderCallbackInterface;
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Display;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.MotionEvent;
    import android.view.SurfaceView;
    import android.view.WindowManager;
    import android.widget.TextView;

    public class MainActivity extends Activity implements CvCameraViewListener2 {
private CameraBridgeViewBase mOpenCvCameraView;
private Mat mRgba;
TextView touchView;
int x, y;
double [] rgb;

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i("OnCreate", "called onCreate");
    super.onCreate(savedInstanceState);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.activity_main);

    mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.surface_view);
    mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
    mOpenCvCameraView.setCvCameraViewListener(this);

    //touchView = (TextView)findViewById(R.id.touchView);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

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

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

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) {
    // TODO Auto-generated method stub
    mRgba = inputFrame.rgba();
    rgb = mRgba.get(x,y);

    return mRgba;
}   

//detects touches on screen
    @SuppressWarnings("deprecation")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        x = (int)event.getX();
        y = (int)event.getY();

        //Display display = getWindowManager().getDefaultDisplay();
        //int width = display.getWidth();
        //int height = display.getHeight();

        //double [] rgb = mRgba.get(width,height);

        touchView.setText("Touch coordinates--> " + "x: " + String.valueOf(x) 
                + " y: " + String.valueOf(y) + " \n" + "RGB values--> " + "Red: " + rgb[0]
                + " Green: " + rgb[1] + " Blue: " + rgb[2]);

        return super.onTouchEvent(event);
    }
    }

错误再次是:

E/MessageQueue-JNI(15884):java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.TextView.setText(java.lang.CharSequence)”

这两个应用程序都显示相机预览,但是当我触摸 Nexus 7 的屏幕时,应用程序停止工作。有人可以告诉我我做错了什么并可能纠正我吗?

4

1 回答 1

0

第二个例子应该可以工作,问题是 x 和 y 没有初始化,所以在onCameraFrame你初始化的方法中rgb = mRgba.get(x,y),在这之后rgb仍然是null,因为x并且y没有初始化。因此,nullPointerException当您尝试打印它时。

我的建议是你刚开始初始化xy开始-1

int x=-1, y=-1;

然后在触摸处理程序方法中更新 x 和 y ,如下所示:

public boolean onTouchEvent(MotionEvent event) {
    x = (int)event.getX();
    y = (int)event.getY();
    return super.onTouchEvent(event);
}

onCameraFrame方法中,您可以执行以下操作:

public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
  mRgba = inputFrame.rgba();
  if(x != -1 && y != -1) { //if this is true, you've touched something
    rgb = mRgba.get(x,y);
    touchView.setText("Touch coordinates--> " + "x: " + String.valueOf(x) 
            + " y: " + String.valueOf(y) + " \n" + "RGB values--> " + "Red: " + rgb[0]
            + " Green: " + rgb[1] + " Blue: " + rgb[2]);
    x = -1; 
    y = -1;
  }

return mRgba;
}

希望这可以帮助

于 2015-08-18T12:24:04.843 回答