How to get the actual point when I touch on screen?

只愿长相守 提交于 2019-12-07 09:01:01

问题


I am developing an android application where i can select region of interest(ROI) when i touch two points on screen. However, when i try to change the resolution of image, the thing goes weird. What it shows does not same with what i touched. Here are my codes,

MainActivity.java

public class MainActivity extends Activity implements CvCameraViewListener2, OnTouchListener {

    private static final String TAG = "OCVSample::Activity";

    private Camera_View mOpenCvCameraView;
    private List<Size> mResolutionList;
    private MenuItem[] mResolutionMenuItems;
    private SubMenu mResolutionMenu;
    private MenuItem mSaveTemplate;
    private MenuItem mTracking;

    int startX = 0, endX = 0, startY = 0, endY = 0;
    Point start_point, end_point;
    Scalar border_colour = new Scalar(255,0,0,0);
    boolean sequence = false;
    Rect roi_rect = new Rect();

    private Mat mZoomWindow;
    private Mat rgba;
    private Mat mytemplate;
    private Mat result;
    boolean tracking = false;
    int resolution_x, resolution_y;

    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();
                    mOpenCvCameraView.setOnTouchListener(MainActivity.this);//TODO
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        mOpenCvCameraView = (Camera_View) findViewById(R.id.java_surface_view);
        mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
        mOpenCvCameraView.setCvCameraViewListener(this);

        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int height = displaymetrics.heightPixels;
        int width = displaymetrics.widthPixels;
        resolution_x = width;
        resolution_y = height;
    }

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

    @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();
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        int idx = 0;
        mResolutionMenu = menu.addSubMenu("Resolution");
        mResolutionList = mOpenCvCameraView.getResolutionList();
        mResolutionMenuItems = new MenuItem[mResolutionList.size()];
        mSaveTemplate = menu.add("Save Template");
        mTracking = menu.add("TplMatch");

        ListIterator<Size> resolutionItr = mResolutionList.listIterator();
        idx = 0;
        while(resolutionItr.hasNext()) {
            Size element = resolutionItr.next();
            mResolutionMenuItems[idx] = mResolutionMenu.add(1, idx, Menu.NONE,
                    Integer.valueOf(element.width).toString() + "x" + Integer.valueOf(element.height).toString());
            idx++;
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getGroupId() == 1) {
            int id = item.getItemId();
            Size resolution = mResolutionList.get(id);
            mOpenCvCameraView.setResolution(resolution);
            resolution = mOpenCvCameraView.getResolution();
            resolution_x = resolution.width;
            resolution_y = resolution.height;
            String caption = resolution_x + "x" + resolution_y;
            Toast.makeText(this, caption, Toast.LENGTH_SHORT).show();
        }else if (item == mSaveTemplate){
            if (endX != 0 && endY != 0){
                SaveImage(rgba,roi_rect);
            }else
                Toast.makeText(this, "Please select Region of Interest", Toast.LENGTH_LONG).show();
        }else if (item == mTracking){
            tracking = !tracking;
            getPath();

        }

        return true;
    }

    @Override
    public void onCameraViewStarted(int width, int height) {

    }

    @Override
    public void onCameraViewStopped() {

    }

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

        if (startX!=0 && endX!=0 && !tracking){
            Core.rectangle(rgba,start_point,end_point,border_colour, 0, 0, 0);
            roi_rect = new Rect(start_point,end_point);
        }

        if(tracking){
            String infile = getFileAbsPath("image.jpg");
            getPath();
            mytemplate = Highgui.imread(filename, Highgui.CV_LOAD_IMAGE_UNCHANGED);

            Imgproc.cvtColor(mytemplate, mytemplate,CvType.CV_32FC1 , 3);

            Log.i (TAG, "Sizec = "+ mytemplate.cols() + "   Sizer = " +mytemplate.rows());

            int result_cols =  rgba.cols() - mytemplate.cols() + 1;
            int result_rows = rgba.rows() - mytemplate.rows() + 1;

            Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);

            /*org.opencv.core.Size size = new org.opencv.core.Size(7,7);
            GaussianBlur(rgba, rgba, size, 3.0);
            GaussianBlur(mytemplate, mytemplate, size, 3.0);*/

            /// Do the Matching and Normalize
            Imgproc.matchTemplate( rgba, mytemplate, result, Imgproc.TM_SQDIFF_NORMED );
            Core.normalize( result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());

            // / Localizing the best match with minMaxLoc
            MinMaxLocResult mmr = Core.minMaxLoc(result);

            Point matchLoc;
            matchLoc = mmr.minLoc;

            // / Show me what you got
            Core.rectangle(rgba, matchLoc, new Point(matchLoc.x + mytemplate.cols(),
                        matchLoc.y + mytemplate.rows()), new Scalar(0, 255, 0));
        }


        return rgba;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        int action = event.getActionMasked();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                if(sequence){
                    startX = (int)event.getX();
                    startY = (int)event.getY();
                    sequence = !sequence;
                }else{
                    endX = (int)event.getX();
                    endY = (int)event.getY();
                    sequence = !sequence;
                }
        }

        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int height = displaymetrics.heightPixels;
        int width = displaymetrics.widthPixels;

        //int offsetX = (int) ((width - resolution_x)/2.0);

        Log.i (TAG, "height: "+height+" width: "+width);

        startX = (int) ((float)startX/width*resolution_x);
        startY = (int) ((float)startY/height*resolution_y);
        endX = (int) ((float)endX/width*resolution_x);
        endY = (int) ((float)endY/height*resolution_y);

        start_point = new Point(startX,startY);
        end_point = new Point(endX,endY);

        Log.i (TAG, start_point +"    " +end_point+"  "+resolution_x+"    "+resolution_y);


        /*float eventX = event.getX();
        float eventY = event.getY();
        float[] eventXY = new float[] {eventX, eventY};

        int x = Integer.valueOf((int)eventXY[0]);
        int y = Integer.valueOf((int)eventXY[1]);

        if (event.getAction()==event.ACTION_DOWN){
            startX = x;
            startY = y;
        }
        if (event.getAction()==event.ACTION_UP){
            endX = x;
            endY = y;
        }

        start_point = new Point(startX,startY);
        end_point = new Point(endX,endY);*/


        return false;
    }
}

