mys*_*bob 2 python arrays numpy ellipse python-2.7
我有一个方程,它以 x^2/a^2 + y^2/b^2 = 1 的一般形式创建一个椭圆。我希望生成一个数组,其中椭圆内的所有点都设置为一个,而椭圆外的所有点都设置为是零。然后将该数组与另一个数组进行卷积。
到目前为止,我已经尝试创建一个大小为我想要遍历所有 x,y 位置的空数组,计算 x^2/a^2 + y^2/b^2 = 1。如果一般形式小于 1在数组中输入一个,否则继续下一个 x,y 位置。
这是我的代码:
arr = numpy.array(im)
sh = numpy.shape(arr)
ar = numpy.empty(sh)
for x in range (sh[0]):
xx = x*x
for y in range (sh[1]):
yy = y*y
ellips = xx/(a*a)+yy/(b*b)
if ellips < 1:
ar[xx,yy] = '1'
else:
break
Run Code Online (Sandbox Code Playgroud)
但是,这不会产生我期望的结果,因为我的椭圆总是以 (0,0) 为中心,因此我希望这些椭圆位于数组的中心,但它们出现在左上角。
有没有人知道我哪里出错了?或者也许是生成数组的更好方法?
- -编辑 - -
尝试过 EOL 的答案后,我收到了一个椭圆数组,但是它与它应该建模的椭圆不匹配。这是一张图片来说明我的意思:http : //i.imgur.com/M4vh4il.jpg ?1 椭圆数组没有椭圆的旋转。产生椭圆和椭圆数组的代码如下:
def Ellipssee(z,stigx,stigy):
points=100 #Number of points to construct the ellipse
x0,y0 = 0,0 #Beam is always centred
z0 = 4 # z0 a constant of the device
al = 2 # alpha a constant of the device
de = sqrt((stigx**2 + stigy**2))
ang = arctan2(stigy, stigx) # result in radians
a = (z+de-z0)*al
b = (z-de-z0)*al
cos_a,sin_a=cos(ang),sin(ang)
the=linspace(0,2*pi,points)
X=a*cos(the)*cos_a-sin_a*b*sin(the)+x0
Y=a*cos(the)*sin_a+cos_a*b*sin(the)+y0
img = Image.open("bug.png").convert("L") # load image for array size
arr = np.array(img)
sh = np.shape(arr)
nx = sh[0] # number of pixels in x-dir
ny = sh[1] # number of pixels in y-dir
x0 = 0; # x center, half width
y0 = 0; # y center, half height
x = np.linspace(-60, 60, nx) # x values of interest
y = np.linspace(-30, 30, ny) # y values of interest
ellipseArr = ((x-x0)/a)**2 + ((y[:,None]-y0)/b)**2 <= 1
Run Code Online (Sandbox Code Playgroud)
我一直在用 values 调用方法Ellipse(1,6,8)。
为什么在创建数组时会丢失旋转?
NumPy 可以直接执行此操作,无需 Python 循环:
>>> import numpy as np
>>> from matplotlib import pyplot
>>> x0 = 4; a = 5 # x center, half width
>>> y0 = 2; b = 3 # y center, half height
>>> x = np.linspace(-10, 10, 100) # x values of interest
>>> y = np.linspace(-5, 5, 100)[:,None] # y values of interest, as a "column" array
>>> ellipse = ((x-x0)/a)**2 + ((y-y0)/b)**2 <= 1 # True for points inside the ellipse
>>> pyplot.imshow(ellipse, extent=(x[0], x[-1], y[0], y[-1]), origin="lower") # Plot
Run Code Online (Sandbox Code Playgroud)

这种技术的几个关键点是:
平方(在 x 和 y 中)只计算一次(而不是单独计算每个点)。这比使用numpy.meshgrid().
由于 NumPy 的广播规则,x 和 y 的贡献以一种简单的方式相加(y[:,None]本质上是使y 值y的列向量,同时x仍然是行向量)。也不需要更大的 2D 中间数组,因为numpy.meshgrid().
NumPy 可以做到“在椭圆中?” 直接测试(这就是<= 1部分),没有 Python 循环。
现在,如果您只能使用整数坐标,x并且y可以简单地使用np.arange()而不是更“精致”的np.linspace().
虽然ellipse是一个布尔数组(椭圆内/外),但 False 在计算中被视为 0 和 True 像 1 一样(例如ellipse*10产生 0 和 10 值的数组),因此您可以在 NumPy 计算中使用它。
| 归档时间: |
|
| 查看次数: |
4722 次 |
| 最近记录: |