画像を表すnumpy配列があります。画像には、オレンジ (背景)、青 (object1)、緑 (object2) の 3 色があります。3 つの値 (0、1、2) を使用して、numpy 配列の 3 つの色を示します。2 つのオブジェクトが重なっていません。
私の質問は次のとおりです。どのオブジェクトが画像の中心 (赤い点) に近いかを知るにはどうすればよいですか? (ここで、より近いとは、オブジェクトから 1 つのオブジェクトの画像の中心までの最も近い距離が、オブジェクトから他のオブジェクトの画像の中心までの最も近い距離よりも小さいことを意味します)
私のコードは次のようなものです:
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 画像を使用して私の方法を説明します。