I want to batch import matrices into nrrd. I added a new keys to the header, but it still cannot work.
mhd_path = path + f'\{name}\Segmentation_1_T1_lumen.mhd'
sitk_image = sitk.ReadImage(mhd_path)
mask = sitk.GetArrayFromImage((sitk_image))
mask = np.transpose(mask, (2, 1, 0))
input_filename = path + f'\{name}\Segmentation_english.seg.nrrd'
output_filename = path + f'\{name}\Segmentation_new.seg.nrrd'
voxels, header = nrrd.read(input_filename)
print(voxels.shape,mask.shape)
new_voxels = np.concatenate((mask[np.newaxis, :, :, :], voxels), axis=0)
header["Segment9_Color"] = "0.694118 0.478431 0.396078"
header["Segment9_ColorAutoGenerated"] = "1"
header["Segment9_Extent"] = "125 303 176 216 52 81"
header["Segment9_ID"] = "Segment_9"
header["Segment9_LabelValue"] = "1"
header["Segment9_Layer"] = "2"
header["Segment9_Name"] = "lumen"
header["Segment9_NameAutoGenerated"] = "0"
header["Segment9_Tags"] = header["Segment1_Tags"]
print(new_voxels.shape)
print(header.keys())
# print(header)
nrrd.write(output_filename, new_voxels, header)
voxels, header = nrrd.read(input_filename)
print(voxels.shape,mask.shape)
new_voxels = np.concatenate((mask[np.newaxis, :, :, :], voxels), axis=0)
pattern = re.compile(r'^Segment(.*)_Color')
new_header = {}
max_num = -1
for key in header.keys():
match = pattern.match(key)
if match:
num = int(match.group(1))
max_num = max(max_num, num)
for key, value in header.items():
new_header[key] = value
if key == f"Segment{max_num}_Tags":
new_header[f"Segment{max_num+1}_Color"] = "0.694118 0.478431 0.396078"
new_header[f"Segment{max_num+1}_ColorAutoGenerated"] = "1"
new_header[f"Segment{max_num+1}_Extent"] = "125 303 176 216 52 81"
new_header[f"Segment{max_num+1}_ID"] = f"Segment_{max_num}"
new_header[f"Segment{max_num+1}_LabelValue"] = "1"
new_header[f"Segment{max_num+1}_Layer"] = str(new_voxels.shape[0]-1)
new_header[f"Segment{max_num+1}_Name"] = "lumen"
new_header[f"Segment{max_num+1}_NameAutoGenerated"] = "0"
new_header[f"Segment{max_num+1}_Tags"] = header["Segment1_Tags"]
print(new_voxels.shape)
print(new_header.keys())
# print(header)
nrrd.write(output_filename, new_voxels, new_header)
segmentation_info = slicerio.read_segmentation_info(output_filename)
number_of_segments = len(segmentation_info["segments"])
print(f"Number of segments: {number_of_segments}")
segment_names = slicerio.segment_names(segmentation_info)
print(f"Segment names: {', '.join(segment_names)}")
spacing = [abs(header['space directions'][i+1][i]) for i in range(3)]
assert False