OpenCV Tutorial 4: CUDA

The example demonstrates the simple way of using CUDA-accelerated opencv_gpu module in your Android application. The sample is a modification of the Tutorial 2 discussed above. Native part of the example implements the same FAST feature detector, but it calls CUDA implementation:

JNIEXPORT void JNICALL 
Java_org_opencv_samples_tutorial4_Tutorial4Activity_FindFeatures(JNIEnv*, jobject, jlong addrGray, jlong addrRgba)
{
Mat& mGr = *(Mat*)addrGray;
Mat& mRgb = *(Mat*)addrRgba;
vector<KeyPoint> keypoints;
GpuMat grGpu(mGr);
FAST_GPU fast(50);
fast(grGpu, GpuMat(), keypoints);
for( unsigned int i = 0; i < keypoints.size(); i++ )
{
const KeyPoint& kp = keypoints[i];
circle(mRgb, Point(kp.pt.x, kp.pt.y), 10, Scalar(255,0,0,255));
}
}

All CUDA-accelerated algorithms use special GpuMat container that stores its content in GPU memory. For more details about GpuMat and usage of CUDA-accelerated vision algorithms see in OpenCV reference manual.

Android.mk also has slightly different structure. opencv_gpu module is too big to distribute it as is with OpenCV Manager, so it is designed to be linked statically. It allows to cut all unnecessary functions in link time to decrease size of native libraries.

Opencv_gpu module depends on CUDA runtime library and some CUDA-accelerated mathematical libraries like NPP and CUFFT. Android.mk must define path to CUDA toolkit via CUDA_TOOLKIT_DIR parameter. By default, Android.mk uses CUDA_TOOLKIT_ROOT environment variable that is set by the CodeWorks for Android installer. Furthermore, CUDA runtime library and math libraries are not a part of Android firmware, so a CUDA-accelerated application must contain them in the APK package. To enable CUDA libraries installation in application package, additional options must be added:

INSTALL_CUDA_LIBRARIES:=on

To prevent sample execution on non-CUDA devices hardware check is placed in Java code:

public void onResume()
{
super.onResume();
if (OpenCVLoader.initDebug(true))
{
// Check CUDA support
if (Gpu.getCudaEnabledDeviceCount() <= 0)
{
Log.e(TAG, "No CUDA capable device found!");
AlertDialog InitFailedDialog = new
AlertDialog.Builder(Tutorial4Activity.this).create();
InitFailedDialog.setTitle("OpenCV CUDA error");
InitFailedDialog.setMessage(
"CUDA compatible device was not found!"
);
InitFailedDialog.setCancelable(false);
InitFailedDialog.setButton(AlertDialog.BUTTON_POSITIVE,
"OK", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Tutorial4Activity.this.finish();
}
});
InitFailedDialog.show();
}
else
{
// Load native library after(!) OpenCV initialization
Log.i(TAG, "Found CUDA capable device!");
System.loadLibrary("cuda_sample");
mOpenCvCameraView.enableView();
}
}
}

 

 

 


NVIDIA® GameWorks™ Documentation Rev. 1.0.200605 ©2014-2020. NVIDIA Corporation. All Rights Reserved.