Advertisement
Tark_Wight

Untitled

Apr 2nd, 2023
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. void gaussianFilter(const char* input_filename, const char* output_filename, int radius)
  2. {
  3. std::vector<unsigned char> input_image;
  4. unsigned int width, height;
  5.  
  6. // загрузка входного изображения
  7. unsigned error = lodepng::decode(input_image, width, height, input_filename);
  8. if (error)
  9. std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl;
  10.  
  11. // создание копии входного изображения
  12. std::vector<unsigned char> output_image(input_image.size());
  13.  
  14. // настройка параметров фильтра
  15. float sigma = radius / 3.0f;
  16. int size = radius * 2 + 1;
  17. std::vector<float> kernel(size * size);
  18. float sum = 0.0f;
  19. for (int y = -radius; y <= radius; y++)
  20. {
  21. for (int x = -radius; x <= radius; x++)
  22. {
  23. float value = std::exp(-(x * x + y * y) / (2.0f * sigma * sigma));
  24. kernel[(y + radius) * size + (x + radius)] = value;
  25. sum += value;
  26. }
  27. }
  28. for (int i = 0; i < size * size; i++)
  29. {
  30. kernel[i] /= sum;
  31. }
  32.  
  33. // фильтрация изображения
  34. for (unsigned int y = radius; y < height - radius; y++)
  35. {
  36. for (unsigned int x = radius; x < width - radius; x++)
  37. {
  38. for (unsigned int c = 0; c < 4; c++)
  39. {
  40. float accumulator = 0.0f;
  41. for (int ky = -radius; ky <= radius; ky++)
  42. {
  43. for (int kx = -radius; kx <= radius; kx++)
  44. {
  45. float value = kernel[(ky + radius) * size + (kx + radius)];
  46. unsigned int index = ((y + ky) * width + (x + kx)) * 4 + c;
  47. accumulator += input_image[index] * value;
  48. }
  49. }
  50. unsigned int index = (y * width + x) * 4 + c;
  51. output_image[index] = (unsigned char)accumulator;
  52. }
  53. }
  54. }
  55.  
  56. // сохранение выходного изображения
  57. error = lodepng::encode(output_filename, output_image, width, height);
  58. if (error)
  59. std::cout << "encoder error " << error << ": " << lodepng_error_text(error) << std::endl;
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement