今天读了一篇论文,关于轮轴柱面表面缺陷检测,柱面图像易受打光的影响导致图像亮度不均匀,因此不能直接使用阈值分割算法检测缺陷。使用两种办法可以改善算法,一:增加缺陷灰度值在图像中的占比;二:只用像素动态阈值分割,也就是每一个像素具有一个自适应的阈值。
文中使用第二种方法,提到使用近邻域灰度值加权均值代替原灰度值,然后与原图像作差,获得阈值图,再进行分割,经试验证明,对于有缺陷和无缺陷的图像可以达到较高的准确率。
近邻灰度值加权均值:
代码:
void filters(Mat &gray, Mat &dst) {
int Structure[5][5] = { 1, 4, 1, 4, 8, 4, 1, 4, 1 };
int m, n;
int sum = 0;
//模板求和
for (m = 0; m < 3; m++) {
for (n = 0; n < 3; n++) {
sum += Structure[m][n];
}
}
//扫描像素点
//四周
for (int j = 0; j < gray.rows ; j++) {
dst.at<uchar>(j, 0) = gray.at<uchar>(j, 0);
dst.at<uchar>(j, gray.cols-1) = gray.at<uchar>(j, gray.cols-1);
}
for (int i = 0; i < gray.cols; i++) {
dst.at<uchar>(0, i) = gray.at<uchar>(0, i);
dst.at<uchar>(gray.rows-1, i) = gray.at<uchar>(gray.rows-1, i);
}
//内部像素
for (int j = 1; j < gray.rows - 1; j++){
for (int i = 1; i < gray.cols - 1; i++) {
dst.at<uchar>(j,i) =(gray.at<uchar>(j - 1, i - 1)*Structure[0][0] +
gray.at<uchar>(j - 1, i)*Structure[0][1]+
gray.at<uchar>(j - 1, i + 1)*Structure[0][2] +
gray.at<uchar>(j , i - 1)*Structure[1][0] +
gray.at<uchar>(j, i)*Structure[1][1] +
gray.at<uchar>(j, i + 1)*Structure[1][2] +
gray.at<uchar>(j + 1, i - 1)*Structure[2][0] +
gray.at<uchar>(j + 1, i)*Structure[2][1] +
gray.at<uchar>(j + 1, i + 1)*Structure[2][2]
)/sum + 0.5;
}
}
// cout << "hello" << endl;
}
结果:
直接阈值分割,结果惨不忍睹。
使用文中方法检测到的缺陷。
若侵权请联系我删除。