opencv双阈值化

来源:互联网 发布:什么叫网络编程 编辑:程序博客网 时间:2024/06/11 18:21

对于图像中有明显的双分界特征,我们考虑用双阈值方法进行二值化操作。根据双阈值操作方法,对于8位灰度图应用该阈值化方法操作时,预先设定好特

定的阈值量thresh1,thresh2,并且thresh<thresh2,阈值化操作只需要将大于thresh1且小于thresh2的灰度值设定为maxVal,其余情况设定为0.双阈值化操作中两个阈值可根据实际场景需求进行设置,需要说明的是,maxVal可以是某一个固定的阈值(通常情况下8为无符号图像设置为最大灰度值255)。

代码如下:
#include "opencv2/highgui/highgui.hpp"#include "opencv2/imgproc/imgproc.hpp"#include "opencv2/opencv.hpp"#include "opencv2/core/core.hpp"#include <stdio.h>#include <string>using namespace std;using namespace cv;int main(){cv::Mat srcImage = cv::imread("C:\\Users\\LP\\Desktop\\C++\\ConsoleApplication4\\ConsoleApplication4\\RGBFlower4.jpg");if (srcImage.empty()){return -1;} cv::imshow("原图像", srcImage);//灰度转换cv::Mat srcGray;cv::cvtColor(srcImage, srcGray, CV_RGB2GRAY);cv::imshow("srcGray", srcGray);//初始化阈值参数int low_threshold = 150;int high_threshold = 210;int maxValue = 255;cv::Mat dstTempImage1, dstTempImage2, dstTempImage;cv::threshold(srcGray, dstTempImage1, low_threshold, maxValue, cv::THRESH_BINARY);cv::threshold(srcGray, dstTempImage2, high_threshold, maxValue, cv::THRESH_BINARY_INV);//矩阵与运算得到二值化结果cv::bitwise_and(dstTempImage1, dstTempImage2, dstTempImage);cv::imshow("dstTempImage", dstTempImage);cv::waitKey(0);return 0;}


原创粉丝点击