本系列代码托管于:https://github.com/chintsan-code/opencv4-tutorials
本篇使用的项目为:bin_image
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, const char** argv) {
Mat src = imread("../sample/master.jpg");
if (src.empty()) {
cout << "could not load image..." << endl;
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", src);
Mat gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
imshow("input", gray);
threshold(gray, binary, 200, 255, THRESH_BINARY);
imshow("threshold binary", binary);
threshold(gray, binary, 127, 255, THRESH_BINARY_INV);
imshow("threshold binary invert", binary);
threshold(gray, binary, 127, 255, THRESH_TRUNC);
imshow("threshold TRUNC", binary);
threshold(gray, binary, 127, 255, THRESH_TOZERO);
imshow("threshold to zero", binary);
threshold(gray, binary, 127, 255, THRESH_TOZERO_INV);
imshow("threshold to zero invert", binary);
waitKey(0);
destroyAllWindows();
return 0;
}
灰度与二值图像
- 灰度图像:单通道。取值范围0-255
- 二值图像:单通道。取值0(黑色)或255(白色)
threshold:使用固定阈值对图像进行分割
double threshold( InputArray src, OutputArray dst, double thresh, double maxval, int type );
- src:输入图像。8-bit或32F,多通道
- dst:输出图像,与src具有相同的尺寸、类型、通道数
- thresh:固定阈值。当type含有THRESH_OTSU或THRESH_TRIANGLE时,可以设为0,即不需要手动设置,而是使用全局自动阈值
- maxval:当type为THRESH_BINARY或THRESH_BINARY_INV时使用的最大值
- type:分割类型
- THRESH_BINARY
- THRESH_BINARY_INV
- THRESH_TRUNC
- THRESH_TOZERO
- THRESH_TOZERO_INV
- THRESH_OTSU
- THRESH_TRIANGLE
- @return:当type含有THRESH_OTSU或THRESH_TRIANGLE时,返回计算出的thresh
关于type:
- THRESH_BINARY
- THRESH_BINARY_INV
- THRESH_TRUNC
- THRESH_TOZERO
- THRESH_TOZERO_INV
- THRESH_OTSU:最大类间方差法
- THRESH_TRIANGLE:三角法
评论 (0)