#include <iostream>
//#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
//#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
//#include "opencv2/features2d.hpp"
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
//cv::Mat image, imagemean, diff, Mask;
Mat image, imagemean, diff, Mask;
image = imread("1.png");
blur(image, imagemean, Size(13, 13)); //低通滤波blur,平滑增强,抑制图片边界
subtract(imagemean, image, diff); //图像的减运算
threshold(diff, Mask, 5, 255, THRESH_BINARY_INV);//二值化,同动态阈值分割dyn_threshold
imshow("image", image);
imshow("imagemean", imagemean);
imshow("diff", diff);
imshow("Mask", Mask);
Mat imagegray;
cvtColor(Mask, imagegray, CV_RGB2GRAY); //颜色空间转换
vector<vector<Point> > contours; //双重向量
vector<Vec4i> hierarchy;
findContours(imagegray, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); //检测物体的轮廓
Mat drawing = Mat::zeros(Mask.size(), CV_8U);
int j = 0;
for (int i = 0; i < contours.size(); i++)
{
Moments moms = moments(Mat(contours[i]));
double area = moms.m00; //零阶矩即为二值图像的面积 double area = moms.m00;
//如果面积超出了设定的范围,则不再考虑该斑点
if (area > 10 && area < 2000) //划痕面积范围
{
drawContours(drawing, contours, i, Scalar(255), FILLED, 8, hierarchy, 0, Point());
j = j + 1;
}
}
cv::Mat element15(3, 3, CV_8U, cv::Scalar(1));
cv::Mat close;
cv::morphologyEx(drawing, close, cv::MORPH_CLOSE, element15); //闭运算 ,先膨胀后腐蚀的过程称为闭运算。它具有填充物体内细小空洞,连接邻近物体和平滑边界的作用。
imshow("drawing", drawing);
vector<vector<Point> > contours1;
vector<Vec4i> hierarchy1;
findContours(close, contours1, hierarchy1, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
imshow("close", close);
j = 0;
int m = 0;
for (int i = 0; i < contours1.size(); i++)
{
Moments moms = moments(Mat(contours1[i])); //moments()来计算图像中的中心矩
double area = moms.m00; //零阶矩即为二值图像的面积 double area = moms.m00;
//如果面积超出了设定的范围,则不再考虑该斑点
double area1 = contourArea(contours1[i]);
if (area > 200 && area < 2000)
{
drawContours(image, contours1, i, Scalar(0, 0, 255), FILLED, 8, hierarchy1, 0, Point());//红
j = j + 1;
}
else if (area >= 10 && area <= 200)
{
drawContours(image, contours1, i, Scalar(255, 0, 0), FILLED, 8, hierarchy1, 0, Point()); // 蓝 B G R
m = m + 1;
}
}
/*char t[256];
sprintf_s(t, "%01d", j);
string s = t;
string txt = "Long NG : " + s;
putText(image, txt, Point(20, 30), CV_FONT_HERSHEY_COMPLEX, 1,
Scalar(0, 0, 255), 2, 8);
sprintf_s(t, "%01d", m);
s = t;
txt = "Short NG : " + s;
putText(image, txt, Point(20, 60), CV_FONT_HERSHEY_COMPLEX, 1,
Scalar(255, 0, 0), 2, 8);
*/
imshow("漏洞", image);
imwrite("52.jpg", close);
imwrite("53.jpg", image);
waitKey();
return 0;
}