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

邮差的信 提交于 2019-11-29 05:22:33

I use something like this to check versions and hardware being used for OpenCL support.

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;
}

Then you can set your preferred hardware to use, using this

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

Hope this helps you.

You can also set a desired OpenCL device from within your code using environment variable method as follows (example is first GPU device):

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;
}

Call to cv::ocl::useOpenCL() will force OpenCV to setup a default OpenCL device to the one specified in the environment variable OPENCV_OPENCL_DEVICE which is setup prior to that call.

I checked that this actually happens by setting a break-point at opencv_core310d.dll!cv::ocl::selectOpenCLDevice() Line 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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!