Advertisement
dan-masek

Average Filter by MicMac on SO - basic refactor, cleanup, and tracing with mistakes left in.

Feb 22nd, 2022
1,398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include <opencv2/opencv.hpp>
  2.  
  3. /*
  4. Note: I split off this piece of code into a separate function in order
  5.       to simplify the reasoning about the code.
  6.       This is probably not ideal for performance, but it's too early to worry about that now.
  7. */
  8. uint8_t filter_mean_at(cv::Mat const& image, int32_t x, int32_t y, int32_t framing)
  9. {
  10.     std::cout << "Applying filter at (" << x << "," << y << ")\n";
  11.     int32_t sum{ 0 };
  12.     for (int32_t dx = 0; dx < framing; ++dx) {
  13.         for (int32_t dy = 0; dy < framing; ++dy) {
  14.             int32_t const xx = x + dx;
  15.             int32_t const yy = y + dy;
  16.             std::cout << " * Processing pixel at  (" << xx << "," << yy << ")\n";
  17.             sum += image.at<uint8_t>(xx, yy);
  18.         }
  19.     }
  20.  
  21.     int32_t mean = sum; // NB: Mistake intentionally left here.
  22.     std::cout << " Result = " << mean << " (as uint8_t = "
  23.         << static_cast<int32_t>(static_cast<uint8_t>(mean)) << ")\n";
  24.     return mean;
  25. }
  26.  
  27. cv::Mat filter_mean(cv::Mat image, int window_size)
  28. {
  29.     cv::Mat result = image.clone();
  30.     int32_t const framing = window_size / 2;
  31.     for (int32_t x = 0; x < image.rows; ++x) {
  32.         for (int32_t y = 0; y < image.cols; ++y) {
  33.             result.at<uint8_t>(x, y) = filter_mean_at(image, x, y, framing);
  34.         }
  35.     }
  36.     return result;
  37. }
  38.  
  39. int main()
  40. {
  41.     // Just some small simple 4x4 grayscale image to test this on...
  42.     cv::Mat img = (cv::Mat1b(4, 4)
  43.         << 0, 16, 32, 48
  44.         , 64, 64, 64, 64
  45.         , 128, 128, 128, 192
  46.         , 255, 255, 255, 255
  47.         );
  48.  
  49.     cv::Mat filtered_image = filter_mean(img, 3);
  50.    
  51.     std::cout << "Result:\n" << filtered_image << '\n';
  52.  
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement