1、下载OpenCV的Android包并解压缩。
下载:https://opencv.org/releases/
2、创建Android应用或者在现有应用中,导入OpenCV模块。
// Import module: Menu -> “File” -> “New” -> “Module” -> “Import Gradle project”:
// Source directory: select this “sdk” directory
// Module name: “:opencv”
3、修改导入的opencv4.7模块的build.gradle,使compileSdkVersion、minSdkVersion、targetSdkVersion与app的build.gradle中的一致。
4、加入依赖(Dependency)。
打开app的build.gradle,可以看到依赖已经被添加进去。
5、在使用OpenCV的Activity中,加入测试代码。
package com.test; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.navigation.fragment.NavHostFragment; import com.test.databinding.FragmentFirstBinding; import org.opencv.android.OpenCVLoader; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.imgproc.Imgproc; public class FirstFragment extends Fragment { private FragmentFirstBinding binding; @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) { binding = FragmentFirstBinding.inflate(inflater, container, false); return binding.getRoot(); } public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ImageView iv; iv = view.findViewById(R.id.img_logo); boolean success = OpenCVLoader.initDebug(); if (success) { Toast.makeText(getActivity(), "加载 OpenCV Libraries 成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), "加载 OpenCV Libraries 失败", Toast.LENGTH_SHORT).show(); } Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon); Mat src = new Mat(); Mat dst = new Mat(); Utils.bitmapToMat(bitmap, src); Imgproc.cvtColor(src,dst, Imgproc.COLOR_BGR2GRAY); Utils.matToBitmap(dst, bitmap); iv.setImageBitmap(bitmap); src.release(); dst.release(); binding.buttonFirst.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { NavHostFragment.findNavController(FirstFragment.this) .navigate(R.id.action_FirstFragment_to_SecondFragment); } }); } @Override public void onDestroyView() { super.onDestroyView(); binding = null; } }
灰度图像