import SimpleITK as sitk
import os
import argparse
from pathlib import Path
import nibabel as nib
import numpy as np
sitk_maskimg = sitk.ReadImage("test.nii", sitk.sitkUInt8)
array1 = sitk.GetArrayFromImage(sitk_maskimg)
cc = sitk.ConnectedComponent(sitk_maskimg)
stats = sitk.LabelIntensityStatisticsImageFilter()
stats.Execute(cc, sitk_maskimg)
maxlabel = 0 # 获取最大连通域的索引
maxsize = 0 # 获取最大连通域的体素大小
# 遍历每一个连通域, 获取最大连通域的体素大小和索引
for l in stats.GetLabels():
size = stats.GetPhysicalSize(l)
if maxsize < size:
maxlabel = l
maxsize = size
labelmaskimage = sitk.GetArrayFromImage(cc)
outmask = labelmaskimage.copy()
outmask[labelmaskimage != maxlabel] = 0
outmask[labelmaskimage == maxlabel] = 1
# 找到不重合的位置
non_overlapping_mask = np.logical_not(np.logical_and(array1!= 0, outmask!= 0))
# 将不重合的位置置为 0
array1[non_overlapping_mask] = 0
modified_image1 = sitk.GetImageFromArray(array1)
outmask = outmask.astype('float32')
modified_image1.SetDirection(sitk_maskimg.GetDirection())
modified_image1.SetSpacing(sitk_maskimg.GetSpacing())
modified_image1.SetOrigin(sitk_maskimg.GetOrigin())
# 保存修改后的图像
sitk.WriteImage(modified_image1, "Stage2LungVessels1.nii")