我有DICOM图像中的数据,我想将DICOM图像转换为png或jpg格式。但是,我需要使用for循环一次转换多个文件夹中的图像。下面是我到目前为止所做的:
import pydicom as dicom
import cv2
# specify your image path
image_path = 'Data/LungSegmentation/NSCLC-Radiomics/LUNG1-001/09-18-2008-StudyID-69331/0.000000-82046/1-001.dcm'
ds = dicom.dcmread(image_path)
pixel_array_numpy = ds.pixel_array
image_format = '.jpg' # or '.png'
image_path = image_path.replace('.dcm', image_format)
cv2.imwrite(image_path, pixel_array_numpy)
#show image.....
plt.imshow(ds.pixel_array,cmap ='gray',vmin=0,vmax=255)
使用python模块(如glob
)遍历文件和文件夹。只是一个小例子:
import glob
folders = glob.glob("PATH_CONTAINING_YOUR_FOLDERS")
for folder in folders:
files = glob.glob(folder+'*.dcm') # pick only dicom files
for file in files:
DO_YOUR_STUFF_HERE(file)
我已经构建了一个将dicom文件转换为jpg/png/bmp的包,您只需pip install dicom2jpg
然后使用
import dicom2jpg
dicom_dir = "/Users/user/Desktop/dir_a"
export_location = "/Users/user/Desktop/dir_b"
# convert all DICOM files in dicom_dir folder to jpg format
dicom2jpg.dicom2jpg(dicom_dir, export_location)
# convert all DICOM files in dicom_dir folder to png format
dicom2jpg.dicom2png(dicom_dir, export_location)
希望能有所帮助