To convert a color image represented in the RGBA format to a greyscale image using the NTSC formula, we implement a CUDA kernel that processes each pixel in parallel. The NTSC formula is:
I = 0.299f * R + 0.587f * G + 0.114f * B
We will use 2D thread blocks and 2D grid to map each thread to a unique pixel, ensuring efficient and scalable processing across the entire image.
✅ Kernel Implementation
#include "utils.h"
__global__
void rgba_to_greyscale(const uchar4* const rgbaImage,
unsigned char* const greyImage,
int numRows, int numCols)
{
// Compute 2D thread position
int x = threadIdx.x + blockIdx.x * blockDim.x;
int y = threadIdx.y + blockIdx.y * blockDim.y;
// Check if this thread is within the image bounds
if (x >= numCols || y >= numRows) return;
// Compute 1D index
int index = y * numCols + x;
// Extract RGB components
uchar4 pixel = rgbaImage[index];
float R = static_cast<float>(pixel.x);
float G = static_cast<float>(pixel.y);
float B = static_cast<float>(pixel.z);
// Apply NTSC formula
float intensity = 0.299f * R + 0.587f * G + 0.114f * B;
// Convert to unsigned char and store
greyImage[index] = static_cast<unsigned char>(intensity);
}
✅ Host Function: Setting Block and Grid Sizes
We use 16x16 thread blocks, a common and efficient block size for 2D grids in CUDA. The grid size is computed to cover the entire image, even if the dimensions are not exact multiples of the block size.
void your_rgba_to_greyscale(const uchar4 * const h_rgbaImage, uchar4 * const d_rgbaImage,
unsigned char* const d_greyImage, size_t numRows, size_t numCols)
{
const int BLOCK_SIZE = 16;
dim3 blockSize(BLOCK_SIZE, BLOCK_SIZE);
dim3 gridSize(
(numCols + BLOCK_SIZE - 1) / BLOCK_SIZE,
(numRows + BLOCK_SIZE - 1) / BLOCK_SIZE
);
rgba_to_greyscale<<<gridSize, blockSize>>>(d_rgbaImage, d_greyImage, static_cast<int>(numRows), static_cast<int>(numCols));
cudaDeviceSynchronize();
checkCudaErrors(cudaGetLastError());
}
📌 Key Considerations
- Thread Mapping: Each thread is mapped to a unique pixel using
threadIdx and blockIdx. This ensures that all pixels are processed in parallel.
- Bounds Checking: Threads that go out of bounds (due to non-divisible dimensions) return early to avoid invalid memory access.