先搭建好开发环境:Android – OpenCv – 开发环境(导入module)
已搭建的直接如下实操:
效果
布局
<LinearLayoutandroid:layout_width=\"wrap_content\"android:layout_height=\"wrap_content\"android:orientation=\"horizontal\"><Buttonandroid:layout_width=\"wrap_content\"android:layout_height=\"wrap_content\"android:id=\"@+id/bt\"android:text=\"原图\"android:onClick=\"Bt\"/><Buttonandroid:layout_width=\"wrap_content\"android:layout_height=\"wrap_content\"android:id=\"@+id/bt_gray\"android:text=\"灰度\"android:onClick=\"Gray\"/></LinearLayout><ImageViewandroid:layout_width=\"wrap_content\"android:layout_height=\"wrap_content\"android:id=\"@+id/iv\"/>
Java
- OpenCv库初始化
private void staticLoadCVLibraries(){boolean load = OpenCVLoader.initDebug();if(load) {Log.i(\"CV\", \"OpenCV init success\");}else {Log.e(\"CV\", \"OpenCV init failed\");}}
- 灰度操作
Mat src = new Mat();Mat temp = new Mat();Mat dst = new Mat();//bitmap 转 矩阵Utils.bitmapToMat(bitmap, src);//色彩空间转换Imgproc.cvtColor(src, temp, Imgproc.COLOR_BGRA2BGR);Log.i(\"CV\", \"image type:\" + (temp.type() == CvType.CV_8UC3));// COLOR_BGR2GRAY : 颜色_BGR2灰色Imgproc.cvtColor(temp, dst, Imgproc.COLOR_BGR2GRAY);//矩阵 转 bitmapUtils.matToBitmap(dst, bitmap);//显示图片imageView.setImageBitmap(bitmap);
完整代码(Java)
public class MainActivity extends AppCompatActivity {ImageView imageView;Bitmap bitmap;Button gray,bt;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);staticLoadCVLibraries();gray = findViewById(R.id.bt_gray);bt = findViewById(R.id.bt);imageView = findViewById(R.id.iv);bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.picture);imageView.setImageBitmap(bitmap);}// OpenCV库初始化private void staticLoadCVLibraries(){boolean load = OpenCVLoader.initDebug();if(load) {Log.i(\"CV\", \"OpenCV init success\");}else {Log.e(\"CV\", \"OpenCV init failed\");}}public void Bt(View v){bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.picture);imageView.setImageBitmap(bitmap);}//灰度public void Gray(View v){Mat src = new Mat();Mat temp = new Mat();Mat dst = new Mat();//bitmap 转 矩阵Utils.bitmapToMat(bitmap, src);//色彩空间转换Imgproc.cvtColor(src, temp, Imgproc.COLOR_BGRA2BGR);Log.i(\"CV\", \"image type:\" + (temp.type() == CvType.CV_8UC3));// COLOR_BGR2GRAY : 颜色_BGR2灰色Imgproc.cvtColor(temp, dst, Imgproc.COLOR_BGR2GRAY);//矩阵 转 bitmapUtils.matToBitmap(dst, bitmap);imageView.setImageBitmap(bitmap);}}