Home > Back-end >  Creating grid of points on an image, but the index is out of range though it isn't, why?
Creating grid of points on an image, but the index is out of range though it isn't, why?

Time:03-08

I'm creating an array that has 255 as grid value, of an image of size 75x115, with the code below:

xn = 13 #grid line num
yn = 7 #grid line num
im = np.zeros((75, 115))
H, W = im.shape

step_x =  (W/(xn-1))
step_y =  (H/(yn-1))
xvalues = np.arange(0, W   step_x, step_x)
yvalues = np.arange(0, H   step_y, step_y)

xx, yy = np.meshgrid(xvalues, yvalues)

positions = np.column_stack([xx.ravel(), yy.ravel()]).astype(int)

for (x,y) in (positions):
    im[y, x] = 255

The error said that

index 115 is out of bounds for axis 1 with size 115

If I were to change the ranges to:

xvalues = np.arange(0, W, step_x)
yvalues = np.arange(0, H, step_y)

this will be the generated image, but it's not what I intended to do, where it only generated 12x6 grid lines, not 13x7. The 13x7 grid lines shall include the start and the end pixel range (0-75, 0-115), so that the image is fully covered in grid equally.

enter image description here

Any idea how to fix this?

CodePudding user response:

If you want almost equally spaced grid points, you can do

xvalues = np.linspace(0, im.shape[1]-1, xn, dtype='int')

and similar for yvalues. However, since 13 does not divide 115 equally, you will not be able to have fully equal spacings with your choice of array size and grid spacing.

This is also seen if we print xvalues.

print(xvalues)
>> [  0.           9.58333333  19.16666667  28.75        38.33333333
  47.91666667  57.5         67.08333333  76.66666667  86.25
  95.83333333 105.41666667]

These points will be plotted at [0, 9, 19, 28, 38, 47, 57, 67, 76, 86, 95, 105], so sometimes with a difference of 10 and sometimes with a difference of 9.

CodePudding user response:

Meshgrids can be useful in any application where we need to construct a well-defined 2D or even multi-dimensional space, xvalues and yvalues are supposed to be your grid indexes value, this means that they could not exceed the dimensions of the image im, I would recommend you to take a look at Gris Plot

  • Related