效果图:
代码:
#include <opencv2/opencv.hpp> #include <iostream> #include <math.h> using namespace cv; using namespace std; Mat src, dst,dst2; //膨胀腐蚀的应用:消除噪声 int main() { //原图 src = imread(".//pic//ABC.png", IMREAD_UNCHANGED); namedWindow("input image", CV_WINDOW_AUTOSIZE); imshow("input image", src); //转成灰度图 Mat gray_src; cvtColor(src, gray_src, CV_BGR2GRAY); imshow("gray image", gray_src); //转成二值图 Mat binImg; //255:二值图像的最大值 //ADAPTIVE_THRESH_MEAN_C:自适应方法 //THRESH_BINARY:阈值类型 //15:块大小 //取反可以把目标变白,灰度值大 adaptiveThreshold(~gray_src, binImg, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, 0); imshow("bin image", binImg); Mat tmp; int s = 3; Mat structureElement = getStructuringElement(MORPH_RECT, Size(s, s), Point(-1, -1)); erode(binImg, tmp, structureElement, Point(-1, -1)); imshow("腐蚀后的图", tmp); dilate(tmp, dst, structureElement, Point(-1, -1)); dst = ~dst; imshow("膨胀后的图", dst); waitKey(0); return 0; }