设定一个阈值,将图片数据大于这个阈值和小于这个阈值的部分区分开来,常用的二值化处理就是将大于阈值的设置为255,小于阈值的设置为0。二值化处理目前只支持8位单通道图像。
也可以用于消除噪声(即滤除过小或过大的像素)。
CV_EXPORTS_W double threshold( InputArray src, OutputArray dst,
double thresh, double maxval, int type );
@param src //输入数组(多通道,8位或32位浮点数)。
@param dst //具有与src相同大小和类型以及相同通道数的输出数组。
@param thresh //阈值。
@param maxval //与#THRESH_BINARY和#THRESH_BINARY_INV阈值类型一起使用的最大值。
@param type //阈值类型(请参阅#ThresholdTypes)。
@return //如果使用了Otsu或Triangle方法,则计算出的阈值。
enum ThresholdTypes {
THRESH_BINARY = 0, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{maxval}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f]
THRESH_BINARY_INV = 1, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{maxval}}{otherwise}\f]
THRESH_TRUNC = 2, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{threshold}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f]
THRESH_TOZERO = 3, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{src}(x,y)}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f]
THRESH_TOZERO_INV = 4, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f]
THRESH_MASK = 7,
THRESH_OTSU = 8, //!< flag, use Otsu algorithm to choose the optimal threshold value
THRESH_TRIANGLE = 16 //!< flag, use Triangle algorithm to choose the optimal threshold value
};
int main() {
cv::namedWindow("src",0);
cv::namedWindow("dst", 0);
cv::Mat src(255, 500, CV_8UC1, cv::Scalar(0));
for (int i = 0; i < src.rows; ++i) {
for (int j = 0; j < src.cols; ++j)
{
src.at(i, j) = i;
}
}
cv::imshow("src", src);
cv::imwrite("./src.jpg", src);
cv::Mat dst;
double r = cv::threshold(src, dst, 128, 255, cv::THRESH_BINARY);
cv::imshow("dst", dst);
cv::imwrite("./dst_THRESH_BINARY.jpg", dst);
cv::waitKey(0);
r = cv::threshold(src, dst, 128, 255, cv::THRESH_BINARY_INV);
cv::imshow("dst", dst);
cv::imwrite("./dst_THRESH_BINARY_INV.jpg", dst);
cv::waitKey(0);
r = cv::threshold(src, dst, 128, 255, cv::THRESH_TRUNC);
cv::imshow("dst", dst);
cv::imwrite("./dst_THRESH_TRUNC.jpg", dst);
cv::waitKey(0);
r = cv::threshold(src, dst, 128, 255, cv::THRESH_TOZERO);
cv::imshow("dst", dst);
cv::imwrite("./dst_THRESH_TOZERO.jpg", dst);
cv::waitKey(0);
r = cv::threshold(src, dst, 128, 255, cv::THRESH_TOZERO_INV);
cv::imshow("dst", dst);
cv::imwrite("./dst_THRESH_TOZERO_INV.jpg", dst);
cv::waitKey(0);
r = cv::threshold(src, dst, 128, 255, cv::THRESH_OTSU);
cv::imshow("dst", dst);
cv::imwrite("./dst_THRESH_OTSU.jpg", dst);
cv::waitKey(0);
r = cv::threshold(src, dst, 128, 255, cv::THRESH_TRIANGLE);
cv::imshow("dst", dst);
cv::imwrite("./dst_THRESH_TRIANGLE.jpg", dst);
cv::waitKey(0);
}