how to open dicom image using fastai?

Viewed 157

I am working on Dicom images using pydicom. But my project is in fasai and I want to open that Dicom image using the fastai library. In fastai, we normally do open_image(path) its work fine for png or jpg but if we have Dicom images we have no method to open it easily. so I use pydicom and them get their pixel array and then convert to RGB and resized. But when I again apply to open that NumPy array which I made it can't open it because open_image needs path` not a numpy image. I have a question that how I can open a Dicom image like we open a simple png image.

we open normal images like in fastai:

im = open_image(img_path)
img.show(figsize=(4,4), ax=axs[0])

it gives us shape of (3,H,W)

but in Dicom's image, it's not easy to open it as same. I need to open it like before. I tried the below code to get the image using the pydicom library.

    if (extension == 'dicom'):
    xray = read_xray(img_path)
    img = resize(xray)
    img = to_rgb(img)
    img = normalize(img)
    img = torch.from_numpy(img)
    img = np.transpose(img, [2, 0, 1])

Please help to get of from this probelm.

2 Answers

Fastai has special functions for working with medical images. You can check https://docs.fast.ai/medical.imaging. I extracted from the official docs this to open a DICOM file:

"... fastai.medical.imaging uses pydicom.dcmread to read a DICOM file. To view the header of a DICOM, specify the path of a test file and call dcmread."

TEST_DCM = Path('images/sample.dcm')
dcm = TEST_DCM.dcmread()

dcm variable should contains your images.

You can also have a more complete solution:

def is_dicomfile(file: Path) -> bool:
    """
    Checks whether a file is a DICOM-file. It uses the feature
    that Dicoms have the string DICM hardcoded at offset 0x80.

    :param file:    The full pathname of the file
    :return:        Returns true if a file is a DICOM-file
    """

    if file.is_file():
        if file.stem.startswith('.'):
            logger.warning(f'File is hidden: {file}')
        with file.open('rb') as dcmfile:
            dcmfile.seek(0x80, 1)
            if dcmfile.read(4) == b'DICM':
                return True
            else:
                # The DICM tag may be missing for anonymized DICOM files
                dicomdict = pydicom.dcmread(str(file), force=True)
                return 'Modality' in dicomdict
    else:
        return False

In this solution, you are checking whether a file is a DICOM file first. Then, it uses the features of pydicom to check if the DICOM files have the string DICM hard-coded at offset 0x80.

Related