全 局 阈 值 和 自 适 应 阈 值 全局阈值和自适应阈值 全局阈值和自适应阈值
1.视频教程:
B站、网易云课堂、腾讯课堂
2.代码地址:
Gitee
Github
3.存储地址:
Google云
百度云:
提取码:
1.全局阈值
1 均值法
2 OTSU
3 三角法
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
Mat src = imread("E:/cats.jpg", IMREAD_UNCHANGED);
if (src.empty()) {
printf("image is empty!!!");
return -1;
}
namedWindow("image", WINDOW_FREERATIO);
imshow("image", src);
Mat gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
imshow("gray", gray);
// 1.均值法
Scalar m = mean(gray);
printf("means:%0.2f\n", m[0]);
threshold(gray, binary, m[0], 255, THRESH_BINARY);
imshow("mean", binary);
// 2.OTSU
double t1 = threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
printf("ostu:%0.2f\n", t1);
imshow("THRESH_OTSU", binary);
// 3.三角法
double t2 = threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_TRIANGLE);
printf("triangle:%0.2f\n", t2);
imshow("THRESH_TRIANGLE", binary);
waitKey(0);
destroyAllWindows();
return 0;
}
2.自适应阈值
全局阈值的局限性,对光照度不均匀的图像容易错误的二值化分割
自适应阈值对图像模糊求差值,然后二值化
- 盒子模糊图像 - D
- 原图 + 加上偏置常量C得 - S
- T = S - D + 255
分割的好坏取决于模糊窗口block大小和常量C
基于高斯_C
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
Mat src = imread("E:/cats.jpg", IMREAD_COLOR);
if (src.empty()) {
printf("image is empty!!!");
return -1;
}
namedWindow("src", WINDOW_AUTOSIZE);
imshow("src", src);
Mat gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
// 自适应阈值分割
adaptiveThreshold(gray, binary, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 25, 10);
imshow("ada-binary", binary);
waitKey(0);
destroyAllWindows();
return 0;
}
基于中值_C
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
Mat src = imread("E:/cats.jpg", IMREAD_COLOR);
if (src.empty()) {
printf("image is empty!!!");
return -1;
}
namedWindow("src", WINDOW_AUTOSIZE);
imshow("src", src);
Mat gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
// 自适应阈值分割
adaptiveThreshold(gray, binary, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 25, 10);
imshow("ada-binary", binary);
waitKey(0);
destroyAllWindows();
return 0;
}