opencv-072-二值图像分析(缺陷检测一)

知识点

缺陷检测,分为两个部分,一个部分是提取指定的轮廓,第二个部分通过对比实现划痕检测与缺角检测。本次主要搞定第一部分,学会观察图像与提取图像ROI对象轮廓外接矩形与轮廓。

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 二值图像分析(缺陷检测一)
*/
int main() {
Mat src = imread("../images/ce_02.jpg");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

// 二值图像
Mat gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);

// 开操作,去掉一些小块
Mat se = getStructuringElement(MORPH_RECT, Size(3, 3));
morphologyEx(binary, binary, MORPH_OPEN, se);

// 绘制轮廓
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE);
int height = src.rows;
for (size_t t = 0; t < contours.size(); t++) {
Rect rect = boundingRect(contours[t]);
double area = contourArea(contours[t]);
if (rect.height > (height / 2)) {
continue;
}
if (area < 150) {
continue;
}
// 绘制外接矩形
rectangle(src, rect, Scalar(0, 0, 255),2);
// 绘制轮廓
drawContours(src, contours, t, Scalar(0, 255, 0), 2);
}

imshow("result", src);

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import cv2 as cv
import numpy as np

src = cv.imread("D:/images/ce_02.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)

# 图像二值化
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)

se = cv.getStructuringElement(cv.MORPH_RECT, (3, 3), (-1, -1))
binary = cv.morphologyEx(binary, cv.MORPH_OPEN, se)
cv.imshow("binary", binary)

# 轮廓提取
contours, hierarchy = cv.findContours(binary, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
height, width = src.shape[:2]
for c in range(len(contours)):
x, y, w, h = cv.boundingRect(contours[c])
area = cv.contourArea(contours[c])
if h > (height//2):
continue
if area < 150:
continue
cv.rectangle(src, (x, y), (x+w, y+h), (0, 0, 255), 1, 8, 0)
cv.drawContours(src, contours, c, (0, 255, 0), 2, 8)

cv.imshow("result", src)
cv.imwrite("D:/binary2.png", src)

cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github