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

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

问题描述

我想生成一个尺寸为200x200的numpy数组,并放入一个以100,100坐标为圆心,半径为80,笔画宽度为3像素的圆圈。如何在不涉及文件操作的情况下在Python 2.7中执行此操作?可能使用几何或图像库来推广到其他形状。 解决方案

开罗是一个现代,灵活和快速的2D图形库。它具有 Python绑定,并允许基于NumPy数组创建曲面:

import numpy
import cairo
import math
data = numpy.zeros((200
表面= cairo.ImageSurface.create_for_data(
数据,cairo.FORMAT_ARGB32,200,200)
cr = cairo.Context(表面)

#用实心白色填充
cr.set_source_rgb(1.0,1.0,1.0)
cr.paint()

#绘制红色圆圈
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()

#写入输出
打印数据[38:48,38:48,0]
surface.write_to_png(circle.png)

此代码打印

  [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:




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

This code prints

[[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]]

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

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

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