Android NDK开发:OpenCV实现图像锐化

目录

目录

实现效果

OpenCV配置

请查看:OpenCV On Android最佳环境配置指南(Android Studio篇)

代码实现

●布局文件




    

●Activity代码

public class MainActivity extends AppCompatActivity {
    private Button button;
    private ImageView imageView;
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.bt_change);
        imageView = findViewById(R.id.img);
        final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.opencv);
        imageView.setImageBitmap(bitmap);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeImage(bitmap);
                imageView.setImageBitmap(bitmap);
            }
        });
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native void changeImage(Object bitmap);
}

●C语言代码

#include 
#include 
#include 
#include 
using namespace cv;
extern "C"
JNIEXPORT void JNICALL
Java_com_example_myapplication_MainActivity_changeImage(JNIEnv *env, jobject instance,
                                                        jobject bitmap) {

    AndroidBitmapInfo info;
    void *pixels;

    CV_Assert(AndroidBitmap_getInfo(env, bitmap, &info) >= 0);
    CV_Assert(info.format == ANDROID_BITMAP_FORMAT_RGBA_8888 ||
              info.format == ANDROID_BITMAP_FORMAT_RGB_565);
    CV_Assert(AndroidBitmap_lockPixels(env, bitmap, &pixels) >= 0);
    CV_Assert(pixels);
    Mat kernel = (Mat_(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
    if (info.format == ANDROID_BITMAP_FORMAT_RGBA_8888) {
        Mat temp(info.height, info.width, CV_8UC4, pixels);
        filter2D(temp,temp,temp.depth(),kernel);//核心逻辑,通过这个函数实现锐化
    } else {
        Mat temp(info.height, info.width, CV_8UC2, pixels);
        filter2D(temp,temp,temp.depth(),kernel);
    }
    AndroidBitmap_unlockPixels(env, bitmap);

}

你可能感兴趣的:(Android NDK开发:OpenCV实现图像锐化)