简体   繁体   中英

Write an array of Dicom images

I have a folder of dicom images and I stored these images in an array and I would like to print them out in a different folder.

I cannot find a method that will write out each of the images like the 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

Method 1: In your case, The answer is ...

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)

Method 2: But, there is better way to process dicom files ...

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)

In above code, the Step 1 is focus on file path processing. It's good for your to porting your code into different environment easily.

The Step 2 is major code which focus on any kind of image processing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM