确保在执行此代码之前,已经安装了pydicom
和numpy
库。这段代码仅做为示例,实际使用时需要根据具体的DICOM图像进行适当的调整,例如检查图像尺寸是否匹配,处理图像之间的差异等。
import pydicom
import numpy as np
# 加载第一个DICOM文件
ds1 = pydicom.dcmread("image1.dcm")
img1 = ds1.pixel_array
# 加载第二个DICOM文件
ds2 = pydicom.dcmread("image2.dcm")
img2 = ds2.pixel_array
# 确保图像具有相同的像素深度
if img1.dtype == img2.dtype:
# 在水平方向上拼接图像
#img_horiz = np.hstack((img1, img2))
# 在垂直方向上拼接图像
img_horiz = np.vstack((img1, img2))
# 创建一个新的Dataset并设置拼接后的图像数据
ds_horiz = pydicom.Dataset(ds1)
ds_horiz.PixelData = img_horiz.tobytes()
ds_horiz.Rows = img_horiz.shape[0]
ds_horiz.Columns = img_horiz.shape[1]
# 保存拼接后的DICOM文件
ds_horiz.is_little_endian = True
ds_horiz.is_implicit_VR = True
pydicom.dcmwrite("image_horiz.dcm", ds_horiz)
else:
print("Error: Images have different pixel depths.")