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:

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(,, 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. 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. must define path to CUDA toolkit via CUDA_TOOLKIT_DIR parameter. By default, 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:


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

public void onResume()
if (OpenCVLoader.initDebug(true))
// Check CUDA support
if (Gpu.getCudaEnabledDeviceCount() <= 0)
Log.e(TAG, "No CUDA capable device found!");
AlertDialog InitFailedDialog = new
InitFailedDialog.setTitle("OpenCV CUDA error");
"CUDA compatible device was not found!"
"OK", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Load native library after(!) OpenCV initialization
Log.i(TAG, "Found CUDA capable device!");




NVIDIA® GameWorks™ Documentation Rev. 1.0.220830 ©2014-2022. NVIDIA Corporation and affiliates. All Rights Reserved.