3

I'm trying to replace pixel data in given example image. My code:

import matplotlib.pyplot as plt
from pydicom import dcmread
from pydicom.data import get_testdata_file

fpath = get_testdata_file('CT_small.dcm')
ds = dcmread(fpath)

# replacing rows and columens with new values 
ds.Rows = 200 
ds.Columns = 200 
# replacing pixel data with new image (type: numpy.ndarray)
ds.pixel_array = data[layer].tobytes()
...

I get this error:

AttributeError: can't set attribute

UPDATE

Ok, if I use

ds.PixelData = data[layer].tobytes()

instead of

ds.pixel_array = data[layer].tobytes()

I get an image, but it looks totally different from the original image (data[layer]). What am I missing?

  • And in which line is the error? – Tehnorobot Sep 16 '21 at 16:41
  • Sorry. In line 10: ds.pixel_array = data[layer].tobytes() – Sebastian Sep 16 '21 at 16:50
  • Most likely the data is not in the expected format. If you use CT data, the data is expected to be monochrome, with 2 bytes per pixel. You may have to convert or reshape your numpy array accordingly. As we don't have information about the data you try to set, this is only a guess. – MrBean Bremen Sep 16 '21 at 17:29
  • Yes, I think you might be right there. The new data is float32 in 200x200. I did adjust the Rows and Columns. Adding .astype(np.float16) did the Job. Thanks a lot! – Sebastian Sep 16 '21 at 17:49

1 Answers1

1

This fixes my problem:

ds.PixelData = data[layer].astype(np.float16).tobytes()