将 JPG 或 PNG 图像转换为 Dicom

您所在的位置:网站首页 jpeg转化成png 将 JPG 或 PNG 图像转换为 Dicom

将 JPG 或 PNG 图像转换为 Dicom

2023-06-15 03:43| 来源: 网络整理| 查看: 265

如果您想将普通图像(如 JPG 或 PNG)转换为医学图像(谈论 Dicom 文件),您只需要安装一个名为“pydicom”的库来操作 Dicom 图像,然后您需要一个预先存在的 Dicom 图像。

因为我们都知道 Dicom 图像或者文件包含的不仅仅是普通图片,比如像素等,Dicom 图像包含我们称之为“像素阵列”的像素信息、患者信息等等。所以在我们的例子中,我们只需要转换像素数组的像素值。为此,我们需要获取现有的 Dicom 图像并获取其旧信息来创建新的。

所以第一步是安装 pydicom 库、pillow 和 numpy。

pip install pydicom pip install numpy pip install pillow

完成后,我们就可以启动主程序了。为此,我们有 3 个步骤:

打开图像、jpg 或 png 以及现有的 Dicom。如果 jpg 或 png 图像在灰度空间中。如果 jpg 或 png 图像在 RGB 空间中 1.打开图像

要打开图像,对于 jpg 或 png 图像,我们将使用Pillow,对于 Dicom,我们将使用 pydicom。以下是执行此操作的行:

ds = pydicom.dcmread(‘path’) # pre-existing dicom file jpg_image = Image.open(‘path’) # the PNG or JPG file to be replace 2如果JPG图像是灰度图像

如果您不知道图像是灰度还是 RGB,您可以通过“模式函数”进行检查,如果返回“L”则表示图像是灰度图,如果返回“RGBA”则表示图像是RGB 图像。

所以我们需要初始化图像,或者我们可以说使用 NumPy 的数组,然后我们需要为数组提供与 JPG 图像相同的尺寸,这样我们就不会丢失信息,之后我们应该指定我们将创建的图像是灰度图像,当然我们需要添加更多参数来指定图像的正确类型。我们应该知道,这个数组将替换第一个 Dicom 图像上存在的数组。

if jpg_image.mode == 'L': np_image = np.array(jpg_image.getdata(),dtype=np.uint8) ds.Rows = jpg_image.height ds.Columns = jpg_image.width ds.PhotometricInterpretation = "MONOCHROME1" ds.SamplesPerPixel = 1 ds.BitsStored = 8 ds.BitsAllocated = 8 ds.HighBit = 7 ds.PixelRepresentation = 0 ds.PixelData = np_image.tobytes() ds.save_as('result_gray.dcm') 3.如果 JPG 图像是 RGB

实际上,我们将执行与灰度图像相同的步骤,只是我们将创建的数组将有 3 个通道而不是 1,“PhotometricInterpretation”将是 RGB 而不是单色,每个像素的通道数是 3而不是 1。

if jpg_image.mode == 'RGBA': np_image = np.array(jpg_image.getdata(), dtype=np.uint8)[:,:3] ds.Rows = jpg_image.height ds.Columns = jpg_image.width ds.PhotometricInterpretation = "RGB" ds.SamplesPerPixel = 3 ds.BitsStored = 8 ds.BitsAllocated = 8 ds.HighBit = 7 ds.PixelRepresentation = 0 ds.PixelData = np_image.tobytes() ds.save_as('result_rgb.dcm') 4.完整代码 import numpy as np import pydicom from PIL import Image ds = pydicom.dcmread('path') # pre-existing dicom file jpg_image = Image.open('path') # the PNG or JPG file to be replace if jpg_image.mode == 'L': np_image = np.array(jpg_image.getdata(),dtype=np.uint8) ds.Rows = jpg_image.height ds.Columns = jpg_image.width ds.PhotometricInterpretation = "MONOCHROME1" ds.SamplesPerPixel = 1 ds.BitsStored = 8 ds.BitsAllocated = 8 ds.HighBit = 7 ds.PixelRepresentation = 0 ds.PixelData = np_image.tobytes() ds.save_as('result_gray.dcm') elif jpg_image.mode == 'RGBA': np_image = np.array(jpg_image.getdata(), dtype=np.uint8)[:,:3] ds.Rows = jpg_image.height ds.Columns = jpg_image.width ds.PhotometricInterpretation = "RGB" ds.SamplesPerPixel = 3 ds.BitsStored = 8 ds.BitsAllocated = 8 ds.HighBit = 7 ds.PixelRepresentation = 0 ds.PixelData = np_image.tobytes() ds.save_as('result_rgb.dcm') 参考目录

https://pycad.co/convert-jpg-or-png-images-into-dicom/



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3