Python读取与显示DICOM图像入门:所需库及代码示例
How to Read, Open, and Display DICOM Images in Python for Beginners
Hey there! I’ve walked a lot of newbies through DICOM processing in Python, so let’s break this down into simple, practical steps that make sense for someone just getting started.
Essential Libraries for DICOM Work
First, you’ll need a couple of core packages—these are the standard tools used by both beginners and experienced developers:
- pydicom: The main library for reading and parsing DICOM files. It handles both the metadata (like patient info, scan settings) and the actual pixel data of the image.
- matplotlib: A straightforward plotting library that lets you display the DICOM image once you’ve extracted the pixel data.
- (Optional) SimpleITK: If you plan to dive into advanced tasks like image segmentation or registration later, this is a powerful tool—but start with the first two for the basics.
Install them with these terminal commands:
pip install pydicom matplotlib
Step-by-Step Code to Read and Display a DICOM Image
Here’s a fully commented example that walks you through every part. I’ll explain each step so you understand what’s going on:
# Import the libraries we need import pydicom import matplotlib.pyplot as plt # 1. Load your DICOM file # Replace 'your_dicom_file.dcm' with the actual path to your file dicom_dataset = pydicom.dcmread("your_dicom_file.dcm") # Optional: Peek at the metadata (patient name, scan dimensions, etc.) # Uncomment the line below to see all the stored metadata # print(dicom_dataset) # 2. Extract the pixel data from the DICOM object pixel_data = dicom_dataset.pixel_array # 3. Normalize pixel values for proper display # Most DICOMs use 16-bit values (0-65535), but matplotlib expects 8-bit (0-255) # This scales the values so the image looks clear instead of washed out or too dark normalized_data = (pixel_data - pixel_data.min()) / (pixel_data.max() - pixel_data.min()) * 255 normalized_data = normalized_data.astype("uint8") # 4. Display the image plt.figure(figsize=(10, 10)) plt.imshow(normalized_data, cmap="gray") # Grayscale is standard for medical images plt.title("DICOM Image") plt.axis("off") # Hide axis ticks for a cleaner view plt.show()
Quick Tips for Beginners
- Why normalize? Skipping this step often leads to images that look wrong—DICOMs store pixel values in a wide range, and we need to scale them down to what display tools can handle.
- Multi-frame DICOMs: The code above works for single-frame images (like X-rays or individual CT slices). If you have a series of scans (a 3D volume),
pixel_datawill be a 3D array—you’ll need to loop through the frames to display each one. - Accessing metadata: You can pull specific fields directly, like
dicom_dataset.PatientNamefor the patient’s name ordicom_dataset.Rowsfor the image height.
内容的提问来源于stack exchange,提问作者s.sowmiya
相关产品推荐
相关产品推荐

