▶ 使用 OpenCV 从文件读取彩色的 png 图像,旋转一定角度以后写回文件
● 代码,核函数
1 // rotate.cl 2 //__constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_FILTER_NEAREST | CLK_ADDRESS_CLAMP;// 设备采样器,可以启用,并删除函数 imageRotate 中的采样器参数 3 4 __kernel void imageRotate(__read_only image2d_t inputImage, __write_only image2d_t outputImage, float angle, sampler_t sampler) 5 { 6 const int width = get_image_width(inputImage), height = get_image_height(inputImage); 7 const int halfWidth = width / 2, halfHeight = height / 2; 8 const int x = get_global_id(0), y = get_global_id(1); 9 const int xt = x - halfWidth, yt = y - halfHeight; 10 const float sinFactor = sin(angle), cosFactor = cos(angle); 11 12 float2 readCoord = (float2)(halfWidth + cosFactor * xt - sinFactor * yt, readCoord.y = halfHeight + sinFactor * xt + cosFactor * yt); 13 float4 value = read_imagef(inputImage, sampler, readCoord); 14 write_imagef(outputImage, (int2)(x, y), value); 15 return; 16 }
● 代码,分三通道分别旋转
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <cl.h> 4 #include <opencv.hpp> 5 #include <opencv2corecvstd.hpp> // namespace cv 的定义 6 7 #pragma warning(disable : 4996) // 解封OPenCL1.2 8 9 using namespace cv; 10 11 const char *sourceProgram = "D:/Code/OpenCL/rotate.cl";// 核函数文件 12 const char *imagePath = "D:\input.png"; 13 const float angle = 3.14f / 4; 14 15 int readSource(const char* kernelPath, char **output)// 读取文本文件,存储为 char * 16 { 17 FILE *fp; 18 int size; 19 fopen_s(&fp, kernelPath, "rb"); 20 if (!fp) 21 { 22 printf("Open kernel file failed "); 23 exit(-1); 24 } 25 if (fseek(fp, 0, SEEK_END) != 0) 26 { 27 printf("Seek end of file faildd "); 28 exit(-1); 29 } 30 if ((size = ftell(fp)) < 0) 31 { 32 printf("Get file position failed "); 33 exit(-1); 34 } 35 rewind(fp); 36 if ((*output = (char *)malloc(size + 1)) == NULL) 37 { 38 printf("Allocate space failed "); 39 exit(-1); 40 } 41 fread((void*)*output, 1, size, fp); 42 fclose(fp); 43 (*output)[size] = '