在Android Studio中使用OpenCV从手机中加载图像,你可以按照以下步骤进行操作:
implementation project(':opencv')
import org.opencv.android.OpenCVLoader;
public class MainActivity extends AppCompatActivity implements LoaderCallbackInterface {
static {
if (!OpenCVLoader.initDebug()) {
// OpenCV initialization failed
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!OpenCVLoader.initDebug()) {
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_4_0, this, this);
} else {
onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
// OpenCV initialization successful
break;
default:
super.onManagerConnected(status);
break;
}
}
@Override
public void onPackageInstall(int operation, InstallCallbackInterface callback) {
// Handle package installation if needed
}
}
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="@+id/loadButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Image" />
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class MainActivity extends AppCompatActivity implements LoaderCallbackInterface {
private ImageView imageView;
private Button loadButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
loadButton = findViewById(R.id.loadButton);
loadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Load image from device storage
Mat image = Imgcodecs.imread("/sdcard/image.jpg");
// Resize image if needed
Size newSize = new Size(640, 480);
Imgproc.resize(image, image, newSize);
// Convert image to bitmap and display in ImageView
Bitmap bitmap = Bitmap.createBitmap(image.cols(), image.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(image, bitmap);
imageView.setImageBitmap(bitmap);
}
});
}
// Other methods for OpenCV initialization and package installation handling
}
以上代码假设你的图像文件位于设备存储的根目录下,并且命名为image.jpg。你可以根据实际情况修改文件路径和名称。
这样,当你点击"Load Image"按钮时,OpenCV将从设备存储中加载图像,并在ImageView中显示出来。
请注意,这只是一个简单的示例,你可以根据自己的需求进行更复杂的图像处理操作。另外,为了更好地了解OpenCV的功能和用法,你可以参考腾讯云的OpenCV产品文档:OpenCV产品介绍。
领取专属 10元无门槛券
手把手带您无忧上云