DICOM文件读取
来源于 Convert dicom to np.array - the correct way
1. 读取
import numpy as np
import pydicom
from pydicom.pixel_data_handlers.util import apply_voi_lut
def read_xray(path, voi_lut=True, fix_monochrome=True):
"""读取DICOM格式数据转为np.array uint8格式"""
dicom = pydicom.read_file(path) #读取数据
#VOI LUT(DICOM 设备可用)将原始DICOM格式转为人类适应的格式voi_lut
if voi_lut:
data = apply_voi_lut(dicom.pixel_array, dicom)
else:
data = dicom.pixel_array #直接用dicom
# "MONOCHROME1":灰度值格式 fix_monochrome固定灰度值
if fix_monochrome and dicom.PhotometricInterpretation == "MONOCHROME1":
data = np.amax(data) - data #不要改成max避免decode错误
#类似归一化后乘以255像素范围来转为黑白的图片
data = data - np.min(data)
data = data / np.max(data)
data = (data * 255).astype(np.uint8)
return data
读取看看数据
dicom_path = "abc.dcm"
data = read_xray(dicom_path)
data.shape
=================
(3093, 2850)
data
==================
array([[ 5, 5, 4, ..., 0, 0, 0],
[ 4, 5, 5, ..., 0, 0, 0],
[ 5, 5, 5, ..., 0, 0, 0],
...,
[ 55, 54, 53, ..., 121, 121, 119],
[ 55, 55, 53, ..., 121, 122, 121],
[ 54, 54, 54, ..., 121, 124, 123]], dtype=uint8)
也可用matplotlib展示
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6), dpi=150)
plt.title("dicom")
plt.imshow(data, 'gray')
plt.show()
2. resize到指定大小
def resize(array, size, keep_ratio=False, resample=Image.LANCZOS):
"""resize array到指定大小,采样格式为Image.LANCZOS
resample有:Image.BICUBIC,Image.LANCZOS,
Image.BILINEAR,Image.NEAREST四种采样方法
"""
img = Image.fromarray(array)
if keep_ratio:
img.thumbnail((size, size), resample) #缩略图,只能缩小
else:
img = img.resize((size, size), resample)
return img
resize_data = resize(data, 256)
plt.figure(figsize=(10, 6), dpi=150)
plt.title("resize dicom")
plt.imshow(resize_data, 'gray')
plt.show()