/**自适应阈值二值化*/ Mat ImgProcession::AdaptiveThereshold(Mat src) { Mat dst; cvtColor(src, dst, COLOR_BGR2GRAY); int x1, y1, x2, y2; int count = 0; long long sum = 0; //划分区域的大小S*S int S = src.rows >> 3; /*百分比,用来最后与阈值的比较. * 原文:If the value of the current pixel is t percent less than this average then it is set to black, otherwise it is set to white.*/ int T = 30;//15 int W = dst.cols; int H = dst.rows; long long **Argv; Argv = new long long *[dst.rows]; for (int ii = 0; ii < dst.rows; ii++) { Argv[ii] = new long long[dst.cols]; } for (int i = 0; i < W; i++) { sum = 0; for (int j = 0; j < H; j++) { sum += dst.at<uchar>(j, i); if (i == 0) Argv[j][i] = sum; else Argv[j][i] = Argv[j][i - 1] + sum; } } for (int i = 0; i < W; i++) { for (int j = 0; j < H; j++) { x1 = i - S / 2; x2 = i + S / 2; y1 = j - S / 2; y2 = j + S / 2; if (x1 < 0) x1 = 0; if (x2 >= W) x2 = W - 1; if (y1 < 0) y1 = 0; if (y2 >= H) y2 = H - 1; count = (x2 - x1) * (y2 - y1); sum = Argv[y2][x2] - Argv[y1][x2] - Argv[y2][x1] + Argv[y1][x1]; if ((long long) (dst.at<uchar>(j, i) * count) < (long long) sum * (100 - T) / 100) dst.at<uchar>(j, i) = 0; else dst.at<uchar>(j, i) = 255; } } for (int i = 0; i < dst.rows; ++i) { delete[] Argv[i]; } delete[] Argv; return dst; }
原文:https://www.cnblogs.com/lx17746071609/p/12510712.html