opencv-048-二值图像分析之轮廓发现

知识点

图像连通组件分析,可以得到二值图像的每个连通组件,但是我们还无法得知各个组件之间的层次关系与几何拓扑关系,如果我们需要进一步分析图像轮廓拓扑信息就可以通过OpenCV的轮廓发现API获取二值图像的轮廓拓扑信息.

轮廓发现API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void cv::findContours(
InputOutputArray image,
OutputArrayOfArrays contours,
OutputArray hierarchy,
int mode,
int method,
Point offset = Point()
)
各个参数详解如下:
Image表示输入图像,必须是二值图像,二值图像可以threshold输出、Canny输出、inRange输出、自适应阈值输出等。
Contours获取的轮廓,每个轮廓是一系列的点集合
Hierarchy轮廓的层次信息,每个轮廓有四个相关信息,分别是同层下一个、前一个、第一个子节点、父节点
mode 表示轮廓寻找时候的拓扑结构返回
-RETR_EXTERNAL表示只返回最外层轮廓
-RETR_TREE表示返回轮廓树结构

Method表示轮廓点集合取得是基于什么算法,常见的是基于CHAIN_APPROX_SIMPLE链式编码方法

绘制轮廓API

1
2
3
4
5
6
7
8
9
10
11
12
13
void cv::drawContours(
InputOutputArray image,
InputArrayOfArrays contours,
int contourIdx,
const Scalar & color,
int thickness = 1,
int lineType = LINE_8,
InputArray hierarchy = noArray(),
int maxLevel = INT_MAX,
Point offset = Point()
)
当thickness为正数的时候表示绘制该轮廓
当thickness为-1表示填充该轮廓

代码(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
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 二值图像分析之轮廓发现
*/
int main() {
Mat src1 = imread("../images/master.jpg");
Mat src2 = imread("../images/coins.jpg");
if (src1.empty() || src2.empty()) {
cout << "could not load image.." << endl;
}
//imshow("input_1", src1);
imshow("input_2", src2);

// 去噪声与二值化
Mat dst, gray, binary;
GaussianBlur(src2, dst, Size(3, 3), 0, 0);
cvtColor(dst, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
imshow("binary", binary);

// 轮廓发现与绘制
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point());
for (auto t = 0; t < contours.size(); ++t) {
drawContours(src2, contours, t, Scalar(0,0,255), 2, 8);
}
imshow("contours", src2);

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
34
35
import cv2 as cv
import numpy as np


def threshold_demo(image):
# 去噪声+二值化
dst = cv.GaussianBlur(image,(3, 3), 0)
gray = cv.cvtColor(dst, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_OTSU | cv.THRESH_BINARY)
cv.imshow("binary", binary)
return binary


def canny_demo(image):
t = 100
canny_output = cv.Canny(image, t, t * 2)
cv.imshow("canny_output", canny_output)
return canny_output


src = cv.imread("D:/images/yuan_test.png")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
binary = threshold_demo(src)

# 轮廓发现
out, contours, hierarchy = cv.findContours(binary, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
for c in range(len(contours)):
cv.drawContours(src, contours, c, (0, 0, 255), 2, 8)

# 显示
cv.imshow("contours-demo", src)

cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github