步驟:
- 讀取圖片
- 轉換為灰度圖片
- 將灰度圖片轉化為二值圖片 adaptiveThreshold()
- 腐蝕
- 膨脹
adapativeThreshold():
#include<opencv2/opencv.hpp> #include<iostream> using namespace cv; using namespace std; Mat src, dst, bilary_gray, output; int main(int argc, char** argv) { src = imread("D:/OpenCVprj/image/test6.jpg"); if (!src.data) { cout << "Could not load image......\n" << endl; return -1; } imshow("src", src); cvtColor(src, dst, CV_BGR2GRAY); imshow("dst", dst); adaptiveThreshold(~dst, bilary_gray, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -2); //double maxValue,二值圖像最大值 //int adaptiveMethod,自適應方法,只能其中之一 - ADAPTIVE_THRESH_MEAN_C , ADAPTIVE_THRESH_GAUSSIAN_C //int thresholdType,閾值類型 //int blockSize,塊大小 //double C, 常量C 可以是正數,0,負數 imshow("bilary_gray", bilary_gray); Mat kernel1 = getStructuringElement(MORPH_RECT, Size(dst.cols/16, 1), Point(-1, -1)); //Mat kernel2 = getStructuringElement(MORPH_RECT, Size(1, dst.rows/16), Point(-1, -1)); erode(bilary_gray, dst, kernel1); dilate(dst, output, kernel1); bitwise_not(output, output); imshow("output", output); waitKey(0); return 0; }
應用補充:
#include<opencv2/opencv.hpp> #include<iostream> using namespace cv; using namespace std; Mat src, dst, bilary_gray, output; int main(int argc, char** argv) { src = imread("D:/OpenCVprj/image/test6.jpg"); if (!src.data) { cout << "Could not load image......\n" << endl; return -1; } imshow("src", src); cvtColor(src, dst, CV_BGR2GRAY); imshow("dst", dst); adaptiveThreshold(~dst, bilary_gray, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -2); //double maxValue,二值圖像最大值 //int adaptiveMethod,自適應方法,只能其中之一 - ADAPTIVE_THRESH_MEAN_C , ADAPTIVE_THRESH_GAUSSIAN_C //int thresholdType,閾值類型 //int blockSize,塊大小 //double C, 常量C 可以是正數,0,負數 imshow("bilary_gray", bilary_gray); //Mat kernel1 = getStructuringElement(MORPH_RECT, Size(dst.cols/16, 1), Point(-1, -1)); //Mat kernel2 = getStructuringElement(MORPH_RECT, Size(1, dst.rows/16), Point(-1, -1)); Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1)); erode(bilary_gray, dst, kernel); dilate(dst, output, kernel); bitwise_not(output, output); //blur(output, output, Size(3, 3), Point(-1, -1)); imshow("output", output); waitKey(0); return 0; }