Advertisement
Tark_Wight

Untitled

Apr 2nd, 2023
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <algorithm>
  4. #include <vector>
  5.  
  6. using namespace std;
  7.  
  8. void medianFilter(const char* in_filename, const char* out_filename, unsigned kernel_size) {
  9. // Загружаем изображение
  10. unsigned error;
  11. unsigned char* image;
  12. unsigned width, height;
  13.  
  14. error = lodepng_decode24_file(&image, &width, &height, in_filename);
  15. if (error) {
  16. cerr << "Failed to load image: " << lodepng_error_text(error) << endl;
  17. return;
  18. }
  19.  
  20. // Фильтр медианного значения
  21. unsigned kernel_radius = kernel_size / 2;
  22. vector<unsigned char> pixels(kernel_size * kernel_size * 3);
  23. for (unsigned y = 0; y < height; y++) {
  24. for (unsigned x = 0; x < width; x++) {
  25. for (unsigned c = 0; c < 3; c++) {
  26. unsigned index = (y * width + x) * 3 + c;
  27.  
  28. // Заполняем ядро пикселей
  29. for (unsigned ky = 0; ky < kernel_size; ky++) {
  30. for (unsigned kx = 0; kx < kernel_size; kx++) {
  31. unsigned px = min(max(int(x) + kx - kernel_radius, 0), int(width) - 1);
  32. unsigned py = min(max(int(y) + ky - kernel_radius, 0), int(height) - 1);
  33. unsigned kindex = (ky * kernel_size + kx) * 3 + c;
  34. pixels[kindex] = image[(py * width + px) * 3 + c];
  35. }
  36. }
  37.  
  38. // Сортируем пиксели в ядре и берем медианное значение
  39. sort(pixels.begin(), pixels.end());
  40. unsigned median_index = pixels.size() / 2;
  41. image[index] = pixels[median_index];
  42. }
  43. }
  44. }
  45.  
  46. // Сохраняем изображение
  47. error = lodepng_encode24_file(out_filename, image, width, height);
  48. if (error) {
  49. cerr << "Failed to save image: " << lodepng_error_text(error) << endl;
  50. return;
  51. }
  52.  
  53. // Освобождаем память
  54. free(image);
  55. }
  56.  
  57. int main() {
  58. // Задаем имена входного и выходного файлов и размер ядра фильтра
  59. const char* in_filename = "input.png";
  60. const char* out_filename = "output.png";
  61. unsigned kernel_size = 3;
  62.  
  63. // Фильтр медианного значения
  64. medianFilter(in_filename, out_filename, kernel_size);
  65.  
  66. return 0;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement