簡體   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