如何将简单的几何形状写入 numpy 数组 [英] How to write simple geometric shapes into numpy arrays

查看:19
本文介绍了如何将简单的几何形状写入 numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个大小为 200x200 元素的 numpy 数组,并在其中放入一个以 100,100 坐标为中心、半径为 80 且笔划宽度为 3 像素的圆.如何在不涉及文件操作的情况下在 python 2.7 中执行此操作?可能使用几何或成像库来泛化到其他形状.

I would like to generate a numpy array of 200x200 elements in size and put into it a circle centered into 100,100 coordinates, radius 80 and stroke width of 3 pixels. How to do this in python 2.7 without involving file operations? Possibly using geometry or imaging libraries to allow generalisation to other shapes.

推荐答案

Cairo 是一个现代、灵活和快速的 2D 图形库.它具有 Python 绑定 并允许基于 NumPy 数组创建表面":

Cairo is a modern, flexible and fast 2D graphics library. It has Python bindings and allows creating "surfaces" based on NumPy arrays:

import numpy
import cairo
import math
data = numpy.zeros((200, 200, 4), dtype=numpy.uint8)
surface = cairo.ImageSurface.create_for_data(
    data, cairo.FORMAT_ARGB32, 200, 200)
cr = cairo.Context(surface)

# fill with solid white
cr.set_source_rgb(1.0, 1.0, 1.0)
cr.paint()

# draw red circle
cr.arc(100, 100, 80, 0, 2*math.pi)
cr.set_line_width(3)
cr.set_source_rgb(1.0, 0.0, 0.0)
cr.stroke()

# write output
print data[38:48, 38:48, 0]
surface.write_to_png("circle.png")

此代码打印

[[255 255 255 255 255 255 255 255 132   1]
 [255 255 255 255 255 255 252 101   0   0]
 [255 255 255 255 255 251  89   0   0   0]
 [255 255 255 255 249  80   0   0   0  97]
 [255 255 255 246  70   0   0   0 116 254]
 [255 255 249  75   0   0   0 126 255 255]
 [255 252  85   0   0   0 128 255 255 255]
 [255 103   0   0   0 118 255 255 255 255]
 [135   0   0   0 111 255 255 255 255 255]
 [  1   0   0  97 254 255 255 255 255 255]]

显示圆圈的一些随机片段.它还创建了这个 PNG:

showing some random fragment of the circle. It also creates this PNG:

这篇关于如何将简单的几何形状写入 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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