在 OpenCV 中,你可以使用 cv::threshold 函数来进行二值化和软阈值操作。下面是一个示例代码:
#include <opencv2/opencv.hpp>
int main()
{
// 读取图像
cv::Mat image = cv::imread("image.jpg", cv::IMREAD_GRAYSCALE);
// 进行软阈值处理
cv::Mat thresholded;
double threshold_value = 127; // 阈值设定为 127
double max_value = 255; // 最大像素值设定为 255
int threshold_type = cv::THRESH_BINARY; // 使用二进制阈值化方式
cv::threshold(image, thresholded, threshold_value, max_value, threshold_type);
// 显示原始图像和处理后的图像
cv::imshow("Original Image", image);
cv::imshow("Thresholded Image", thresholded);
cv::waitKey(0);
return 0;
}
这段代码加载一张灰度图像,然后使用 cv::threshold 函数将其进行二值化操作,并显示原始图像和处理后的图像。
请注意,在以上示例中,我们使用了一个固定的阈值(127),根据需要你可以调整阈值来获得不同的效果。
内容由零声教学AI助手提供,问题来源于学员提问




