Changing Image Format

Learn to convert an image from DICOM format into an ordinary image.

Converting and resizing images

Often in our work, we need to convert DICOM format into ordinary images and resize them—for example, converting DICOM format into PNG image format.

This option works but does not consider the metadata related to the image, especially concerning the BitsAllocated and PhotometricInterpretation values.

Pixel data interpretation

The PhotometricInterpretation value determines the intended interpretation of the pixel data. Here, we are interested in the two main values of the X-ray:

  • MONOCHROME1 is pixel data that represents a single monochrome image plane. The minimum sample value is intended to be displayed as white after any volume of interest (VOI) grayscale transformations are performed.
  • MONOCHROME2 is pixel data that represents a single monochrome image plane. The minimum sample value is intended to be displayed as black after any VOI grayscale transformations are performed.

Pixel size

A number of bits are allocated for each pixel sample. Each sample will have the same number of bits allocated. The BitsAllocated will be either 11 or a multiple of 88.

Here’s what we need to do to prepare to run this code:

  • First, we read the DICOM file.
  • Then, we convert the image into pixel_array to display the image.
  • We use resize()to set the size of the image.
  • Using the cv2.imwrite(), we save the image in PNG file format.
  • Then, we extract the file name, resize the image, and save it as PNG.

Let’s run the following code to see the bits allocated in this file and the photometric interpretation of the image:

Press + to interact
from skimage.transform import resize
import cv2
import pydicom
import numpy as np
from matplotlib import pyplot as plt
example = 'stage_2_images/ID_01fe90211.dcm'
imagedata= pydicom.dcmread(example)
img =imagedata.pixel_array
name = example.split('/')[-1][:-4]
img = resize(img,(512,512))
cv2.imwrite('output/{}.png'.format(name), img * 255)
print(imagedata.BitsAllocated)
print(imagedata.PhotometricInterpretation)

The output of the above code is 8 and MONOCHROME2. We don’t have to rework the code, but if PhotometricInterpretation was MONOCHROME1, the image would be inverted. To do this we can use numpy.invert().

Inverting the image color

In the code below, we use NumPy’s np.invert() function. We’ll use this function to invert black colors into white and white colors into black.

Press + to interact
from skimage.transform import resize
import cv2
import pydicom
import numpy as np
from matplotlib import pyplot as plt
example = 'stage_2_images/ID_01fe90211.dcm'
imagedata= pydicom.dcmread(example)
img = np.invert(imagedata.pixel_array)
name = example.split('/')[-1][:-4]
img = resize(img,(512,512))
cv2.imwrite('output/{}.png'.format(name), img * 255)

We use invert() to invert the color of the image. So, after inverting, the color of the VOI and background are swapped.