绘制2D numpy的数组中的矩形 [英] Drawing a rectangle inside a 2D numpy array

查看:1017
本文介绍了绘制2D numpy的数组中的矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有从传感器的每个像素含有的各个数据的2D numpy的阵列。的图像与从照相机活饲料中显示的GUI。我希望能够绘制在图像的矩形,以便区分在屏幕的一个区域。它似乎pretty简单绘制一个矩形平行于图像的一边,但我最终想要能够旋转矩形。我如何知道哪些像素时,旋转的矩形覆盖?

I have a 2D numpy array containing the individual data from each pixel of a sensor. The image is displayed in a GUI with a live feed from the camera. I want to be able to draw a rectangle over the image in order to distinguish an area of the screen. It seems pretty simple to draw a rectangle which is parallel to the side of the image but I eventually want to be able to rotate the rectangle. How will I know which pixels the rectangle covers when it is rotated?

推荐答案

您可以使用Python图像库,如果你不介意的依赖。给定一个2D numpy的阵列数据,和多边形坐标的数组(带形状(N,2)),这将绘制在数组中填充值为0的多边形:

You can use the Python Imaging Library, if you don't mind the dependency. Given a 2D numpy array data, and an array poly of polygon coordinates (with shape (n, 2)), this will draw a polygon filled with the value 0 in the array:

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()

本脚本生成此图:

这篇关于绘制2D numpy的数组中的矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