摘要
本篇用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實作
實作方法與思路:
- 原圖轉灰階圖後使用核大小201(奇數)做中值濾波;
- 灰階圖與濾波圖像做差,門檻值處理
- 形态學進一步提取缺陷
- 輪廓查找,通過面積篩選缺陷,顯示
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函數進行做差,得出圖像:
然後二值化,尋找輪廓,篩選得出缺陷輪廓。