package com.yeyupiaoling.teststadiometry; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.os.Bundle; import android.util.Log; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import org.opencv.android.OpenCVLoader; import java.io.IOException; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getName(); private ImageView imageViewResult; private StereoBMUtil stereoBMUtil; private TextView textView; private Bitmap leftBitmap; private Bitmap rightBitmap; @SuppressLint("ClickableViewAccessibility") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化 if (OpenCVLoader.initDebug()) { Log.d(TAG, "OpenCVLoader初始化成功"); } stereoBMUtil = new StereoBMUtil(); ImageView imageViewLeft = findViewById(R.id.imageViewLeft); ImageView imageViewRight = findViewById(R.id.imageViewRight); imageViewResult = findViewById(R.id.imageViewResult); textView = findViewById(R.id.result_tv); Button button = findViewById(R.id.button); Button button1 = findViewById(R.id.button1); // 加载图片 try { leftBitmap = BitmapFactory.decodeStream(getAssets().open("Left3.bmp")); rightBitmap = BitmapFactory.decodeStream(getAssets().open("Right3.bmp")); imageViewLeft.setImageBitmap(leftBitmap); imageViewRight.setImageBitmap(rightBitmap); } catch (IOException e) { e.printStackTrace(); } // 执行StereoBM算法 button.setOnClickListener(v -> { try { Bitmap result = stereoBMUtil.compute(leftBitmap, rightBitmap); imageViewResult.setImageBitmap(result); } catch (Exception e) { e.printStackTrace(); } }); // 打开相机activity button1.setOnClickListener(v -> { Intent intent = new Intent(MainActivity.this, CameraActivity.class); startActivity(intent); }); // 点击计算后的图片,获取三维坐标数据 imageViewResult.setOnTouchListener((v, event) -> { // 获取触摸点的坐标 x, y float x = event.getX(); float y = event.getY(); // 目标点的坐标 float[] dst = new float[2]; Matrix imageMatrix = imageViewResult.getImageMatrix(); Matrix inverseMatrix = new Matrix(); imageMatrix.invert(inverseMatrix); inverseMatrix.mapPoints(dst, new float[]{x, y}); int dstX = (int) dst[0]; int dstY = (int) dst[1]; // 获取该点的三维坐标 double[] c = stereoBMUtil.getCoordinate(dstX, dstY); String s = String.format("点(%d, %d) 三维坐标:[%.2f, %.2f, %.2f]", dstX, dstY, c[0], c[1], c[2]); Log.d(TAG, s); textView.setText(s); return true; }); } }