Fastest way to assign values based on their index

Viewed 65

What would be the fastest way to do something like this without the loops?

The piece of code creates a line with separate value on each side of the line.

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
1 Answers

You can use 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

rotated line

Related