nnunet报错 the direction does not match between the images
报错如下:
the direction does not match between the images
The geometry of the image does not match the geometry of the label file. The pixel arrays will not be aligned and nnU-Net cannot use this data. Please make sure your image modalities are coregistered and have the same geometry as the label
解决方案
找到检查对齐的代码,然后使用这段代码来验证原图和标注,来排除问题。
nnunet/preprocessing/sanity_checks.py
def verify_same_geometry(img_1: sitk.Image, img_2: sitk.Image):
ori1, spacing1, direction1, size1 = img_1.GetOrigin(), img_1.GetSpacing(), img_1.GetDirection(), img_1.GetSize()
ori2, spacing2, direction2, size2 = img_2.GetOrigin(), img_2.GetSpacing(), img_2.GetDirection(), img_2.GetSize()
same_ori = np.all(np.isclose(ori1, ori2))
if not same_ori:
print("the origin does not match between the images:")
print(ori1)
print(ori2)
same_spac = np.all(np.isclose(spacing1, spacing2))
if not same_spac:
print("the spacing does not match between the images")
print(spacing1)
print(spacing2)
same_dir = np.all(np.isclose(direction1, direction2))
if not same_dir:
print("the direction does not match between the images")
print(direction1)
print(direction2)
same_size = np.all(np.isclose(size1, size2))
if not same_size:
print("the size does not match between the images")
print(size1)
print(size2)
if same_ori and same_spac and same_dir and same_size:
return True
else:
return False
我们对原图和标注进行对齐操作就能解决问题
def align_image_direction(img_1: sitk.Image, img_2: sitk.Image):
# 获取图像1的方向
direction1 = img_1.GetDirection()
# 获取图像2的方向
direction2 = img_2.GetDirection()
# 计算图像1到图像2的变换矩阵
transform = sitk.AffineTransform(3)
matrix = np.reshape(direction2, (3, 3)) @ np.linalg.inv(np.reshape(direction1, (3, 3)))
transform.SetMatrix(matrix.ravel())
# 对图像1应用变换矩阵
aligned_img_1 = sitk.Resample(img_1, img_2, transform, sitk.sitkLinear, 0.0, img_1.GetPixelID())
return aligned_img_1