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

如何在OpenCV Python中仅通过轮廓点求两个轮廓的并集?

直接通过轮廓点计算两个轮廓的并集(无需绘制后重找轮廓)

要实现仅靠轮廓点计算并集,核心是对多边形轮廓做几何运算,这里可以借助Shapely库(专门处理几何对象的Python库)直接操作轮廓点,不用绕绘制图像的流程。具体步骤如下:

步骤1:安装依赖

如果没装Shapely,先执行安装命令:

pip install shapely

步骤2:核心代码实现

假设你已经有两个OpenCV格式的轮廓contour1和contour2(每个轮廓是(N,1,2)的numpy数组),代码如下:

import cv2
import numpy as np
from shapely.geometry import Polygon
from shapely.ops import unary_union

def contour_union(contour1, contour2):
    # 把OpenCV轮廓格式转换为Shapely接受的点列表(去掉中间冗余维度)
    pts1 = contour1.reshape(-1, 2).tolist()
    pts2 = contour2.reshape(-1, 2).tolist()
    
    # 创建Shapely多边形对象
    poly1 = Polygon(pts1)
    poly2 = Polygon(pts2)
    
    # 计算两个多边形的并集
    union_poly = unary_union([poly1, poly2])
    
    # 把并集结果转换回OpenCV轮廓格式
    union_contours = []
    if union_poly.geom_type == 'Polygon':
        # 并集是单个多边形的情况
        coords = np.array(union_poly.exterior.coords, dtype=np.int32)
        union_contours.append(coords.reshape(-1, 1, 2))
    elif union_poly.geom_type == 'MultiPolygon':
        # 并集是多个分离多边形的情况
        for poly in union_poly.geoms:
            coords = np.array(poly.exterior.coords, dtype=np.int32)
            union_contours.append(coords.reshape(-1, 1, 2))
    
    return union_contours

# 示例调用
# 假设已获取到两个目标轮廓contour1、contour2
# union_result = contour_union(contour1, contour2)

关键说明

  • Shapely会自动处理多边形的重叠、嵌套等复杂情况,直接输出并集的几何形状
  • 转换回OpenCV轮廓时,需区分Polygon(单个轮廓)和MultiPolygon(多个分离轮廓)两种结果类型
  • 若你的轮廓包含内孔(嵌套轮廓),需要额外处理Shapely的内部环结构,常规外轮廓并集用上述代码即可满足需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:27:33