1
votes

I have a folder with DICOM files inside (CT scan for example) and I need to extract affine information of the volume since I will produce a mask and need it later to align the volume and mask.

However the solution I have now is not optimal at all. I use the dicom2nifti package to first create a nifti file from the folder containing DICOM files and then I use nibabel to open the created nifti file. THEN I get affine info with nii.affine (where nii is the loaded nifti file python object).
This is why, the creation of the nifti file is taking a LOT of time.

How can I get the affine matrix using python?

1
I think the question is about reading the file as "native DICOM" without converting it to NIFTI as it is currently done.kritzel_sw
I would suggest looking at the nibabel source code - it should be some combination of ImagePositionPatient, ImageOrientationPatient, GridFrameOffsetVector, perhaps others. If someone could code a Dataset.affine() function for pydicom, I'd be happy to merge that in.darcymason
I created code for an affine using pydicom, based on nipy.org/nibabel/dicom/…. If question is re-opened, I can post it.darcymason
I vote to reopen this question as it is sufficiently clear in the context of DICOM what the OP asks (especially after the edit by @darcymason is approved).MrBean Bremen
@darcymason - the question is reopened, you can go ahead :)MrBean Bremen

1 Answers

0
votes

Below is a 2d single slice affine matrix based on https://nipy.org/nibabel/dicom/dicom_orientation.html#dicom-affine-formula, using pydicom, with a pydicom Dataset ds passed to the function.

import numpy as np 

def affine2d(ds):
    F11, F21, F31 = ds.ImageOrientationPatient[3:]
    F12, F22, F32 = ds.ImageOrientationPatient[:3]

    dr, dc = ds.PixelSpacing
    Sx, Sy, Sz = ds.ImagePositionPatient

    return np.array(
        [
            [F11 * dr, F12 * dc, 0, Sx],
            [F21 * dr, F22 * dc, 0, Sy],
            [F31 * dr, F32 * dc, 0, Sz],
            [0, 0, 0, 1]
        ]
    )

I've only tested a couple of cases for the standard [1, 0, 0, 0, 1, 0] orientation. With further testing, I'd be happy to add to pydicom as a Dataset method. This could also be extended to a 3d affine (using first and last ImagePositionPatient), as described at the same link.