1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| void adaptive_mean_filter(Mat& srcImage, Mat& dstImage, int size) { dstImage = srcImage.clone(); int height = srcImage.rows; int width = srcImage.cols; int k = size / 2;
double variance = 900; for (int i = k; i < height - k; i++) { for (int j = k; j < width - k; j++) { for (int c = 0; c < srcImage.channels(); c++) { if (srcImage.channels() == 1) { double gxy = srcImage.at<uchar>(i, j); double xy_mean = 0; for (int m = -k; m <= k; m++) { for (int n = -k; n <= k; n++) { xy_mean += srcImage.at<uchar>(i + m, j + n); } } xy_mean /= (size * size); double xy_variance = 0; for (int m = -k; m <= k; m++) { for (int n = -k; n <= k; n++) { xy_variance += pow(srcImage.at<uchar>(i + m, j + n) - xy_mean, 2); } } xy_variance /= (size * size); if (variance / xy_variance > 1.0) { dstImage.at<uchar>(i, j) = saturate_cast<uchar>(xy_mean); } else { dstImage.at<uchar>(i, j) = saturate_cast<uchar>(gxy - (variance / xy_variance) * (gxy - xy_mean)); } } else if (srcImage.channels() == 3) { double gxy = srcImage.at<Vec3b>(i, j)[c]; double xy_mean = 0; for (int m = -k; m <= k; m++) { for (int n = -k; n <= k; n++) { xy_mean += srcImage.at<Vec3b>(i + m, j + n)[c]; } } xy_mean /= (size * size); double xy_variance = 0; for (int m = -k; m <= k; m++) { for (int n = -k; n <= k; n++) { xy_variance += pow(srcImage.at<Vec3b>(i + m, j + n)[c] - xy_mean, 2); } } xy_variance /= (size * size); if (variance / xy_variance > 1.0) { dstImage.at<Vec3b>(i, j)[c] = saturate_cast<uchar>(xy_mean); } else { dstImage.at<Vec3b>(i, j)[c] = saturate_cast<uchar>(gxy - (variance / xy_variance) * (gxy - xy_mean)); } } } } } }
|