You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCV fillPoly填充超出polylines轮廓的临时解决方案(支持凹多边形)

OpenCV fillPoly 边界溢出临时解决方案(支持凹多边形)

针对OpenCV中fillPoly存在的边界溢出bug(填充区域超出polylines绘制的轮廓范围),以下是两种支持凹多边形的临时修复方案:

方案1:掩码修正法(保留fillPoly调用逻辑)

核心思路是先用精确的轮廓掩码过滤掉fillPoly溢出的部分:

import cv2
import numpy as np

# 初始化画布
img = np.zeros((500, 500, 3), dtype=np.uint8)
# 凹多边形顶点示例
pts = np.array([[100, 100], [400, 100], [400, 400], [250, 250], [100, 400]], np.int32)
pts = pts.reshape((-1, 1, 2))

# 1. 生成与轮廓完全匹配的掩码(drawContours填充无溢出问题)
mask = np.zeros(img.shape[:2], dtype=np.uint8)
cv2.drawContours(mask, [pts], 0, 255, thickness=cv2.FILLED)

# 2. 执行原fillPoly操作(允许溢出)
cv2.fillPoly(img, [pts], (255, 0, 0))

# 3. 用掩码剔除溢出区域
img = cv2.bitwise_and(img, img, mask=mask)

# 4. 绘制红色轮廓
cv2.polylines(img, [pts], True, (0, 0, 255), 2)

cv2.imshow('Fixed Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

原理

drawContours的填充逻辑对凹多边形支持准确,不会出现边界偏移,用它生成的掩码能精准覆盖polylines的轮廓范围,再通过位运算过滤掉fillPoly溢出的像素。

方案2:直接用drawContours替代fillPoly(更高效)

如果可以替换填充方式,直接使用drawContours完成填充,完全避开fillPoly的bug:

import cv2
import numpy as np

img = np.zeros((500, 500, 3), dtype=np.uint8)
pts = np.array([[100, 100], [400, 100], [400, 400], [250, 250], [100, 400]], np.int32)
pts = pts.reshape((-1, 1, 2))

# 用drawContours填充多边形(支持凹多边形,无边界溢出)
cv2.drawContours(img, [pts], 0, (255, 0, 0), thickness=cv2.FILLED)
# 绘制红色轮廓
cv2.polylines(img, [pts], True, (0, 0, 255), 2)

cv2.imshow('Fixed Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

优势

无需额外掩码操作,代码更简洁,执行效率更高,且填充结果与polylines轮廓完全对齐。

内容的提问来源于stack exchange,提问作者Fnord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 20:35:03