opencv-057-二值图像分析(点多边形测试)

知识点

对于轮廓图像,有时候还需要判断一个点是在轮廓内部还是外部,OpenCV中实现这个功能的API叫做点多边形测试,它可以准确的得到一个点距离多边形的距离,如果点是轮廓点或者属于轮廓多边形上的点,距离是零,如果是多边形内部的点是是正数,如果是负数返回表示点是外部。

API

1
2
3
4
5
6
7
8
double cv::pointPolygonTest(
InputArray contour,
Point2f pt,
bool measureDist
)
Contour轮廓所有点的集合
Pt 图像中的任意一点
MeasureDist如果是True,则返回每个点到轮廓的距离,如果是False则返回+1,0,-1三个值,其中+1表示点在轮廓内部,0表示点在轮廓上,-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
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 二值图像分析(点多边形测试)
*/
int main() {
Mat src = imread("../images/my_mask.png");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

// 二值化
Mat dst, gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);

// 轮廓发现与绘制
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());

Mat image = Mat::zeros(src.size(), CV_32FC3);
// 对轮廓内外的点进行分类
for (int row = 0; row < src.rows; ++row) {
for (int col = 0; col < src.cols; ++col) {
double dist = pointPolygonTest(contours[0], Point(col, row), true);
if (dist == 0) {
image.at<Vec3f>(row, col) = Vec3f(255, 255, 255);
} else if (dist > 0) {
image.at<Vec3f>(row, col) = Vec3f(255 - dist, 0, 0);
} else {
image.at<Vec3f>(row, col) = Vec3f(0, 0, 255 + dist);
}
}
}
convertScaleAbs(image, image);
imshow("points", image);

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

src = cv.imread("D:/images/my_mask.png")
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 | cv.THRESH_OTSU)
cv.imshow("binary", binary)

# 轮廓发现
image = np.zeros(src.shape, dtype=np.float32)
out, contours, hierarchy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
h, w = src.shape[:2]
for row in range(h):
for col in range(w):
dist = cv.pointPolygonTest(contours[0], (col, row), True)
if dist == 0:
image[row, col] = (255, 255, 255)
if dist > 0:
image[row, col] = (255-dist, 0, 0)
if dist < 0:
image[row, col] = (0, 0, 255+dist)

dst = cv.convertScaleAbs(image)
dst = np.uint8(dst)

# 显示
cv.imshow("contours_analysis", dst)
cv.imwrite("D:/contours_analysis.png", dst)
cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github