介绍:
本篇文章的目的是使用OpenCV捕获视频,并将其作为输入传递给OpenCL程序。同时,两者之间的转换需要尽可能地高效(如果这不是问题的话,为什么要使用OpenCL呢?)。据我所知,OpenCV内部使用OpenCL(UMat),我可以通过访问UMat::handle来访问GPU缓冲区。然而,到目前为止我的尝试都没有成功。
本文旨在重用UMat缓冲区作为OpenCL kernel的输入,最终以图像形式返回到另一个UMat以便显示。
OpenCV框架只用于生成程序的输入,因此我对使用OpenCV CL wrapper(cv::ocl)不感兴趣,而更喜欢使用普通的OpenCL(cl::...)。这样可以避免在整个软件中包含/链接OpenCV框架。
问题:
如何通过OpenCL访问OpenCV UMat缓冲区?
- 将UMat缓冲区用作OpenCL缓冲区(第一种选择)
- 将UMat缓冲区移动到GPU内的OpenCL缓冲区(第二种选择)
我已经取得的成果:
- OpenCL可以完美地独立运行
- OpenCV可以完美地独立运行
- 将UMat::handle转换为cl::Buffer编译
- 给定的缓冲区似乎无效。
免责声明:请友好对待,因为本文只是针对这个问题的极简示例。
#include <iostream>
#include <vector>
#include <cassert>
#define __CL_ENABLE_EXCEPTIONS // enable exceptions instead of error-codes
#define CL_TARGET_OPENCL_VERSION 120
#include <CL/cl.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/core/ocl.hpp>
using namespace cv;
using namespace std;
int main()
{
// OPENCL STUFF
// Very simplified/basic/stupid/naive OpenCL context creation
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
assert(platforms.size()>0);
std::vector<cl::Device> devices;
platforms[0].getDevices( CL_DEVICE_TYPE_ALL, &devices);
assert(devices.size()>0);
cl_context_properties prop[3] =
{
CL_CONTEXT_PLATFORM,
(cl_context_properties)(platforms[0])(),
0
};
cl::Context context( devices[0], prop, nullptr, nullptr);
std::string kernelStr = R"DELIMITER(
kernel void replaceRB( global uchar3* content)
{
const size_t globalId = get_global_id(0);
private uchar3 byte = content[globalId];
char aux = byte.z;
byte.z = byte.x;
byte.x = aux;
content[globalId] = byte;
}
)DELIMITER";
cl::Program::Sources sources;
sources.push_back(std::make_pair<const char*, size_t>(kernelStr.data(), kernelStr.size()));
cl::Program program(context, sources);
try
{
program.build({devices[0]}, "");
}
catch (...)
{
std::cout << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) << std::endl;
}
std::vector<cl::Kernel> kernels;
program.createKernels(&kernels);
assert(kernels.size()>0);
cl::CommandQueue queue(context, devices[0]);
// OPENCV STUFF
ocl::setUseOpenCL(true);
cv::ocl::attachContext(platforms[0].getInfo<CL_PLATFORM_NAME>(), platforms[0](), context(), devices[0]());
assert(ocl::haveOpenCL());
cout << cv::ocl::Context::getDefault().ndevices() << " GPU devices are detected." << endl;
VideoCapture cap(0); //Camera
//VideoCapture cap("SampleVideo_1280x720_1mb.mp4"); //Video example
assert(cap.isOpened());
UMat frame;
assert(cap.read(frame));
//MIX OF BOTH opencl and opencv
//cl::Buffer buf(context,CL_MEM_READ_WRITE, 256); // This works
cl::Buffer buf(*((cl_mem*)frame.handle(CL_MEM_READ_WRITE)));
int result = kernels[0].setArg(0, buf);
std::cout << result << " == " << CL_INVALID_MEM_OBJECT << std::endl;
queue.enqueueNDRangeKernel(kernels[0], cl::NullRange, cl::NDRange(16), cl::NDRange(4));
queue.flush();
//DISPLAY RESULT?
string window_name = "Test OpenCV and OpenCL";
namedWindow(window_name);
imshow(window_name, frame);
waitKey(5000);
return 0;
}
CL_MEM_READ_WRITE
看起来像是1
,而ACCESS_RW
包含了1<<24
。 - Adrian Maire