How to write simple geometric shapes into numpy arrays(如何将简单的几何形状写入 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 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将简单的几何形状写入 numpy 数组


- 计算测试数量的Python单元测试 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01