OpenCV是一个开源的计算机视觉库,它提供了大量的图像处理功能。在C++中使用OpenCV进行图像阈值处理时,可以利用其内置的函数来实现多种阈值处理技巧。
#include <opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
int main() {
Mat src = imread("input.jpg", IMREAD_GRAYSCALE);
Mat dst;
double threshold_value = 128;
double max_value = 255;
int threshold_type = THRESH_BINARY;
threshold(src, dst, threshold_value, max_value, threshold_type);
imwrite("output.jpg", dst);
return 0;
}
#include <opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
int main() {
Mat src = imread("input.jpg", IMREAD_GRAYSCALE);
Mat dst;
int block_size = 25;
double constant = 5;
int threshold_type = THRESH_BINARY;
adaptiveThreshold(src, dst, 255, ADAPTIVE_THRESH_MEAN_C, threshold_type, block_size, constant);
imwrite("output.jpg", dst);
return 0;
}
#include <opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
int main() {
Mat src = imread("input.jpg", IMREAD_GRAYSCALE);
Mat dst;
double threshold_value = 0;
double max_value = 255;
int threshold_type = THRESH_BINARY | THRESH_OTSU;
threshold(src, dst, threshold_value, max_value, threshold_type);
imwrite("output.jpg", dst);
return 0;
}
#include <opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
double triangleThreshold(Mat& src) {
int hist[256] = {0};
for (int i = 0; i < src.rows; i++) {
for (int j = 0; j < src.cols; j++) {
hist[src.at<uchar>(i, j)]++;
}
}
int total = src.rows * src.cols;
int accumulator[256] = {0};
for (int i = 0; i < 256; i++) {
accumulator[i] = hist[i] + (i == 0 ? 0 : accumulator[i - 1]);
}
double max_dist = 0;
int threshold = 0;
for (int i = 0; i < 256; i++) {
if (accumulator[i] == 0 || accumulator[i] == total) continue;
double dist = (double)(total - accumulator[i]) * i - (double)accumulator[i] * (255 - i);
if (dist > max_dist) {
max_dist = dist;
threshold = i;
}
}
return threshold;
}
int main() {
Mat src = imread("input.jpg", IMREAD_GRAYSCALE);
Mat dst;
double threshold_value = triangleThreshold(src);
double max_value = 255;
int threshold_type = THRESH_BINARY;
threshold(src, dst, threshold_value, max_value, threshold_type);
imwrite("output.jpg", dst);
return 0;
}
这些示例展示了如何在C++中使用OpenCV进行不同类型的图像阈值处理。你可以根据需要选择合适的阈值处理技巧。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。