To store the data using JPEG compression, you need to change the transfer syntax and handle the pixel data differently. Here's how to modify your code:
Transfer Syntax: Changed to pydicom.uid.JPEGBaseline8Bit (you could also use pydicom.uid.JPEGExtended12Bit or other JPEG variants depending on your needs)
Pixel Data: Instead of using raw pixel bytes, convert the PIL image directly to JPEG format and use those compressed bytes as the pixel data
Quality Control: You can adjust the JPEG quality parameter (0-100) to balance file size vs. image quality
Other JPEG transfer syntax options you might consider:
pydicom.uid.JPEGExtended12Bit - for 12-bit JPEG
pydicom.uid.JPEGLossless - for lossless JPEG compression
pydicom.uid.JPEGLSLossless - for JPEG-LS lossless compression
Note that when using JPEG compression, the pixel data is already compressed, so you don't need to convert it to a numpy array first - you can work directly with the JPEG-encoded bytes from PIL.
User
This prints """ValueError: The (7FE0,0010) 'Pixel Data' element value hasn't been encapsulated as required for a compressed transfer syntax - see pydicom.encaps.encapsulate() for more information"""
Assistant
You're right! For compressed transfer syntaxes like JPEG, pydicom requires the pixel data to be properly encapsulated. Here's the corrected code:
The key change is using encapsulate([jpeg_bytes]) instead of directly assigning the JPEG bytes to PixelData. The encapsulate function properly formats the compressed data according to DICOM standards for compressed transfer syntaxes.
The encapsulate function takes a list of frame data (even for single-frame images, you pass a list with one element) and creates the proper DICOM encapsulation format with sequence delimiters and item tags that DICOM readers expect for compressed pixel data.
User
I'm getting an error: "'WsiDataset' object has
no attribute 'TotalPixelMatrixColumns'"
Assistant
This error suggests you're working with a Whole Slide Imaging (WSI) dataset that's missing some required DICOM SM (Slide Microscopy) attributes. When creating SM DICOM files, especially for WSI data, you need to include additional required attributes.
Here's the updated code with the necessary SM-specific attributes:
SpecimenLabelInImage - whether specimen label is visible
FocusMethod - focusing method used
ExtendedDepthOfField - whether extended depth of field was used
NumberOfFocalPlanes - number of focal planes
DimensionOrganizationType - how the image data is organized
InstanceNumber - required for all DICOM instances
If you're still getting errors, you might need to copy additional attributes from your reference dataset. You can inspect what attributes are present in your reference dataset with:
python
print([attr for attr in dir(refds) if not attr.startswith('_')])