【问题标题】:Write an array of Dicom images编写一组 Dicom 图像
【发布时间】:2019-07-08 19:49:23
【问题描述】:

我有一个 dicom 图像文件夹,我将这些图像存储在一个数组中,我想将它们打印到另一个文件夹中。

我找不到像 cv2.imwrite 那样写出每个图像的方法

import pydicom
import skimage, os
import numpy as np
FolderPathName = r'FolderPathName'
slices = [pydicom.read_file(FolderPathName + imagename) for imagename in os.listdir(FolderPathName)]
    # Sort the dicom slices in their respective order
slices.sort(key=lambda x: int(x.InstanceNumber))

for x in range(len(slices)): 
    #write the images in a new folder

【问题讨论】:

  • 您想再次保存图像吗?作为DICOM?使用不同的文件名?
  • 基本上,问题是文件被乱序命名,所以我使用排序方法: slices.sort(key=lambda x: int(x.InstanceNumber)) ,以正确组织它们数组切片,然后我将按顺序重命名它们

标签: python pydicom


【解决方案1】:

方法一: 在你的情况下, 答案是……

import pydicom
import skimage, os
import numpy as np
FolderPathName = r'FolderPathName'
slices = [pydicom.read_file(FolderPathName + imagename) for imagename in os.listdir(FolderPathName)]
# Sort the dicom slices in their respective order
slices.sort(key=lambda x: int(x.InstanceNumber))
jpg_folder = '' # Set your jpg folder
for idx in range(len(slices)): 
    #write the images in a new folder
    jpg_filepath = os.path.join( jpg_folder, "pic-{}.jpg".format(idx) )
    np_pixel_array = slices[idx].pixel_array
    cv2.imwrite(jpg_filepath, np_pixel_array)

方法二: 但是,有更好的方法来处理 dicom 文件...

import pydicom
import os
import numpy as np
import cv2
dicom_folder = '' # Set the folder of your dicom files that inclued images 
jpg_folder = '' # Set the folder of your output folder for jpg files 
# Step 1. prepare your input(.dcm) and output(.jpg) filepath 
dcm_jpg_map = {}
for dicom_f in os.listdir(dicom_folder):
    dicom_filepath = os.path.join(dicom_folder, dicom_f)
    jpg_f = dicom_f.replace('.dcm', '.jpg') 
    jpg_filepath = os.path.join(jpg_folder,jpg_f)
    dcm_jpg_map[dicom_filepath] = jpg_filepath

# Now, dcm_jpg_map is key,value pair of input dcm filepath and output jpg filepath

# Step 2. process your image by input/output information
for dicom_filepath, jpg_filepath in dcm_jpg_map.items():
    # convert dicom file into jpg file
    dicom = pydicom.read_file(dicom_filepath)
    np_pixel_array = dicom.pixel_array
    cv2.imwrite(jpg_filepath, np_pixel_array)

在上面的代码中, 第 1 步 专注于文件路径处理。方便您将代码移植到不同的环境中。

第 2 步 是主要代码,专注于任何类型的图像处理。

【讨论】:

  • 我刚刚得到 ---> 11 jpg_filepath = os.path.join( jpg_folder, "pic-{}.jpg".format(x) ) 12 np_pixel_array = slices[idx].pixel_array 13 cv2.imwrite(jpg_filepath, np_pixel_array) NameError: name 'x' is not defined using your first example
  • @user3078100 感谢您的反馈。这很有帮助。我已将其从 format(x) 更改为 format(idx)。
猜你喜欢
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多