OpenCV--041:Triangle二值寻找算法
程序员文章站
2024-02-20 23:34:22
...
三角形的二值化法:
不用自己指定thresh值,系统会进行计算并且作为返回值返回。
THRESH_OTSU最适用于双波峰。
THRESH_TRIANGLE最适用于单个波峰,最开始用于医学分割细胞等。
- 原理:
1.图像转灰度
2.计算图像灰度直方图
3.寻找直方图中两侧边界
4.寻找直方图最大值
5.检测是否最大波峰在亮的一侧,否则翻转
6.计算阈值得到阈值T,如果翻转则255-T
void Threshold(Mat& src, Mat& dst, double thresh) {
int bt;
//遍历灰度图像,统计灰度级的个数
for (int i = 0; i < src.rows; i++)
{
uchar* p = src.ptr<uchar>(i);
uchar* p1 = dst.ptr<uchar>(i);
for (int j = 0; j < src.cols; j++)
{
bt = p[j];
cout << "bt=" << bt << " ";
if (bt > thresh) {
bt = 255;
}
else {
bt = 0;
}
p1[j] = bt;
}
}
imshow("src", src);
imshow("dst", dst);
}
void Triangle(Mat& src, Mat& dst) {
int i = 0, j = 0;
int gray;
int temp = 0;
bool isflipped = false;
//求直方图
//void calcHist( const Mat* images, int nimages,
// const int* channels, InputArray mask,
// OutputArray hist, int dims, const int* histSize,
// const float** ranges, bool uniform = true, bool accumulate = false );
//
/*int nimages = 1;
int channels[1] = { 0 };
Mat calchist;
int dims = 1;
int histSize[1] = { 256 };
//每一维数值的取值范围ranges
float hranges[2] = { 0,255 };
//每一维数值的取值范围
const float* ranges[1] = { hranges };
//灰度级别
calcHist(&src, nimages, channels, Mat(), calchist, dims, histSize, ranges);
*/
int calchist[256] = { 0 };
//遍历灰度图像,统计灰度级的个数
for (i = 0; i < src.rows; i++)
{
uchar* p = src.ptr<uchar>(i);
for (j = 0; j < src.cols; j++)
{
int value = p[j];
calchist[value]++;
}
}
//寻找直方图中两侧边界
int left_bound = 0;
int right_bound = 0;
int max = 0;
int max_index = 0;
//左侧为零的位置
for (i = 0; i < 256; i++) {
if (calchist[i] > 0) {
left_bound = i;
break;
}
}
//直方图为零的位置
if (left_bound > 0) {
left_bound--;
}
//直方图右侧为零的位置
for (i = 255; i > 0; i--) {
if (calchist[i] > 0) {
right_bound = i;
break;
}
}
//直方图为零的地方
if (right_bound > 0) {
right_bound++;
}
//寻找直方图最大值
for (i = 0; i < 256; i++) {
if (calchist[i] > max) {
max = calchist[i];
max_index = i;
}
}
//判断最大值是否在最左侧,如果是则不用翻转
//因为三角形二值化只能适用于最大值在最右侧
if (max_index - left_bound < right_bound - max_index) {
isflipped = true;
i = 0;
j = 255;
while (i < j) {
//左右交换
temp = calchist[i];
calchist[i] = calchist[j];
calchist[j] = temp;
i++;
j--;
}
left_bound = 255 - right_bound;
max_index = 255 - max_index;
}
//求阈值
double thresh = left_bound;
double a, b, dist = 0, tempdist;
a = max;
b = left_bound - max_index;
for (int i = left_bound+1; i <= max_index; i++)
{
//计算距离--不需要真正计算
tempdist = a * i + b * calchist[i];
if (tempdist > dist) {
dist = tempdist;
thresh = i;
}
}
thresh--;
// 对已经得到的阈值T,如果前面已经翻转了,则阈值要用255-T
if (isflipped)
{
thresh = 255 - thresh;
}
//二值化
Threshold(image, dst, thresh);
}
int main() {
Mat src = imread("D:/test/src.jpg", 0);
Mat dst;
//threshold(src, dst, 0, 255, THRESH_BINARY | THRESH_OTSU);
Triangle(src, dst);
waitKey(0);
return 0;
}
OpenCV中的实现
学习: