我有一个 numpy 数组,它代表一个图像。图像有 3 种颜色:橙色(背景)、蓝色(object1)和绿色(object2)。我使用 3 个值(0、1 和 2)来表示 numpy 数组中的 3 种颜色。两个对象不重叠。
我的问题是:如何知道哪个物体更靠近图像的中心(红点)?(这里,更近是指物体到一个物体图像中心的最近距离小于该物体到另一个物体图像中心的最近距离)
我的代码是这样的:
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
上面的代码可以工作,但速度很慢,而且需要很大的内存(大约 30 GB)。如果您想在您的 PC 中重现我的代码,您可以使用较小的形状而不是 (3200, 1200, 1200)。有没有更有效的方法来实现我的目标?
注意:实际上我的图像是3D CT医学图像,太大无法上传。图像中的对象是随机的,可能是凸的,也可能不是。这就是为什么我的实施速度很慢。这里为了澄清我的问题,我使用2D图像来解释我的方法。