#define CL_HPP_TARGET_OPENCL_VERSION 120 #define CL_HPP_MINIMUM_OPENCL_VERSION 120 #if defined(__APPLE__) #include #else #include #endif #include #include #include #include int main(void) { // Set up platform, device and context std::vector platforms; std::vector devices; cl::Device default_device; cl::Platform::get(&platforms); if (platforms.size() == 0) { std::cout << "No OpenCL platform found, check installation!" << std::endl; exit(-1); } platforms[0].getDevices(CL_DEVICE_TYPE_ALL, &devices); if (devices.size() == 0) { std::cout << "No devices found in platform, check installation!" << std::endl; exit(-1); } default_device = devices[0]; cl::Context context(default_device); std::ifstream program_file("read_write_image.cl"); std::string program_string(std::istreambuf_iterator(program_file), (std::istreambuf_iterator())); cl::Program::Sources source{ program_string }; cl::Program dummy_program(context, source); if (dummy_program.build() != CL_SUCCESS) { std::cout << "Error building: " << dummy_program.getBuildInfo(default_device) << std::endl; exit(-1); } cl::Kernel kernel(dummy_program, "read_write_image"); cl::CommandQueue queue(context, default_device); // Set up dummy grayscale image std::vector A(256, 0.0); for (int i = 0; i < 256; i++) { A[i] = 255.0f - i; std::cout << A[i] << " "; } std::cout << std::endl; // the below section is not required // Blow up to float4 array /* std::vector A_img(256, 0.0); //A_img(1024, 0.0) for (int i = 0; i < 256; i++) { //A_img[4 * i] = A[i]; //A_img[(4 * i) + 3] = 1; } */ std::vector B_img(256, 0.0); //B_img(1024, 0.0) cl::ImageFormat grayscale(CL_R, CL_FLOAT); cl::Image2D Input_Image(context, CL_MEM_READ_ONLY, grayscale, 16, 16); cl::Image2D Output_Image(context, CL_MEM_WRITE_ONLY, grayscale, 16, 16); std::array origin = { 0, 0, 0 }; std::array region = { 16, 16, 1 }; queue.enqueueWriteImage(Input_Image, CL_TRUE, origin, region, 0, 0, &A[0]); kernel.setArg(0, Input_Image); kernel.setArg(1, Output_Image); queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(16, 16), cl::NullRange, NULL); queue.enqueueReadImage(Output_Image, CL_TRUE, origin, region, 0, 0, &B_img[0]); bool matched = true; for (int i = 0; i < 256; i++) { if (A[i] != B_img[i]) { std::cout << "i = " << i << " A: " << A[i] << " B_img: " << B_img[i] << std::endl; matched = false; break; } } if (matched) { std::cout << "Image matched"; } else { std::cout << "Image mismatch"; } std::cout << std::endl; return EXIT_SUCCESS; }