Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void gaussianBlur(unsigned char* image, int width, int height, int channels, float sigma)
- {
- // Calculate Gaussian kernel size based on sigma
- int kernelSize = std::ceil(3 * sigma) * 2 + 1;
- // Allocate memory for the Gaussian kernel
- std::vector<float> kernel(kernelSize * kernelSize);
- // Calculate the Gaussian kernel
- float sum = 0;
- for (int i = 0; i < kernelSize; i++)
- {
- for (int j = 0; j < kernelSize; j++)
- {
- float x = i - kernelSize / 2;
- float y = j - kernelSize / 2;
- float value = std::exp(-(x * x + y * y) / (2 * sigma * sigma));
- kernel[i * kernelSize + j] = value;
- sum += value;
- }
- }
- // Normalize the Gaussian kernel
- for (int i = 0; i < kernelSize * kernelSize; i++)
- {
- kernel[i] /= sum;
- }
- // Allocate memory for the blurred image
- std::vector<unsigned char> blurred(width * height * channels);
- // Apply the Gaussian filter
- for (int y = 0; y < height; y++)
- {
- for (int x = 0; x < width; x++)
- {
- // Compute the weighted average of the pixel's neighbors
- float r = 0, g = 0, b = 0, a = 0;
- for (int i = 0; i < kernelSize; i++)
- {
- for (int j = 0; j < kernelSize; j++)
- {
- int ix = std::max(0, std::min(x + i - kernelSize / 2, width - 1));
- int iy = std::max(0, std::min(y + j - kernelSize / 2, height - 1));
- int index = (iy * width + ix) * channels;
- float weight = kernel[i * kernelSize + j];
- r += weight * image[index + 0];
- g += weight * image[index + 1];
- b += weight * image[index + 2];
- if (channels == 4)
- {
- a += weight * image[index + 3];
- }
- }
- }
- // Store the blurred pixel in the output image
- int index = (y * width + x) * channels;
- blurred[index + 0] = static_cast<unsigned char>(r);
- blurred[index + 1] = static_cast<unsigned char>(g);
- blurred[index + 2] = static_cast<unsigned char>(b);
- if (channels == 4)
- {
- blurred[index + 3] = static_cast<unsigned char>(a);
- }
- }
- }
- // Copy the blurred image back to the original buffer
- std::memcpy(image, blurred.data(), blurred.size() * sizeof(unsigned char));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement