Advertisement
Tark_Wight

Untitled

Apr 2nd, 2023
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. void gaussianBlur(unsigned char* image, int width, int height, int channels, float sigma)
  2. {
  3. // Calculate Gaussian kernel size based on sigma
  4. int kernelSize = std::ceil(3 * sigma) * 2 + 1;
  5.  
  6. // Allocate memory for the Gaussian kernel
  7. std::vector<float> kernel(kernelSize * kernelSize);
  8.  
  9. // Calculate the Gaussian kernel
  10. float sum = 0;
  11. for (int i = 0; i < kernelSize; i++)
  12. {
  13. for (int j = 0; j < kernelSize; j++)
  14. {
  15. float x = i - kernelSize / 2;
  16. float y = j - kernelSize / 2;
  17. float value = std::exp(-(x * x + y * y) / (2 * sigma * sigma));
  18. kernel[i * kernelSize + j] = value;
  19. sum += value;
  20. }
  21. }
  22.  
  23. // Normalize the Gaussian kernel
  24. for (int i = 0; i < kernelSize * kernelSize; i++)
  25. {
  26. kernel[i] /= sum;
  27. }
  28.  
  29. // Allocate memory for the blurred image
  30. std::vector<unsigned char> blurred(width * height * channels);
  31.  
  32. // Apply the Gaussian filter
  33. for (int y = 0; y < height; y++)
  34. {
  35. for (int x = 0; x < width; x++)
  36. {
  37. // Compute the weighted average of the pixel's neighbors
  38. float r = 0, g = 0, b = 0, a = 0;
  39. for (int i = 0; i < kernelSize; i++)
  40. {
  41. for (int j = 0; j < kernelSize; j++)
  42. {
  43. int ix = std::max(0, std::min(x + i - kernelSize / 2, width - 1));
  44. int iy = std::max(0, std::min(y + j - kernelSize / 2, height - 1));
  45. int index = (iy * width + ix) * channels;
  46. float weight = kernel[i * kernelSize + j];
  47. r += weight * image[index + 0];
  48. g += weight * image[index + 1];
  49. b += weight * image[index + 2];
  50. if (channels == 4)
  51. {
  52. a += weight * image[index + 3];
  53. }
  54. }
  55. }
  56.  
  57. // Store the blurred pixel in the output image
  58. int index = (y * width + x) * channels;
  59. blurred[index + 0] = static_cast<unsigned char>(r);
  60. blurred[index + 1] = static_cast<unsigned char>(g);
  61. blurred[index + 2] = static_cast<unsigned char>(b);
  62. if (channels == 4)
  63. {
  64. blurred[index + 3] = static_cast<unsigned char>(a);
  65. }
  66. }
  67. }
  68.  
  69. // Copy the blurred image back to the original buffer
  70. std::memcpy(image, blurred.data(), blurred.size() * sizeof(unsigned char));
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement