複雜背景的缺陷提取

唯有自己強大發表於2021-06-18

摘要

本篇用halcon和opencv分別實現對於複雜背景下的缺陷提取實戰


如下圖,背景很複雜,周圍劃痕都是正常區域。要提取中間小塊的黑色區域(缺陷區域)。單純用頻域濾波和閾值提取,效果一般。都會把周圍的劃痕提取出來。

Halcon實現

思路:

通過中值濾波後,對影像進行動態閾值提取細化缺陷部分,結合開運算,閉運算提取缺陷。

read_image (Image, 'D:/opencv練習圖片/複雜背景提取缺陷.jpg')
dev_set_line_width (3)
threshold (Image, Region, 30, 255)
reduce_domain (Image, Region, ImageReduced)
mean_image (ImageReduced, ImageMean, 150, 150)
dyn_threshold (ImageReduced, ImageMean, SmallRaw, 37, 'dark')
opening_circle (SmallRaw, RegionOpening,4.5)
closing_circle (RegionOpening, RegionClosing, 7)
connection (RegionClosing, ConnectedRegions)
dev_set_color ('red')
dev_display (Image)
dev_set_draw ('margin')
dev_display (ConnectedRegions)

 Opencv實現

 實現方法與思路:

  1. 原圖轉灰度圖後使用核大小201(奇數)做中值濾波;
  2. 灰度圖與濾波影像做差,閾值處理
  3. 形態學進一步提取缺陷
  4. 輪廓查詢,通過面積篩選缺陷,顯示
int main(int argc, char** argv)
{
    Mat src = imread("D:/opencv練習圖片/複雜背景提取缺陷.jpg");
    imshow("輸入影像", src);
    Mat gray, gray_mean,dst,binary1, binary2, binary;
    cvtColor(src, gray, COLOR_BGR2GRAY);
    medianBlur(gray, gray_mean, 201);
    imshow("中值濾波", gray_mean);
    addWeighted(gray, -1, gray_mean, 1, 0, dst);
    imshow("做差", dst);
    //閾值提取
    threshold(dst, binary1, 10, 255, THRESH_BINARY|THRESH_OTSU);
    imshow("二值化", binary1);
    Mat src_open, src_close;
    //形態學
    Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(7, 7), Point(-1, -1));
    morphologyEx(binary1, src_open, MORPH_OPEN, kernel, Point(-1, -1));
    imshow("開運算", src_open);
    morphologyEx(src_open, src_close, MORPH_CLOSE, kernel, Point(-1, -1));
    imshow("閉運算", src_close);
    vector<vector<Point>>contours;
    findContours(src_close, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE, Point());
    for (int i = 0; i < contours.size(); i++)
    {
        float area = contourArea(contours[i]);
        cout << area << endl;
        if (area > 1000)
        {
            drawContours(src, contours, i, Scalar(0, 0, 255), 2, 8);
        }
    }
    imshow("結果", src);
    waitKey(0);
    return 0;
}

這裡巧用了addWeighted函式進行做差,得出影像:

然後二值化,尋找輪廓,篩選得出缺陷輪廓。

 

相關文章