import pydicom
from deid.dicom import replace_identifiers
from PIL import Image
from io import BytesIO
from pydicom.encaps import encapsulate
dcm = pydicom.read_file('example.dcm')
with BytesIO() as bio:
Image.fromarray(dcm.pixel_array).save(
bio,
optimize=True,
quality=95,
format="JPEG",
lossless=True,
)
dcm.PixelData = encapsulate([bio.getvalue()])
dcm.file_meta.TransferSyntaxUID = pydicom.uid.JPEGBaseline
dcm.is_little_endian = True
dcm.is_implicit_VR = False
dcm[0x7fe0, 0x0010].VR = "OB"
dcm.save_as('dcm_comp.dcm')
The thing is, when I want to read the new dicom with dcmtk it fails with
I: reading DICOM file: /tmp/dcm/dcm_comp.dcm
I: preparing pixel data
E: can't change to unencapsulated representation for pixel data
E: can't determine 'PhotometricInterpretation' of decompressed image
E: mandatory attribute 'PhotometricInterpretation' is missing or can't be determined
F: Missing attribute
PhotometricInterpretation is set (to RGB), I've tried to change it to other YRB values but it didn't help. I've also tried other TransferSyntaxUID but it didn't help either.
Do you guys have any idea what's the issue here ? It works fine with the original dicom.
$ dciodvfy ./dcm_comp.dcm
Warning - Missing attribute or value that would be needed to build DICOMDIR - Patient ID
Warning - Missing attribute or value that would be needed to build DICOMDIR - Study Date
Warning - Missing attribute or value that would be needed to build DICOMDIR - Study Time
Warning - Missing attribute or value that would be needed to build DICOMDIR - Study ID
Error - Information Object Not found
I can, however, successfully run "dcm_comp.dcm" through DCMTK's dcmdjpeg tool, which decompresses it. I can also run dcm2pnm over the compressed image to create a bitmap rendering. However, if you want to see correct colors, the PhotometricInterpretation needs to be set to YBR_FULL before the image is decompressed.
dcm2pnm -d -v ~/Downloads/dcms/dcm_comp.dcm ~/Downloads/dcms/dcm_comp.jpg
I: reading DICOM file: /home/robz/Downloads/dcms/dcm_comp.dcm
W: DcmItem: Length of element (7fe0,0010) is not a multiple of 2 (VR=OW)
I: preparing pixel data
E: can't change to unencapsulated representation for pixel data
E: can't determine 'PhotometricInterpretation' of decompressed image
E: mandatory attribute 'PhotometricInterpretation' is missing or can't be determined
F: Missing attribute
And according to dcmdump, PhotometricInterpretation is set.
dcmdump -d -v ~/Downloads/dcms/dcm_comp.dcm +P PhotometricInterpretation
W: DcmItem: Length of element (7fe0,0010) is not a multiple of 2 (VR=OW)
(0028,0004) CS [RGB] # 4, 1 PhotometricInterpretation
How could it work for you but not me, on the same file ?