Camera_View.java

public class Camera_View extends JavaCameraView{
    private static final String TAG = "Camera View";
    private String mPictureFileName;

    public Camera_View(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public List<String> getEffectList() {
        return mCamera.getParameters().getSupportedColorEffects();
    }

    public boolean isEffectSupported() {
        return (mCamera.getParameters().getColorEffect() != null);
    }

    public String getEffect() {
        return mCamera.getParameters().getColorEffect();
    }

    public void setEffect(String effect) {
        Camera.Parameters params = mCamera.getParameters();
        params.setColorEffect(effect);
        mCamera.setParameters(params);
    }

    public List<Size> getResolutionList() {
        return mCamera.getParameters().getSupportedPreviewSizes();
    }

    public void setResolution(Size resolution) {
        disconnectCamera();
        mMaxHeight = resolution.height;
        mMaxWidth = resolution.width;
        connectCamera(getWidth(), getHeight());
    }

    public Size getResolution() {
        return mCamera.getParameters().getPreviewSize();
    }
}

I've tried this codes

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
startX = (int) ((float)startX/width*resolution_x);
startY = (int) ((float)startY/height*resolution_y);
endX = (int) ((float)endX/width*resolution_x);
endY = (int) ((float)endY/height*resolution_y);

to solve my problem but something went wrong. Can Anyone help me?

来源:https://stackoverflow.com/questions/34988449/how-to-get-the-actual-point-when-i-touch-on-screen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!