【发布时间】:2016-07-20 06:29:28
【问题描述】:
我刚开始使用 CUDA。现在我有一个问题。 我有 N*N 矩阵,窗口比例为 8x8。我想将此矩阵细分为多个子矩阵并找到它的最大值。 例如,如果我有 64*64 矩阵,那么我将有 8 个具有 8*8 比例的小矩阵并找出 8 个最大值。最后我将所有最大值保存到新数组中,但它的顺序总是改变。我想找到解决方案以使它们保持正确的顺序
__global__ void calculate_emax_kernel(float emap[],float emax[], int img_height, int img_width,int windows_size)
{
int x_index = blockIdx.x*blockDim.x+threadIdx.x;
int y_index = blockIdx.y*blockDim.y+threadIdx.y;
int num_row_block = img_height/windows_size;
int num_col_block = img_width/windows_size;
__shared__ float window_elements[256];
__shared__ int counter;
__shared__ int emax_count;
if (threadIdx.x == 0) emax_count = 0;
__syncthreads();
int index;
int emax_idx = 0;
if(y_index >= img_height|| x_index >= img_width) return;
for(int i = 0; i < num_row_block; i++)
{
for(int j = 0; j < num_col_block; j++)
{
counter = 0;
if(y_index >= i*windows_size && y_index < (i+1)*windows_size
&& x_index >= j*windows_size && x_index < (j+1)*windows_size)
{
int idx = y_index*img_height + x_index;
index = atomicAdd(&counter, 1);
window_elements[index] = emap[idx];
__syncthreads();
// reduction
unsigned int k = (windows_size*windows_size)/2;
while(k != 0)
{
if(index < k)
{
window_elements[index] = fmaxf(window_elements[index], window_elements[index+k]);
}
k /= 2;
}
if(index == 0)
{
emax[i*num_row_block+j] = window_elements[index];
}
}
__syncthreads();
}
__syncthreads();
}
__syncthreads();
}
这是我的配置
void construct_emax(float *input,float *output, int img_height, int img_width)
{
int windows_size = 4;
float * d_input, * d_output;
cudaMalloc(&d_input, img_width*img_height*sizeof(float));
cudaMalloc(&d_output, img_width*img_height*sizeof(float));
cudaMemcpy(d_input, input, img_width*img_height*sizeof(float), cudaMemcpyHostToDevice);
dim3 blocksize(16,16);
dim3 gridsize;
gridsize.x=(img_width+blocksize.x-1)/blocksize.x;
gridsize.y=(img_height+blocksize.y-1)/blocksize.y;
calculate_emax_kernel<<<gridsize,blocksize>>>(d_input,d_output,img_height,img_width,windows_size);
}
【问题讨论】:
-
你的意思是“我将有 8x8 的 8*8 小矩阵并找出 8x8 的最大值”?
-
@kangshiyin 对不起,很难解释,这意味着我会将输入矩阵分割成一些小矩阵,这取决于窗口的大小。例如,如果我有 16*16 矩阵和 8*8 窗口大小,那么我将有 4 个小矩阵。并找出每个小矩阵的最大值。
-
你的网格/块配置是什么?
-
@kangshiyin 我把它贴在下面的回答中
-
您可能的窗口大小和范围是多少? 1,2,3,4,5...还是只有2,4,8,16,...?