图像处理——(源)自适应阈值分割(adaptiveThreshold)函数编程实现


1
#include <iostream> 2 #include <opencv2/core.hpp> 3 #include <opencv2/highgui.hpp> 4 #include <opencv2/imgproc.hpp> 5 6 enum adaptiveMethod{meanFilter,gaaussianFilter,medianFilter}; 7 8 void AdaptiveThreshold(cv::Mat& src, cv::Mat& dst, double Maxval, int Subsize, double c, adaptiveMethod method = meanFilter){ 9 10 if (src.channels() > 1) 11 cv::cvtColor(src, src, CV_RGB2GRAY); 12 13 cv::Mat smooth; 14 cv::blur(src, smooth, cv::Size(Subsize, Subsize)); //均值滤波 15 smooth = smooth - c; 16 //阈值处理 17 src.copyTo(dst); 18 for (int r = 0; r < src.rows;++r){ 19 const uchar* srcptr = src.ptr<uchar>(r); 20 const uchar* smoothptr = smooth.ptr<uchar>(r); 21 uchar* dstptr = dst.ptr<uchar>(r); 22 for (int c = 0; c < src.cols; ++c){ 23 if (srcptr[c]>smoothptr[c]){ 24 dstptr[c] = Maxval; 25 } 26 else 27 dstptr[c] = 0; 28 } 29 } 30 31 } 32 33 int main(){ 34 cv::Mat src = cv::imread("E://lena.jpg"); 35 if (src.empty()){ 36 return -1; 37 } 38 if (src.channels() > 1) 39 cv::cvtColor(src, src, CV_RGB2GRAY); 40 41 cv::Mat dst, dst2; 42 double t2 = (double)cv::getTickCount(); 43 AdaptiveThreshold(src, dst, 255, 21, 10, meanFilter); // 44 t2 = (double)cv::getTickCount() - t2; 45 double time2 = (t2 *1000.) / ((double)cv::getTickFrequency()); 46 std::cout << "my_process=" << time2 << " ms. " << std::endl << std::endl; 47 48 49 cv::adaptiveThreshold(src, dst2, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 21, 10); 50 51 52 cv::namedWindow("src", CV_WINDOW_NORMAL); 53 cv::imshow("src", src); 54 cv::namedWindow("dst", CV_WINDOW_NORMAL); 55 cv::imshow("dst", dst); 56 cv::namedWindow("dst2", CV_WINDOW_NORMAL); 57 cv::imshow("dst2", dst2); 58 59 cv::waitKey(0); 60 }

 

posted on 2019-07-20 21:21  AI大道理  阅读(1682)  评论(0编辑  收藏  举报

导航