[Python] In Python numpy array, how to know which object is nearer to one point in one image?

Discussão em 'Python' iniciado por Stack, Agosto 17, 2025.

  1. Stack

    Stack Membro Participativo

    I have a numpy array, which represents an image. The image has 3 colors: orange (background), blue (object1) and green (object2). I use 3 values (0, 1 and 2) to indicate the 3 colors in numpy array. Two objects are not overlapped.

    My question is: how do know which object is nearer to the center (red point) of the image? (Here, nearer means the nearest distance from the object to the center of the image of one object is smaller than the nearest distance from the object to the center of the image of the other object)

    My code is like this:

    import numpy as np
    from scipy import spatial
    import time

    sub_image1 = np.ones((30, 30, 30))
    sub_image2 = np.ones((20, 10, 15))

    # pad the two sub_images to same shape (1200, 1200, 1200) to simulate my 3D medical data
    img_1 = np.pad(sub_image1, ((1100, 70), (1100, 70), (1100, 70)))
    img_2 = np.pad(sub_image1, ((1100, 80), (1130, 60), (1170, 15)))

    def nerest_dis_to_center(img):
    position = np.where(img > 0)
    coordinates = np.transpose(np.array(position)) # get the coordinates where the voxels is not 0
    cposition = np.array(img.shape) / 2 # center point position/coordinate
    distance, index = spatial.KDTree(coordinates).query(cposition)
    return distance

    t1 = time.time()
    d1 = nerest_dis_to_center(img_1)
    d2 = nerest_dis_to_center(img_2)

    if d1 > d2:
    print("img2 object is nearer")
    elif d2 > d1:
    print("img1 object is nearer")
    else:
    print("They are the same far")
    t2 = time.time()
    print("used time: ", t2-t1)
    # 30 seconds


    The above code works, but slowly and it requires very large amount of memory (about 30 GB). If you want to reproduce my code in your PC, you can use a smaller shape instead of (3200, 1200, 1200). Is there any more efficient way to achieve my goal?

    Note: actually my image is a 3D CT medical image, it is too big to be uploaded. The objects in the image is random, may be convex or not. That is why my implementation is far slowly. Here in order to clarify my question, I use the 2D image to explain my method.

    [​IMG]

    Continue reading...

Compartilhe esta Página