0

I need to edit medical image saved as dicom. My target is editing, doing threshhold and saving a new image as black and white.

ds = pydicom.dcmread(filename)
png = Image.fromarray(ds.pixel_array)

I can edit by ImageMagic and save an image. Next I have to replace ds.PixelData that contains an image as bytes. That is why I did:

imgAsBytes = png.tobytes()
ds.PixelData = imgAsBytes
plt.imshow(ds.pixel_array , cmap=plt.cm.bone)

Here I received an error:

The length of the pixel data in the dataset (237568 bytes) doesn't match the expected length (475136 bytes). The dataset may be corrupted or there may be an issue with the pixel data handler.

So I added:

imgAsByte+= img.tobytes()

Result is:

enter image description here

The image in .dcm is four times duplicated and isn't white and black. Why my image saved as dicom has diffrent from .png? What I tried to resolve this issue:

Info abount the original image in .dcm:

  • len(ds.PixelData) = 475136
  • len(ds.pixel_array[0]) = 464
  • len(ds.pixel_array) = 512

Info about the image in .png before saving as .dcm:

  • img.size = (464, 512)
  • img.mode = L
  • len(imgAsByte) * 2 = 475136 # after multipied 2 I have the same length like in an original image

1 Answers1

2

Most grayscale DICOM images (like MR and CT images) use 2 bytes per pixel (this can be seen in the BitsAllocated tag, that is usually 16). Your image manipulation seems to create 1 byte per pixel for these images - so you have to adapt the respective DICOM tags, at least BitsAllocated and BitsStored, that both have to be set to 8 in this case:

ds.BitsAllocated = 8
ds.BitsStored = 8

You may have to adapt other tags as well, depending on your data and your use case. If you have compressed images (which seems not to be the case in your example) you have to compress the data yourself (this is error prone, so I wouldn't do it), or change the encoding in the DICOM image.

If you want to store the data back in a PACS, you have to do more to avoid writing illegal DICOM, for example generating a new SOP Instance UID, probably changing the SOP Class to Secondary Capture, change Image Type and a few other tags - this is handled in other questions on SO, so I won't go into it here.

MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46