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:
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:
- use cv2
- Open PIL image from byte file
- changing parameters in img.tobytes()
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