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

如何获取OpenCV中cv.polylines绘制的多边形像素数据?

如何直接获取OpenCV绘制多边形的像素坐标?

首先,OpenCV绘制多边形的常规代码如下:

import numpy as np
import cv2 as cv

img = np.zeros((125, 240, 3), dtype = "uint8")
poly = np.array([[[20,15],[210,30],[220,100],[20,100]]], np.int32)
cv.polylines(img, [poly], True, (0,0,255), 1)

cv.imshow('Shapes', img)
cv.waitKey(0)
cv.destroyAllWindows()

示例图像

需求说明

需要获取上述多边形红线经过的所有像素数据,要求输出数组尺寸为(n, 2)或(1, n, 2)。

当前采用的方案

通过填充多边形后提取轮廓的方式实现:

mask = np.zeros((125, 240), dtype = "uint8")
cv.fillPoly(mask, poly, 255)
contours, _ = cv.findContours(mask, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
contour = contours[0][:, 0, :]

# 输出示例:
# array([[20, 15],
#        [20, 16],
#        [20, 17],
#        ...,
#        [23, 15],
#        [22, 15],
#        [21, 15]], dtype=int32)

问题解答

OpenCV的cv.polylines函数本身不会直接返回绘制的像素坐标——它的设计目标是修改输入图像完成渲染,内部使用的绘制算法(如Bresenham直线算法)不会暴露生成的像素点列表,只会将结果写入图像数组。

不过可以通过直接检测绘制后图像中的目标像素,来更高效地获取这些坐标,步骤如下:

import numpy as np
import cv2 as cv

# 初始化图像并绘制多边形
img = np.zeros((125, 240, 3), dtype="uint8")
poly = np.array([[[20,15],[210,30],[220,100],[20,100]]], np.int32)
cv.polylines(img, [poly], True, (0,0,255), 1)

# 提取所有红色像素的坐标(对应绘制的红线)
# np.where返回(y, x)格式,转换为OpenCV常用的(x, y)顺序
y_coords, x_coords = np.where(np.all(img == (0, 0, 255), axis=-1))
poly_pixels = np.column_stack((x_coords, y_coords))

# 得到的poly_pixels形状为(n, 2),符合需求
print(poly_pixels.shape)

这种方法无需填充多边形再提取轮廓,直接从绘制后的图像中提取目标像素,更贴合“从cv.polylines绘制结果获取像素”的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 10:40:28