Python 读取 dicom 文件
首先要安装所需的库 pydicom
! pip install pydicom
下面是示例代码
import numpy as np
import pandas as pd
import os
import pydicom
from pydicom.pixel_data_handlers.util import apply_voi_lut
import matplotlib.pyplot as plt
from skimage import exposure
import cv2
def dicom2array(path, voi_lut=True, fix_monochrome=True):
dicom = pydicom.read_file(path)
# VOI LUT (if available by DICOM device) is used to transform raw DICOM data to "human-friendly" view
if voi_lut:
data = apply_voi_lut(dicom.pixel_array, dicom)
else:
data = dicom.pixel_array
# depending on this value, X-ray may look inverted - fix that:
if fix_monochrome and dicom.PhotometricInterpretation == "MONOCHROME1":
data = np.amax(data) - data
data = data - np.min(data)
data = data / np.max(data)
data = (data * 255).astype(np.uint8)
return data
def plot_img(img, size=(7, 7), is_rgb=True, title="", cmap='gray'):
plt.figure(figsize=size)
plt.imshow(img, cmap=cmap)
plt.suptitle(title)
plt.show()
def draw_bboxes(img, boxes, thickness=10, color=(255, 0, 0), img_size=(500,500)):
img_copy = img.copy()
if len(img_copy.shape) == 2:
img_copy = np.stack([img_copy, img_copy, img_copy], axis=-1)
for box in boxes:
img_copy = cv2.rectangle(
img_copy,
(int(box[0]), int(box[1])),
(int(box[2]), int(box[3])),
color, thickness)
if img_size is not None:
img_copy = cv2.resize(img_copy, img_size)
return img_copy
下载测试文件
! wget https://raw.githubusercontent.com/ElijahMingLiu/data-save/main/000434271f63a053c4128a0ba6352c7f.dicom
测试一下
img = '000434271f63a053c4128a0ba6352c7f.dicom'
img = dicom2array(img)
plot_img(img)