0

I have a numpy meshgrid that outlines boxes on my image. I want to find the midpoint of each "box" and plot a point. I am doing that manually like this:

xg = np.linspace(0, (x1 - x0), inputx + 1)
yg = np.linspace(0, (y2 - y1), inputy + 1)
xgr, ygr = np.meshgrid(xg, yg)

xpnt, ypnt = ((xgr[1][1] - xgr[0][0]) // 2 + xgr[0][0], (ygr[1][1] - ygr[0][0]) // 2 + ygr[0][0])
circle = plt.Circle((xpnt, ypnt), 5, color='r')
a.add_patch(circle)

This would require me to go through each point and make x,y values for each midpoint. Is there a faster way to do this? I will show the image output of just the one midpoint circle. blue circles are made with values from my meshgrid

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • 1
    You could make a new `meshgrid` with `x` that starts at `xpt`, and has `input` values, etc. Or `((xgr[1][,1] - xgr[0,0]) // 2 + xgr[0,0]` can be generalized to `xgr[1:,1:] - xgr[:-1,:-1]//2 + xgr[:-1,:-1]` – hpaulj Apr 21 '23 at 01:43

1 Answers1

1

Make a mesh same size as yours, but with simpler numbers:

In [1]: input = 5; 
In [2]: x1 = np.linspace(0,1,input+1)
In [3]: x1
Out[3]: array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])
In [5]: I,J = np.meshgrid(x1,x1,indexing='ij')    
In [6]: I,J
Out[6]: 
(array([[0. , 0. , 0. , 0. , 0. , 0. ],
        [0.2, 0.2, 0.2, 0.2, 0.2, 0.2],
        [0.4, 0.4, 0.4, 0.4, 0.4, 0.4],
        [0.6, 0.6, 0.6, 0.6, 0.6, 0.6],
        [0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
        [1. , 1. , 1. , 1. , 1. , 1. ]]),
 array([[0. , 0.2, 0.4, 0.6, 0.8, 1. ],
        [0. , 0.2, 0.4, 0.6, 0.8, 1. ],
        [0. , 0.2, 0.4, 0.6, 0.8, 1. ],
        [0. , 0.2, 0.4, 0.6, 0.8, 1. ],
        [0. , 0.2, 0.4, 0.6, 0.8, 1. ],
        [0. , 0.2, 0.4, 0.6, 0.8, 1. ]]))

We could make a new mesh with one less point in each direction:

In [7]: x2 = np.linspace(.1,.9,input)    
In [8]: x2
Out[8]: array([0.1, 0.3, 0.5, 0.7, 0.9])

In [10]: np.meshgrid(x2,x2,indexing='ij')
Out[10]: 
[array([[0.1, 0.1, 0.1, 0.1, 0.1],
        [0.3, 0.3, 0.3, 0.3, 0.3],
        [0.5, 0.5, 0.5, 0.5, 0.5],
        [0.7, 0.7, 0.7, 0.7, 0.7],
        [0.9, 0.9, 0.9, 0.9, 0.9]]),
 array([[0.1, 0.3, 0.5, 0.7, 0.9],
        [0.1, 0.3, 0.5, 0.7, 0.9],
        [0.1, 0.3, 0.5, 0.7, 0.9],
        [0.1, 0.3, 0.5, 0.7, 0.9],
        [0.1, 0.3, 0.5, 0.7, 0.9]])]

Alternatively we could average points in the original mesh:

In [11]: (I[1:,1:]+I[:-1,:-1])/2
Out[11]: 
array([[0.1, 0.1, 0.1, 0.1, 0.1],
       [0.3, 0.3, 0.3, 0.3, 0.3],
       [0.5, 0.5, 0.5, 0.5, 0.5],
       [0.7, 0.7, 0.7, 0.7, 0.7],
       [0.9, 0.9, 0.9, 0.9, 0.9]])

In [12]: (J[1:,1:]+J[:-1,:-1])/2
Out[12]: 
array([[0.1, 0.3, 0.5, 0.7, 0.9],
       [0.1, 0.3, 0.5, 0.7, 0.9],
       [0.1, 0.3, 0.5, 0.7, 0.9],
       [0.1, 0.3, 0.5, 0.7, 0.9],
       [0.1, 0.3, 0.5, 0.7, 0.9]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353