python:将dcm批量转换jpg,并把图像显示出来的完整代码
时间: 2025-01-18 10:04:25 浏览: 92
在Python中,我们可以使用`pydicom`库处理DICOM文件,然后使用如`PIL`(Pillow)或`matplotlib`库来转换并显示成JPEG格式。下面是一个简单的示例,展示了如何将DICOM文件批量转换为JPEG,并使用`matplotlib`显示:
```python
import os
import pydicom
from PIL import Image
# 定义源目录和目标目录
src_dir = 'path/to/dicom/files'
dst_dir = 'path/to/jpeg/files'
# 检查目标目录是否存在,不存在则创建
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
# 遍历源目录中的所有DICOM文件
for dicom_file in os.listdir(src_dir):
if dicom_file.endswith('.dcm'):
# 解析DICOM文件
ds = pydicom.dcmread(os.path.join(src_dir, dicom_file))
# 将数据转为像素数组
img_data = ds.pixel_array
# 调整尺寸并转换为RGB格式(如果需要)
img = Image.fromarray(img_data).convert('RGB')
# 保存为JPEG
jpg_file = os.path.splitext(dicom_file)[0] + '.jpg'
img.save(os.path.join(dst_dir, jpg_file))
# 使用matplotlib显示图片(这里只用于演示,实际应用中可能不需要)
fig, ax = plt.subplots()
ax.imshow(img)
plt.show()
# 如果不打算实时显示,可以注释掉这一部分
```
请注意,这个例子假设你已经安装了`pydicom`, `Pillow`, 和 `matplotlib`库。如果没有,你可以通过pip安装:
```bash
pip install pydicom pillow matplotlib
```
阅读全文
相关推荐

















