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

如何用Python获取多边形边界包围区域的所有坐标点?

高效获取多边形包围区域所有坐标点的Python方案

针对你需要提取多边形边界包围的所有坐标点(用于图像区域高亮)的需求,以下几个Python库都是基于底层优化实现的,完全不需要手动写循环,效率远高于手动遍历:

1. OpenCV(首选,适配图像场景)

OpenCV的矩阵操作基于C++实现,速度极快,完美匹配图像区域处理的需求。核心思路是生成多边形掩码,再提取掩码中的非零坐标:

import cv2
import numpy as np

def get_polygon_inner_points(polygon, img_shape):
    # polygon: 输入的边界坐标列表,格式[[x1,y1], [x2,y2], ...]
    # img_shape: 图像的(高度, 宽度),可通过img.shape[:2]获取
    mask = np.zeros(img_shape, dtype=np.uint8)
    # 转换为OpenCV要求的多边形格式
    pts = np.array(polygon, np.int32).reshape((-1, 1, 2))
    # 填充多边形区域
    cv2.fillPoly(mask, [pts], 255)
    # 提取所有非零坐标,返回[x,y]格式的列表
    y_coords, x_coords = np.where(mask == 255)
    return np.column_stack((x_coords, y_coords)).tolist()

优势:纯向量化操作,无Python层循环,速度最快;直接适配图像场景,拿到坐标后可直接用于图像像素修改(高亮)。

2. Shapely(通用几何计算场景)

如果你的需求不局限于图像,需要更灵活的几何操作,Shapely是专业的几何计算库,底层经过优化:

from shapely.geometry import Polygon, Point
import numpy as np

def get_polygon_inner_points(polygon):
    poly = Polygon(polygon)
    # 获取多边形外接矩形,缩小待判断点的范围
    min_x, min_y, max_x, max_y = poly.bounds
    # 生成外接矩形内的所有整数坐标点
    x_vals = np.arange(int(np.floor(min_x)), int(np.ceil(max_x)) + 1)
    y_vals = np.arange(int(np.floor(min_y)), int(np.ceil(max_y)) + 1)
    xx, yy = np.meshgrid(x_vals, y_vals)
    all_points = np.column_stack((xx.ravel(), yy.ravel()))
    # 批量判断点是否在多边形内
    inside_mask = np.array([poly.contains(Point(p)) for p in all_points])
    # 筛选内部点
    return all_points[inside_mask].tolist()

优势:几何计算功能丰富,支持复杂多边形(含孔洞),通过外接矩形减少计算量,效率远高于手动射线法。

3. PIL/Pillow(轻量图像场景)

如果已经在用PIL处理图像,可直接用其绘图功能生成掩码并提取坐标:

from PIL import Image, ImageDraw
import numpy as np

def get_polygon_inner_points(polygon, img_shape):
    # img_shape: 图像的(宽度, 高度),注意与OpenCV的顺序相反
    mask = Image.new('L', img_shape, 0)
    draw = ImageDraw.Draw(mask)
    # 填充多边形
    draw.polygon(polygon, fill=255)
    # 转换为numpy数组提取坐标
    mask_np = np.array(mask)
    y_coords, x_coords = np.where(mask_np == 255)
    return np.column_stack((x_coords, y_coords)).tolist()

优势:轻量简洁,无需额外安装重型库(如果已用PIL),操作直观。


推荐选择

如果你的核心需求是图像区域高亮,优先用OpenCV方案,它的速度和适配性都是最优的,完全避免了手动循环的低效问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 10:53:08