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

如何在numpy数组中创建矩形等多边形形状并支持旋转操作

Numpy数组生成空心矩形/多边形轮廓实现方案

1. 无旋转空心矩形生成

直接通过坐标索引赋值即可实现,代码如下:

import numpy as np

def create_hollow_rect(canvas_size: tuple, top_left: tuple, width: int, height: int) -> np.ndarray:
    """
    canvas_size: 画布大小,格式为(高度, 宽度)
    top_left: 矩形左上角坐标,格式为(x坐标, y坐标)
    width: 矩形宽度
    height: 矩形高度
    """
    canvas = np.zeros(canvas_size, dtype=np.int8)
    x1, y1 = top_left
    x2, y2 = x1 + width - 1, y1 + height - 1
    # 绘制上下边界
    canvas[y1, x1:x2+1] = 1
    canvas[y2, x1:x2+1] = 1
    # 绘制左右边界
    canvas[y1+1:y2, x1] = 1
    canvas[y1+1:y2, x2] = 1
    return canvas

# 生成你给出的5x5示例数组
sample = create_hollow_rect((5,5), (1,1), 3, 3)
print(sample)

运行输出:

[[0 0 0 0 0]
 [0 1 1 1 0]
 [0 1 0 1 0]
 [0 1 1 1 0]
 [0 0 0 0 0]]

2. 支持旋转的空心矩形生成

实现思路:先计算矩形四个顶点坐标,对顶点做旋转变换后再绘制轮廓即可,可借助scikit-image的多边形轮廓绘制接口简化实现:
首先安装依赖:pip install scikit-image
代码如下:

import numpy as np
import math
from skimage.draw import polygon_perimeter

def rotate_point(px: int, py: int, cx: int, cy: int, angle_deg: float) -> tuple:
    """将点(px,py)绕中心点(cx,cy)旋转指定角度(角度制),返回旋转后的坐标"""
    angle_rad = math.radians(angle_deg)
    cos_a = math.cos(angle_rad)
    sin_a = math.sin(angle_rad)
    # 坐标平移到原点
    px -= cx
    py -= cy
    # 旋转变换
    new_x = px * cos_a - py * sin_a
    new_y = px * sin_a + py * cos_a
    # 坐标平移回原坐标系
    return int(round(new_x + cx)), int(round(new_y + cy))

def create_rotated_hollow_rect(canvas_size: tuple, center: tuple, width: int, height: int, angle_deg: float) -> np.ndarray:
    """
    canvas_size: 画布大小,格式为(高度, 宽度)
    center: 矩形旋转中心坐标,格式为(x坐标, y坐标)
    width: 矩形宽度
    height: 矩形高度
    angle_deg: 旋转角度(角度制)
    """
    canvas = np.zeros(canvas_size, dtype=np.int8)
    cx, cy = center
    half_w, half_h = width // 2, height // 2
    # 定义未旋转时的四个顶点
    raw_points = [
        (cx - half_w, cy - half_h),
        (cx + half_w, cy - half_h),
        (cx + half_w, cy + half_h),
        (cx - half_w, cy + half_h)
    ]
    # 旋转所有顶点
    rotated_points = [rotate_point(x, y, cx, cy, angle_deg) for x, y in raw_points]
    x_list = [p[0] for p in rotated_points]
    y_list = [p[1] for p in rotated_points]
    # 绘制多边形轮廓,自动裁剪超出画布的部分
    rr, cc = polygon_perimeter(y_list, x_list, shape=canvas_size, clip=True)
    canvas[rr, cc] = 1
    return canvas

# 示例:生成15x15画布,中心在(7,7),宽6高4,旋转45度的空心矩形
rotated_sample = create_rotated_hollow_rect((15,15), (7,7), 6, 4, 45)
print(rotated_sample)

如果不想引入第三方依赖,可自行实现Bresenham直线绘制算法,依次连接四个旋转后的顶点绘制轮廓即可。

3. 任意多边形生成拓展

如果需要生成其他形状的多边形轮廓,只需要将上述代码中的矩形四个顶点替换为对应多边形的顶点坐标,直接调用轮廓绘制逻辑即可实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:15:02