【问题标题】:Drawing a rectangle inside a 2D numpy array在 2D numpy 数组中绘制一个矩形
【发布时间】:2012-09-20 06:23:57
【问题描述】:

我有一个 2D numpy 数组,其中包含来自传感器每个像素的单独数据。图像显示在 GUI 中,并带有来自摄像机的实时馈送。我希望能够在图像上绘制一个矩形以区分屏幕区域。绘制一个与图像侧面平行的矩形似乎很简单,但我最终希望能够旋转矩形。我如何知道矩形在旋转时覆盖了哪些像素?

【问题讨论】:

  • 我认为使用 Gtk.DrawingArea() 代替 numpy 数组可能更容易?

标签: arrays numpy draw shape


【解决方案1】:

如果您不介意依赖关系,您可以使用 Python Imaging Library。给定一个二维 numpy 数组 data 和一个多边形坐标数组 poly(形状为 (n, 2)),这将绘制一个填充了数组中值 0 的多边形:

img = Image.fromarray(data)
draw = ImageDraw.Draw(img)
draw.polygon([tuple(p) for p in poly], fill=0)
new_data = np.asarray(img)

这是一个独立的演示:

import numpy as np
import matplotlib.pyplot as plt

# Python Imaging Library imports
import Image
import ImageDraw


def get_rect(x, y, width, height, angle):
    rect = np.array([(0, 0), (width, 0), (width, height), (0, height), (0, 0)])
    theta = (np.pi / 180.0) * angle
    R = np.array([[np.cos(theta), -np.sin(theta)],
                  [np.sin(theta), np.cos(theta)]])
    offset = np.array([x, y])
    transformed_rect = np.dot(rect, R) + offset
    return transformed_rect


def get_data():
    """Make an array for the demonstration."""
    X, Y = np.meshgrid(np.linspace(0, np.pi, 512), np.linspace(0, 2, 512))
    z = (np.sin(X) + np.cos(Y)) ** 2 + 0.25
    data = (255 * (z / z.max())).astype(int)
    return data


if __name__ == "__main__":
    data = get_data()

    # Convert the numpy array to an Image object.
    img = Image.fromarray(data)

    # Draw a rotated rectangle on the image.
    draw = ImageDraw.Draw(img)
    rect = get_rect(x=120, y=80, width=100, height=40, angle=30.0)
    draw.polygon([tuple(p) for p in rect], fill=0)
    # Convert the Image data to a numpy array.
    new_data = np.asarray(img)

    # Display the result using matplotlib.  (`img.show()` could also be used.)
    plt.imshow(new_data, cmap=plt.cm.gray)
    plt.show()

此脚本生成此图:

【讨论】:

    猜你喜欢
    • 2013-09-03
    • 1970-01-01
    • 2021-03-08
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 2013-06-30
    相关资源
    最近更新 更多