python+opencv填充图像不规则区域:fillPoly和fillConvexPoly区别、半透明填充方法

目录

一、用某种颜色填充

1)cv2.fillConvexPoly

2)cv2.fillPoly

二、半透明填充


一、用某种颜色填充

1)cv2.fillConvexPoly

cv2.fillConvexPoly()函数,只能用来填充凸多边形

只需要提供凸多边形的顶点即可。

例:

img = np.zeros((1080, 1920, 3), np.uint8)
triangle = np.array([[0, 0], [1500, 800], [500, 400]])
cv2.fillConvexPoly(img, triangle, (255, 255, 255))
plt.imshow(img)
plt.show()

2)cv2.fillPoly

cv2.fillPoly()函数可以用来填充任意形状的图型,可以用来绘制多边形。也可以使用非常多个边来近似的画一条曲线。cv2.fillPoly()函数可以一次填充多个图型。

在刚开始使用cv2.fillPoly()时,会发现没有效果,只有轮廓线被染色了,内部却没有被填充。这是因为忘记了加中括号。

点构成的边界,要加中括号[  ]。见下面例子:

contours是一堆边界,往往是通过二值化操作、cv2.findContours方法找到的结果。这里近取出第1个边界数组来画。

cv2.fillPoly(img,[contours[1]],(255,0,0))  #填充内部
cv2.fillPoly(img,contours[1],(255,0,0)) #只染色边界

二、半透明填充

有时候希望有半透明的填充效果,可以用cv2.addWeighted方法。

alpha = 0.7
beta = 1-alpha
gamma = 0
img_add = cv2.addWeighted(img1, alpha,img2, beta, gamma)
cv2.imwrite('final ret.jpg',img_add)
cv2.imshow('img_add',img_add)
if cv2.waitKey(500) and 0xff == ord('q'):
    cv2.destroyAllWindows()

函数使用:cv2.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]]) → dst,实际使用时,简化为src1, alpha, src2, beta, gamma五个参数就可以了。具体参数含义如下:

src1 – first input array.

alpha – weight of the first array elements.

src2 – second input array of the same size and channel number as src1.

beta – weight of the second array elements.

dst – output array that has the same size and number of channels as the input arrays.

gamma – scalar added to each sum.

dtype – optional depth of the output array; when both input arrays have the same depth, dtype can be set to -1, which will be equivalent to src1.depth().

发布了150 篇原创文章 · 获赞 334 · 访问量 74万+

猜你喜欢

转载自blog.csdn.net/lyxleft/article/details/90676451
今日推荐