John
John

Reputation: 855

How to calculate center point of box of grid which is near to point x,y?

How to calculate center point of each grid box which is closest to the point x,y. Here is the code for generating grid.I want to save all the center points in a list centers and then find closest center point. here is the code.

from PIL import Image, ImageDraw

if __name__ == '__main__':
    height = 600
    width = 600
    centers=[]
    image = Image.new(mode='L', size=(height, width), color=255)

    # Draw some lines
    draw = ImageDraw.Draw(image)
    y_start = 0
    y_end = image.height
    step_size = int(image.width / 10)

    for x in range(0, image.width, step_size):
        line = ((x, y_start), (x, y_end))
        draw.line(line, fill=128)

    x_start = 0
    x_end = image.width

    for y in range(0, image.height, step_size):
        line = ((x_start, y), (x_end, y))
        draw.line(line, fill=128)

    del draw

    image.show()

I found centroids like this

for x in range(0, image.width, step_size):
        for y in range(0, image.height, step_size):
            centers.append([(x+(x+step_size))/2,(y+(y+step_size))/2])

How to find a centroid which is near to (x,y) point which is obtained on mouse click?

Upvotes: 1

Views: 1370

Answers (2)

T. Ray
T. Ray

Reputation: 641

The same question about Euclidean distance was asked here. In your case, that would look like this:

def closest_node(node, nodes):
    nodes = np.asarray(nodes)
    dist = np.sum((nodes - node)**2, axis=1)
    return np.argmin(dist)

mouse_xy = (20, 20)
closest_centroid = centers[closest_node(mouse_xy, centers)]

print(closest_centroid)

[30, 30]

Upvotes: 1

Alexander Freyr
Alexander Freyr

Reputation: 918

Someone could definitely improve on this but you can use the min function built in for python. I threw this together:

# Simulated mouse click
x_click = 542
y_click = 253

find_closest_x = min(centers, key=lambda x_center: abs(x_click - x_center[0]))
find_closest_y = min(centers, key=lambda y_center: abs(y_click - y_center[1]))
closest = find_closest_x[0], find_closest_y[1]
print(closest)

Although a little bit whacky, this find the closest values for x and y in the list centers

Upvotes: 1

Related Questions