如何使用python读取和显示dicom图像。我是python和IT领域的新手。请一些人简要介绍一下dicom图像处理所需的包和库以及打开dicom图像的代码。
答案 0 :(得分:3)
如果您只想预览dicom图像而不提取任何信息,请使用以下代码。您需要安装pydicom python软件包,可以使用pip install pydicom
-
import pydicom as dicom
import matplotlib.pylab as plt
# specify your image path
image_path = 'data/train_images/sample.dcm'
ds = dicom.dcmread(image_path)
plt.imshow(ds.pixel_array)
如果您要将图像转换为png / jpg,则可以执行以下操作-
import pydicom as dicom
import cv2
# specify your image path
image_path = 'data/train_images/sample.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)
答案 1 :(得分:1)
如果您正在使用Windows,我建议您安装Anaconda以使用python。它有大多数库和包。
我建议您先安装以下库:
1)pydicom(对于python版本> 3.0) 链接:https://anaconda.org/conda-forge/pydicom 2)Matplotlib(如果不在anaconda工作) 3)Numpy(如果不在anaconda工作)
以下代码应显示您的图片:
import numpy as np
import matplotlib.pyplot as plt
import os, glob
import pydicom
import pylab as pl
import sys
import matplotlib.path as mplPath
class IndexTracker(object):
def __init__(self, ax, X):
self.ax = ax
ax.set_title('Scroll to Navigate through the DICOM Image Slices')
self.X = X
rows, cols, self.slices = X.shape
self.ind = self.slices//2
self.im = ax.imshow(self.X[:, :, self.ind])
self.update()
def onscroll(self, event):
print("%s %s" % (event.button, event.step))
if event.button == 'up':
self.ind = (self.ind + 1) % self.slices
else:
self.ind = (self.ind - 1) % self.slices
self.update()
def update(self):
self.im.set_data(self.X[:, :, self.ind])
ax.set_ylabel('Slice Number: %s' % self.ind)
self.im.axes.figure.canvas.draw()
fig, ax = plt.subplots(1,1)
os.system("tree C:/Users/Dicom_ROI")
plots = []
for f in glob.glob("C:/Users/Dicom_ROI/AXIAL_2/*.dcm"):
pass
filename = f.split("/")[-1]
ds = pydicom.dcmread(filename)
pix = ds.pixel_array
pix = pix*1+(-1024)
plots.append(pix)
y = np.dstack(plots)
tracker = IndexTracker(ax, y)
fig.canvas.mpl_connect('scroll_event', tracker.onscroll)
plt.show()