如何更改在 OpenCV 中使用 Umat 执行 OpenCL 代码的设备?

How can I change the device on which OpenCL-code will be executed with Umat in OpenCV?

众所周知,OpenCV 3.0 支持新的 class cv::Umat which provides Transparent API (TAPI) to use OpenCL automaticaly if it can: http://code.opencv.org/projects/opencv/wiki/Opencv3#tapi

cv::Umat和TAPI有两个介绍:

但是如果我有:

  1. 英特尔 CPU Core i5 (Haswell) 4xCores (OpenCL Intel CPUs with SSE 4.1, SSE 4.2 or AVX support)
  2. 英特尔集成高清显卡 supports OpenCL 1.2
  3. 第一个 nVidia GPU GeForce GTX 970 (Maxwell) supports OpenCL 1.2 和 CUDA
  4. 第二个 nVidia GPU GeForce GTX 970 ...

如果我在 OpenCV 中打开 OpenCL,那么我如何更改执行 OpenCL 代码的设备:CPU 的 8 核,集成高清显卡,第一个 nVidia GPU 或第二个nVidia GPU?

我如何 select 这 4 台设备中的每台设备都可以使用 OpenCL 与 cv::Umat 并行执行算法?

例如,我如何在 CPU Core-i5 的 4xCores 和 cv::Umat 上使用 OpenCL 加速?

我使用类似的方法来检查用于 OpenCL 支持的版本和硬件。

ocl::setUseOpenCL(true);
if (!ocl::haveOpenCL())
{
    cout << "OpenCL is not available..." << endl;
    //return;
}

cv::ocl::Context context;
if (!context.create(cv::ocl::Device::TYPE_GPU))
{
    cout << "Failed creating the context..." << endl;
    //return;
}

cout << context.ndevices() << " GPU devices are detected." << endl; //This bit provides an overview of the OpenCL devices you have in your computer
for (int i = 0; i < context.ndevices(); i++)
{
    cv::ocl::Device device = context.device(i);
    cout << "name:              " << device.name() << endl;
    cout << "available:         " << device.available() << endl;
    cout << "imageSupport:      " << device.imageSupport() << endl;
    cout << "OpenCL_C_Version:  " << device.OpenCL_C_Version() << endl;
    cout << endl;
}

然后您可以设置要使用的首选硬件,使用这个

cv::ocl::Device(context.device(1));

希望对您有所帮助。

您还可以使用环境变量方法从代码中设置所需的 OpenCL 设备,如下所示(示例是第一个 GPU 设备):

if (putenv("OPENCV_OPENCL_DEVICE=:GPU:0") != 0 || !cv::ocl::useOpenCL())
{
    std::cerr << "Failed to set a desired OpenCL device" << std::endl;
    std::cerr << "Press any key to exit..." << std::endl;
    getchar();
    return 1;
}

调用 cv::ocl::useOpenCL() 将强制 OpenCV 将默认 OpenCL 设备设置为在调用之前设置的环境变量 OPENCV_OPENCL_DEVICE 中指定的设备。

我通过在 opencv_core310d.dll!cv::ocl::selectOpenCLDevice() 行 2256 (opencv\source\modules\core\src\ocl.cpp):

static cl_device_id selectOpenCLDevice()
{
    std::string platform, deviceName;
    std::vector<std::string> deviceTypes;

    const char* configuration = getenv("OPENCV_OPENCL_DEVICE");
    if (configuration &&
            (strcmp(configuration, "disabled") == 0 ||
             !parseOpenCLDeviceConfiguration(std::string(configuration), platform, deviceTypes, deviceName)
            ))
        return NULL;