基本的步骤:
- 图像形态学梯度
- 灰度转化
- 全局阈值二值化
- 轮廓分析
void morphologyEx_gradient(Mat& src) {
//1. 图像形态学梯度
Mat kernel, gradient_Img;
kernel=getStructuringElement(MORPH_RECT, Size(3, 3));
morphologyEx(src, gradient_Img, MORPH_GRADIENT, kernel);
imshow("gradientImg", gradient_Img);
//2. 灰度转化
Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY);
//3. 全局阈值二值化
Mat binary;
threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
imshow("binary", binary);
//4. 轮廓分析
vector<vector<Point>> contours;
//4.1 找到轮廓
findContours(binary, contours, RETR_TREE, CHAIN_APPROX_SIMPLE);
//4.2 遍历每一个轮廓
for (size_t i = 0; i < contours.size(); i++)
{
//4.3 找到每一个轮廓的正外接矩形
Rect rect=boundingRect(contours[i]);
//4.4 每个轮廓的最小外接矩形
double area = contourArea(contours[i]);
//4.5 根据条件画出符合要求的轮廓.
if (area < 200)
continue;
int h = rect.height;
int w = rect.width;
if (h > (3 * w) || h < 20)
continue;
rectangle(src, rect, Scalar(0, 0, 255), 1);
}
imshow("dst", src);
}
画出图像的轮廓:
//4.2 遍历每一个轮廓
for (size_t i = 0; i < contours.size(); i++)
{
//4.3 找到每一个轮廓的正外接矩形
Rect rect=boundingRect(contours[i]);
//4.4 每个轮廓的最小外接矩形
double area = contourArea(contours[i]);
//4.5 根据条件画出符合要求的轮廓.
if (area < 200)
continue;
int h = rect.height;
int w = rect.width;
if (h > (3 * w) || h < 20)
continue;
drawContours(src, contours, i, Scalar(255, 255, 255), 3);
rectangle(src, rect, Scalar(0, 0, 255), 1);
}