如何用Python将JPG/PNG转为可读取DICOM文件?代码生成文件无法打开
Hey there! I totally get how frustrating this can be—most resources out there focus on converting DICOM to JPG/PNG, not the other way around. The reason your generated DCM file won't open is almost certainly missing or incorrect DICOM metadata. Unlike image formats like JPG, DICOM isn't just pixel data; it requires a ton of standardized metadata tags to be recognized by viewers. Let's fix this with a complete, working example.
Common Issues With Your Initial Code
Chances are your original code skipped critical DICOM components:
- Missing File Meta Information (the mandatory header that tells readers what kind of DICOM file this is)
- Unfilled required metadata tags (patient info, study IDs, image dimensions, etc.)
- Mismatched pixel data parameters (e.g., bits allocated vs. actual pixel depth)
Working Python Code to Convert JPG/PNG to DICOM
This example uses pydicom for DICOM handling and PIL/numpy for image processing. It fills all necessary metadata to ensure the output DCM is readable:
import datetime import pydicom from pydicom.dataset import Dataset, FileDataset, FileMetaDataset from PIL import Image import numpy as np # ---------------------- # Step 1: Load your image # ---------------------- input_img_path = "your_image.jpg" # Replace with your JPG/PNG path img = Image.open(input_img_path) # Convert to grayscale (most DICOM viewers handle grayscale best; adjust for color if needed) img_gray = img.convert("L") pixel_data = np.array(img_gray) # ---------------------- # Step 2: Create DICOM File Meta (MANDATORY) # ---------------------- file_meta = FileMetaDataset() # Use a valid SOP Class UID: "Secondary Capture Image" is ideal for converted images file_meta.MediaStorageSOPClassUID = "1.2.840.10008.5.1.4.1.1.7" file_meta.MediaStorageSOPInstanceUID = pydicom.uid.generate_uid() file_meta.ImplementationClassUID = "1.2.3.4.5.6.7.8" # Customize or use pydicom's default file_meta.TransferSyntaxUID = pydicom.uid.ImplicitVRLittleEndian # Most compatible syntax # ---------------------- # Step 3: Build Main DICOM Dataset # ---------------------- output_dcm_path = "converted_image.dcm" ds = FileDataset(output_dcm_path, {}, file_meta=file_meta, preamble=b"\x00" * 128) # Fill required patient/study/series metadata (customize these values!) ds.PatientName = "Doe^John" ds.PatientID = "PAT-1234" ds.StudyInstanceUID = pydicom.uid.generate_uid() ds.SeriesInstanceUID = pydicom.uid.generate_uid() ds.SOPInstanceUID = file_meta.MediaStorageSOPInstanceUID # Critical image metadata (must match your pixel data) ds.Rows = pixel_data.shape[0] ds.Columns = pixel_data.shape[1] ds.BitsAllocated = 8 ds.BitsStored = 8 ds.HighBit = 7 ds.PixelRepresentation = 0 # 0 = unsigned integer, 1 = signed ds.PhotometricInterpretation = "MONOCHROME2" # White = max value, black = 0 ds.SamplesPerPixel = 1 ds.PixelData = pixel_data.tobytes() # Optional: Add additional metadata ds.StudyDate = datetime.datetime.now().strftime("%Y%m%d") ds.StudyTime = datetime.datetime.now().strftime("%H%M%S") ds.InstitutionName = "Example Clinic" # ---------------------- # Step 4: Save the DICOM file # ---------------------- ds.save_as(output_dcm_path, write_like_original=False) print(f"Successfully saved valid DICOM file to: {output_dcm_path}")
Key Notes for Success
- Color Images: If you need to convert a color JPG/PNG, adjust these tags:
PhotometricInterpretation = "RGB"SamplesPerPixel = 3- Keep
BitsAllocated = 8(for 24-bit color)
- UIDs: Always generate unique UIDs for each study/series/instance using
pydicom.uid.generate_uid()—reusing UIDs can cause issues with DICOM viewers. - SOP Class UID: Use
1.2.840.10008.5.1.4.1.1.7(Secondary Capture) for converted images; this is the standard for non-medical-captured images.
Why This Works
Unlike your initial code, this example includes all mandatory DICOM structure elements: the file meta header, required patient/study metadata, and pixel data parameters that match your input image. This ensures DICOM viewers can properly parse and display the file.
内容的提问来源于stack exchange,提问作者vithika

