繁体   English   中英

根据索引分配值的最快方法

[英]Fastest way to assign values based on their index

如果没有循环,最快的方法是什么?

这段代码在行的每一侧创建了一个具有单独值的行。

def get_image(img_size = (500,500),angle=90) :
    angle = angle*np.pi/180
    img = np.zeros(img_size)
    center = np.array(img_size)/2

    for x in range(img_size[0]):
        for y in range(img_size[1]):
            cord = np.array((x,y))
            true_cord = cord - center
            x1,y1 = true_cord
            if y1 > np.tan(angle)*x1 :
                img[x,y] = 1

    return img

您可以使用np.mgrid

import numpy as np
import matplotlib.pyplot as plt

def get_image(img_size=(500,500), angle=90):
    r, c = np.array(img_size)/2
    x1, y1 = np.mgrid[-r:r, -c:c]
    return y1 > np.tan(np.radians(angle)) * x1


plt.imshow(get_image((123,123), 23))
plt.axis('off')
plt.show()

Output

旋转线

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM