VS2017&OPENCV4.0
#include
#include
#include
using namespace cv;
int main(int argc, char** argv) {
Mat src, dst;
src = imread("D:\\test.jpg");
if (!src.data) {
printf("could not load image...\n");
return -1;
}
char INPUT_WIN[] = "input image";
char OUTPUT_WIN[] = "result image";
namedWindow(INPUT_WIN, WINDOW_AUTOSIZE);
imshow(INPUT_WIN, src);
Mat gray_src;
cvtColor(src, gray_src, CV_BGR2GRAY);//改变颜色
namedWindow("gray image", WINDOW_AUTOSIZE);
imshow("gray image", gray_src);
Mat binImg;
adaptiveThreshold(~gray_src, binImg, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -2);// 转换为二值图像
/*解析adaptiveThreshold函数:adaptiveThreshold(
Mat src, // 输入的灰度图像
Mat dest, // 二值图像
double maxValue, // 二值图像最大值
int adaptiveMethod // 自适应方法,只能其中之一 –
// ADAPTIVE_THRESH_MEAN_C , ADAPTIVE_THRESH_GAUSSIAN_C
int thresholdType,// 阈值类型
int blockSize, // 块大小
double C // 常量C 可以是正数,0,负数
)
*/
namedWindow("binary image", WINDOW_AUTOSIZE);
imshow("binary image", binImg);
// 水平结构元素
Mat hline = getStructuringElement(MORPH_RECT, Size(src.cols / 16, 1), Point(-1, -1));
// 垂直结构元素
Mat vline = getStructuringElement(MORPH_RECT, Size(1, src.rows / 16), Point(-1, -1));
// 矩形结构
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
Mat temp1;
erode(binImg, temp1, hline);//腐蚀
dilate(temp1, dst, hline);//膨胀,提取水平
bitwise_not(dst, dst);
namedWindow("Final Result1", WINDOW_AUTOSIZE);
imshow("Final Result1", dst);
Mat temp2;
erode(binImg, temp2, vline);//腐蚀
dilate(temp2, dst, vline);//膨胀,提取垂直
bitwise_not(dst, dst);
namedWindow("Final Result2", WINDOW_AUTOSIZE);
imshow("Final Result2", dst);
Mat temp3;
erode(binImg, temp3, kernel);//腐蚀
dilate(temp3, dst, kernel);//膨胀,去掉干扰项
bitwise_not(dst, dst);
namedWindow("Final Result3", WINDOW_AUTOSIZE);
imshow("Final Result3", dst);
waitKey(0);
return 0;
}