fillConvexPoly() 和 fillPoly() 函数是用来填充图像不规则区域的颜色的。

fillConvexPoly() 函数

此函数,只能用来填充凸多边形。只需要提供凸多边形的顶点即可。相较于下边提到的 fillPoly() 函数,它的速度更快。

1
2
3
4
5
6
7
void fillConvexPoly(InputOutputArray img, InputArray points,  
const Scalar& color, int lineType = LINE_8,
int shift = 0);

void fillConvexPoly(InputOutputArray img, const Point* pts, int npts,
const Scalar& color, int lineType = LINE_8,
int shift = 0);

参数说明

img:输入图像。
points:多边形各个顶点的位置。
pts:指向单个多边形的指针数组。
npts:多边形的顶点个数。
color:多边形的颜色。
lineType:组成多边形的线条的类型 (or 0)
- 8 - connected line (8邻接)连接线。
- 4 - connected line (4邻接)连接线。
- AA - antialiased 线条。
shift:顶点坐标的小数点位数。

LineType

1
2
3
4
5
6
enum LineTypes {  
FILLED = -1, // Fill 填充
LINE_4 = 4, //!< 4-connected line
LINE_8 = 8, //!< 8-connected line
LINE_AA = 16 //!< antialiased line
};

fillPoly() 函数

可以用来填充任意形状的图型,可以用来绘制多边形。也可以使用非常多个边来近似的画一条曲线。并且可以一次填充多个图型。

1
2
3
4
5
6
7
8
void fillPoly(InputOutputArray img, InputArrayOfArrays pts,  
const Scalar& color, int lineType = LINE_8, int shift = 0,
Point offset = Point() );

void fillPoly(InputOutputArray img, const Point** pts,
const int* npts, int ncontours,
const Scalar& color, int lineType = LINE_8, int shift = 0,
Point offset = Point() );

参数说明

img:输入图像。
pts:指向多边形的数组指针。
npts:多边形的顶点个数的数组。
contours:组成填充区域的线段的数量。
color:多边形的颜色。
lineType:组成多边形的线条的类型。
shift:顶点坐标的小数点位数。
offset:轮廓所有点的偏移,可选。

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/python
# coding=utf-8

import cv2
from matplotlib import pyplot as plt

import numpy as np

img = cv2.imread('pictures/photo_faces.jpg')
origin = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # 将图像转换为RGB格式 原因:matplotlib 的颜色通道是GBR,不是一般的RGB
plt.subplot(121),plt.imshow(origin),plt.title('Origin')

points1 = np.array([[50,10], [300,12], [350,250],[9,250]])
cv2.fillConvexPoly(origin, points1,(255,0,0))

points2 = np.array([[450,10], [700,12], [750,250],[409,250]])
cv2.fillPoly(origin, [points2], (0, 255, 0))

plt.subplot(122),plt.imshow(origin),plt.title('Fill')

plt.suptitle('Fill Poly samples')
plt.show()

测试结果