栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在numpy数组中生成填充的多边形

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在numpy数组中生成填充的多边形

以下解决方案仅需要numpy。它适用于凸多边形的顶点(在[行,列]坐标系中按顺时针顺序定义)。凹面多边形可以工作,但最终会切除凸出的点。

import numpy as npdef check(p1, p2, base_array):    """    Uses the line defined by p1 and p2 to check array of     input indices against interpolated value    Returns boolean array, with True inside and False outside of shape    """    idxs = np.indices(base_array.shape) # Create 3D array of indices    p1 = p1.astype(float)    p2 = p2.astype(float)    # Calculate max column idx for each row idx based on interpolated line between two points    max_col_idx = (idxs[0] - p1[0]) / (p2[0] - p1[0]) * (p2[1] - p1[1]) +  p1[1]        sign = np.sign(p2[0] - p1[0])    return idxs[1] * sign <= max_col_idx * signdef create_polygon(shape, vertices):    """    Creates np.array with dimensions defined by shape    Fills polygon defined by vertices with ones, all other values zero"""    base_array = np.zeros(shape, dtype=float)  # Initialize your array of zeros    fill = np.ones(base_array.shape) * True  # Initialize boolean array defining shape fill    # Create check array for each edge segment, combine into fill array    for k in range(vertices.shape[0]):        fill = np.all([fill, check(vertices[k-1], vertices[k], base_array)], axis=0)    # Set all values inside polygon to one    base_array[fill] = 1    return base_array# (Row, Col) Vertices of Polygon (Defined Clockwise)vertices = np.array([    [5,12],    [8,18],    [13,14],    [11,6],    [4,6],])polygon_array = create_polygon([20,20], vertices)# This section prints numbers at each vertex for visual check, just comment out # to print an array of only zeros and onesfor n, vertex in enumerate(vertices):    polygon_array[vertex[0],vertex[1]] = 10*(n+1)# Simple routine to print the final arrayfor row in polygon_array.tolist():    for c in row:        print '{:4.1f}'.format(c),    print ''


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661625.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号