我想通过C ++使用自动阈值算法进行图像分割,但我的代码并没有按照我的预期处理图像。我使用用户定义的类来加载和保存BMP,它对我来说很好。它对某些图像做了一些好事,但也没有使用某些图像。您建议我开发代码的是什么?这是我的代码:
int Segmentation::getThreshold() {
int distance[256] = { 0 };
int t1 = 10;
int t2 = 200;
int t1O = 0;
int t2O = 0;
int threshold = 0;
int meanT1 = 1000;
int meanT2 = 2000;
double sd1 = 1;
double sd2 = 1;
while (t1 != t1O || t2 != t2O) {
int weighT1 = 0;
int weighT2 = 0;
meanT1 = 0;
meanT2 = 0;
for (int i = 0; i < 256; i++) {
if (abs(histogram[t1] - histogram[i]) < abs(histogram[t2] - histogram[i]))
distance[i] = 1;
if (abs(histogram[t1] - histogram[i]) >= abs(histogram[t2] - histogram[i]))
distance[i] = 2;
}
for (int j = 0; j < 256; j++) {
if (distance[j] == 1) {
meanT1 += histogram[j] * j;
weighT1 += histogram[j];
}
if (distance[j] == 2) {
meanT2 += histogram[j] * j;
weighT2 += histogram[j];
}
}
meanT1 = meanT1 / weighT1;
meanT2 = meanT2 / weighT2;
if (histogram[meanT1] != histogram[t1O] || histogram[meanT2] != histogram[t2O]) {
t1O = t1;
t1 = meanT1;
t2O = t2;
t2 = meanT2;
}
else {
t1 = meanT1;
t2 = meanT2;
break;
}
}
threshold = (t1 + t2) / 2;
cout << "Threshold is: " << threshold << endl;
return threshold;
void Segmentation::getSegmentation() {
int threshold;
threshold = getThreshold();
for (int i = 0; i<width; i++)
for (int j = 0; j < height; j++) {
if (histogram[img[width*i + j]] > histogram[threshold])
img[width*i + j] = 0;
else
img[width*i + j] = 255;
}
}
答案 0 :(得分:1)
替换
histogram[img[width*i + j]] > histogram[threshold]
通过
img[width*i + j] > threshold