The error you're encountering suggests that the TotalPixelMatrixColumns attribute is not defined in your ds object. This attribute is not a standard DICOM attribute, and it seems like there might be some confusion or a custom requirement.
To address this, let's focus on ensuring that all required DICOM attributes are correctly set and that the dataset is properly formed. Here’s a refined version of the code that should work without the TotalPixelMatrixColumns attribute:
from PIL import Image
import numpy as np
import pydicom
import datetime
import io
from pydicom.encaps import encapsulate
# Convert PIL image to RGB
pilImage = pilImage.convert('RGB')
# Save the image to a BytesIO object in JPEG format
jpeg_stream = io.BytesIO()
pilImage.save(jpeg_stream, format='JPEG')
jpeg_data = jpeg_stream.getvalue()
# Read reference DICOM file
refds = pydicom.dcmread(anypath, stop_before_pixels=True)
# Create file meta information
file_meta = pydicom.FileMetaDataset()
file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.77.1.6'
file_meta.MediaStorageSOPInstanceUID = uid
file_meta.TransferSyntaxUID = pydicom.uid.JPEGBaseline # Use JPEG Baseline transfer syntax
file_meta.ImplementationClassUID = pydicom.uid.PYDICOM_IMPLEMENTATION_UID
file_meta.ImplementationVersionName = pydicom.__version__
# Create the main dataset
ds = pydicom.Dataset()
ds.file_meta = file_meta
# Set the required DICOM attributes
ds.SOPClassUID = file_meta.MediaStorageSOPClassUID
ds.SOPInstanceUID = uid
ds.StudyInstanceUID = refds.StudyInstanceUID
ds.PatientID = getattr(refds, 'PatientID', '')
ds.PatientName = getattr(refds, 'PatientName', '')
ds.StudyID = getattr(refds, 'StudyID', '')
ds.StudyDate = getattr(refds, 'StudyDate', datetime.datetime.now().strftime('%Y%m%d'))
ds.StudyTime = getattr(refds, 'StudyTime', datetime.datetime.now().strftime('%H%M%S'))
ds.SeriesInstanceUID = refds.SeriesInstanceUID
ds.SeriesNumber = seriesNum
ds.SeriesDescription = 'Label Image'
ds.Modality = 'SM'
ds.Manufacturer = getattr(refds, 'Manufacturer', 'Custom')
ds.ContentDate = ds.StudyDate
ds.ContentTime = ds.StudyTime
ds.ImageType = ['ORIGINAL', 'PRIMARY', imgtype, 'NONE']
ds.SamplesPerPixel = 3
ds.PhotometricInterpretation = 'RGB'
ds.PlanarConfiguration = 0
ds.Rows = pilImage.height
ds.Columns = pilImage.width
ds.BitsAllocated = 8
ds.BitsStored = 8
ds.HighBit = 7
ds.PixelRepresentation = 0
# Encapsulate the JPEG data
ds.PixelData = encapsulate(jpeg_data, explicit_VR=True)
# Set is_little_endian and is_implicit_VR based on the transfer syntax
ds.is_little_endian = True
ds.is_implicit_VR = False
# Save the file
ds.save_as(imgpath, write_like_original=False)
return imgpath
Explanation:
- Encapsulation: The
encapsulate function is used to encapsulate the JPEG data properly.
- Transfer Syntax: The
TransferSyntaxUID is set to , indicating that the pixel data is stored using JPEG baseline compression.