Advertisement
Tark_Wight

Untitled

Apr 2nd, 2023
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include "lodepng.h"
  4.  
  5. // Get the median value of a vector of values
  6. unsigned char getMedian(std::vector<unsigned char>& values) {
  7. std::sort(values.begin(), values.end());
  8. return values[values.size() / 2];
  9. }
  10.  
  11. // Apply median filter to an image
  12. void applyMedianFilter(std::vector<unsigned char>& image, int width, int height, int channels, int filterSize) {
  13. std::vector<unsigned char> result(image.size());
  14.  
  15. int radius = filterSize / 2;
  16.  
  17. for (int y = 0; y < height; y++) {
  18. for (int x = 0; x < width; x++) {
  19. for (int c = 0; c < channels; c++) {
  20. std::vector<unsigned char> values;
  21.  
  22. for (int i = -radius; i <= radius; i++) {
  23. for (int j = -radius; j <= radius; j++) {
  24. int px = std::min(std::max(x + j, 0), width - 1);
  25. int py = std::min(std::max(y + i, 0), height - 1);
  26.  
  27. values.push_back(image[(py * width + px) * channels + c]);
  28. }
  29. }
  30.  
  31. result[(y * width + x) * channels + c] = getMedian(values);
  32. }
  33. }
  34. }
  35.  
  36. image = result;
  37. }
  38.  
  39. // Apply median filter to an image file
  40. void medianFilter(const char* inputFilename, const char* outputFilename, int filterSize) {
  41. std::vector<unsigned char> image;
  42. unsigned width, height;
  43.  
  44. // Load image from file
  45. unsigned error = lodepng::decode(image, width, height, inputFilename);
  46.  
  47. if (error) {
  48. std::cerr << "Error decoding image: " << lodepng_error_text(error) << std::endl;
  49. return;
  50. }
  51.  
  52. // Apply median filter
  53. applyMedianFilter(image, width, height, 4, filterSize);
  54.  
  55. // Save image to file
  56. error = lodepng::encode(outputFilename, image, width, height);
  57.  
  58. if (error) {
  59. std::cerr << "Error encoding image: " << lodepng_error_text(error) << std::endl;
  60. return;
  61. }
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement