Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a 2D Numpy array based on given coordinates

I want to fill a 2D numpy array created by this:

import numpy as np

arr = np.full((10,10),0)

Example coordinates:

enter image description here

How can I fill those selected elements with data even if the coordinates is switched from 2,1:2,5 to 2,5:2,1 or from 5,1:8,1 to 8,1:5,1

If I want to fill data on 2,1 : 2,5,2,1 2,2 2,3 2,4 2,5 will be filled. Also same as 5,1 : 5,8

like image 986
JFetz2191 Avatar asked Nov 20 '25 11:11

JFetz2191


1 Answers

Here's one way of doing it:

import numpy as np

coords = ['2,1:2,5', '8,6:4,6', '5,1:8,1']
arr = np.full((10, 10), 0)

for coord in coords:
    start, stop = map(lambda x: x.split(','), coord.split(':'))
    (x0, y0), (x1, y1) = sorted([start, stop])
    arr[int(y0):int(y1)+1, int(x0):int(x1)+1] = 1

Which results in arr looking like:

array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 1, 1, 1, 1, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
like image 69
Matt Hall Avatar answered Nov 21 '25 23:11

Matt Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!