先搭建好开发环境:Android - OpenCv - 开发环境(导入module)
已搭建的直接如下实操:
效果
布局
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt"
android:text="原图"
android:onClick="Bt"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt_gray"
android:text="灰度"
android:onClick="Gray"/>
</LinearLayout>
<ImageView
android: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);
//矩阵 转 bitmap
Utils.matToBitmap(dst, bitmap);
//显示图片
imageView.setImageBitmap(bitmap);
完整代码(Java)
public class MainActivity extends AppCompatActivity {
ImageView imageView;
Bitmap bitmap;
Button gray,bt;
@Override
protected 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);
//矩阵 转 bitmap
Utils.matToBitmap(dst, bitmap);
imageView.setImageBitmap(bitmap);
}
}