Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect NIfTI orientations #1

Open
fyrdahl opened this issue Sep 3, 2024 · 0 comments
Open

Incorrect NIfTI orientations #1

fyrdahl opened this issue Sep 3, 2024 · 0 comments
Labels
bug Something isn't working good first issue Good for newcomers help wanted Extra attention is needed

Comments

@fyrdahl
Copy link
Owner

fyrdahl commented Sep 3, 2024

The orientations in the NIfTI output currently need to be correctly implemented.

I have attempted to implement this (https://nipy.org/nibabel/dicom/dicom_orientation.html#dicom-affine-formula) in the affine3d function, but the current implementation is not correct.

def affine3d(ds_list):
    """See: https://nipy.org/nibabel/dicom/dicom_orientation.html#dicom-affine-formula"""

    N = len(ds_list)
    if N < 2:
        raise ValueError(
            "ds_list must contain at least two datasets to compute affine matrix"
        )

    # Extract image positions
    positions = np.array([ds.ImagePositionPatient for ds in ds_list])
    T1, T2, T3 = positions[:, 0], positions[:, 1], positions[:, 2]

    # Extract orientation
    orientation = np.array(ds_list[0].ImageOrientationPatient)
    row_x, row_y, row_z = orientation[:3]
    col_x, col_y, col_z = orientation[3:]

    # Calculate slice direction
    slice_x, slice_y, slice_z = np.cross([row_x, row_y, row_z], [col_x, col_y, col_z])

    # Extract pixel spacing
    dr, dc = ds_list[0].PixelSpacing

    # Try to get slice thickness
    try:
        dslice = float(ds_list[0].SliceThickness)
    except AttributeError:
        try:
            dslice = float(ds_list[0][0x0018, 0x0050].value)
        except KeyError:
            dslice = np.linalg.norm(positions[-1] - positions[0]) / (N - 1)

    # Calculate affine matrix
    affine = np.array(
        [
            [row_x * dr, col_x * dc, slice_x * dslice, T1[0]],
            [row_y * dr, col_y * dc, slice_y * dslice, T2[0]],
            [row_z * dr, col_z * dc, slice_z * dslice, T3[0]],
            [0, 0, 0, 1],
        ]
    )

    return affine
    
@fyrdahl fyrdahl added bug Something isn't working help wanted Extra attention is needed good first issue Good for newcomers labels Sep 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working good first issue Good for newcomers help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant