以下是使用 OpenCV 和熵算法进行图像阈值分割的 C++ 代码示例:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
double calculateEntropy(Mat& image, int threshold)
{
int hist[256] = {0};
int total = 0;
for (int i = 0; i < image.rows; i++)
{
uchar* row = image.ptr<uchar>(i);
for (int j = 0; j < image.cols; j++)
{
hist[row[j]]++;
total++;
}
}
double entropy = 0.0;
for (int i = 0; i < 256; i++)
{
if (hist[i] > 0)
{
double p = (double)hist[i] / total;
entropy -= p * log2(p);
}
}
return entropy;
}
int main(int argc, char** argv)
{
// 读取输入图像
Mat src = imread("input.jpg", IMREAD_GRAYSCALE);
// 判断图像是否加载成功
if (src.empty())
{
cout << "Error: Failed to load image." << endl;
return -1;
}
// 计算阈值
double maxEntropy = 0;
int bestThreshold = 0;
for (int i = 0; i < 256; i++)
{
Mat binary;
threshold(src, binary, i, 255, THRESH_BINARY);
double entropy = calculateEntropy(binary, i);
if (entropy > maxEntropy)
{
maxEntropy = entropy;
bestThreshold = i;
}
}
// 应用阈值
Mat dst;
threshold(src, dst, bestThreshold, 255, THRESH_BINARY);
// 显示结果图像
imshow("Input Image", src);
imshow("Output Image", dst);
// 等待用户按下任意按键退出程序
waitKey(0);
return 0;
}
在上述代码中,我们首先使用 `imread` 函数读取输入图像,并判断是否成功加载。然后,我们使用自定义的 `calculateEntropy` 函数计算给定阈值下的熵值。接下来,我们使用 `threshold` 函数在图像上应用不同的阈值,并计算每个阈值下的熵值。最后,我们选择具有最大熵值的阈值,并将其用于二值化图像,生成输出图像。最后,我们使用 `imshow` 函数将输入和输出图像显示出来。最后,我们使用 `waitKey` 函数等待用户按下任意按键,以便退出程序。