如何正确使用cv2.fillPoly函数?多多边形填充报错求助
问题
尝试用cv2.fillPoly同时填充三角形和梯形两个多边形,代码如下:
# Import necessary libraries import cv2 import numpy as np # Read an image img = np.zeros((500,500)) # Define an array of endpoints of triangle points = np.array([[[160, 130], [350, 130], [250, 300]],[[160, 30], [50, 30], [80, 130],[100, 130]]],dtype=object) # Use fillPoly() function and give input as # image, end points,color of polygon # Here color of polygon will blue for i in range(len(points)): cv2.fillPoly(img, pts=[points[i]], color=(255, 0, 0)) #cv2.fillPoly(img, pts=[points[1]], color=(255, 0, 0)) # Displaying the image cv2.imshow("Triangle", img) # wait for the user to press any key to # exit window cv2.waitKey(0) # Closing all open windows cv2.destroyAllWindows()
运行后报错:
/var/folders/hh/phtw2ldx7gj88krjgwdbz9680000gn/T/ipykernel_1755/1373141779.py:9: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray. points = np.array([[[160, 130], [350, 130], [250, 300]],[[160, 30], [50, 30], [80, 130],[100, 130]]]) --------------------------------------------------------------------------- error Traceback (most recent call last) Input In [35], in <cell line: 14>() 11 # Use fillPoly() function and give input as 12 # image, end points,color of polygon 13 # Here color of polygon will blue 14 for i in range(len(points)): ---> 15 cv2.fillPoly(img, pts=[points[i]], color=(255, 0, 0)) 16 #cv2.fillPoly(img, pts=[points[1]], color=(255, 0, 0)) 17 18 19 # Displaying the image 20 cv2.imshow("Triangle", img) error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'fillPoly' > Overload resolution failed: > - Can't parse 'pts'. Sequence item with index 0 has a wrong type > - Can't parse 'pts'. Sequence item with index 0 has a wrong type
问题核心:两个多边形顶点数不同(3个和4个),使用dtype=object的numpy数组存储导致fillPoly无法解析pts参数。
解决方法
OpenCV的fillPoly要求每个多边形的顶点数组必须是固定维度的int32类型numpy数组,无需将不同顶点数的多边形塞进同一个object类型数组,直接用Python列表管理多个多边形即可。
修复后的代码
import cv2 import numpy as np # 创建单通道空白图像(uint8类型符合OpenCV图像格式要求) img = np.zeros((500, 500), dtype=np.uint8) # 用Python列表存储两个多边形,每个多边形转为shape=(N,1,2)的int32数组 polygons = [ # 三角形:转int32后调整形状为(3,1,2) np.array([[160, 130], [350, 130], [250, 300]], dtype=np.int32).reshape((-1, 1, 2)), # 梯形:转int32后调整形状为(4,1,2) np.array([[160, 30], [50, 30], [80, 130], [100, 130]], dtype=np.int32).reshape((-1, 1, 2)) ] # 遍历填充每个多边形 for poly in polygons: cv2.fillPoly(img, pts=[poly], color=255) # 单通道用灰度值,彩色图像可改为(255,0,0) # 显示结果 cv2.imshow("Polygons", img) cv2.waitKey(0) cv2.destroyAllWindows()
关键修复细节
- 放弃
dtype=object的numpy数组,改用Python列表存储不同顶点数的多边形,避免数组形状不统一问题。 - 每个多边形顶点数组必须是np.int32类型,且形状为
(顶点数量, 1, 2),通过reshape((-1,1,2))可自动适配任意顶点数。 - 图像数组指定
dtype=np.uint8,符合OpenCV处理图像的标准格式,避免类型不兼容问题。
内容的提问来源于stack exchange,提问作者Alain Michael Janith Schroter
相关产品推荐
相关产品推荐

