在Python 3.7中更改NIFTI的整个图像切片

2024-05-19 00:21:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我实际上正在使用Python处理MRI图像。 图像格式为NIFTI格式 我知道了如何在x、y或z轴上可视化切片,但现在,我想对每个切片使用Sobel过滤,并用这些切片创建一个新的NIFTI图像

为此:

  • 我加载main.nii.gz映像(img=nib.load(im_路径))
  • 我用一个新名称“img_sobel”(img_sobel=nib.load(im_path))再次加载main.nii.gz图像
  • 为每个切片创建一个循环
  • Sobel过滤切片
  • 在img_sobel的相应切片上替换该切片(“img_sobel_data[:,:,sl]==np.hypot(sx,sy)”)
  • 循环结束后,将img_sobel保存为“image_XXX_sobel”

使用子图,我看到sobel过滤在每个切片上都起作用,但似乎“img_sobel_data[:,:,sl]==np.hypot(sx,sy)”行不起作用,为什么

以下是lopp部分:

    # Name the interested data
    img_data = img.get_fdata()
    img_sobel_data = img_sobel.get_fdata()

    header = img.header
    nb_img = header.get_data_shape()
    nb_img_h = nb_img[2] #Hauteur

    for sl in range(0,nb_img_h):
            slice_h = img_data[:, :, sl]
            #Sobel
            sx = ndimage.sobel(slice_h, axis=0, mode='constant')
            sy = ndimage.sobel(slice_h, axis=1, mode='constant')
            sobel_h = np.hypot(sx, sy)

            img_sobel_data[:, :, sl] = sobel_h #Change the image slice to the sobel one
# Save Sobel:
nib.save(img_sobel,imSobel_path)

怎么了?我们不能在Python中替换另一个图像切片吗?有办法解决这个问题吗

谢谢大家!

编辑:好的,我得到一点我为什么不能这么容易做的原因:我提取了NIFTI图像的切片,过滤了它们,但我没有改变NIFTI图像本身!!! 现在我的问题是:如何更改NIFTI图像从img_sobel.get_fdata()获取


Tags: 图像imgdatagetnp切片slicenb
1条回答
网友
1楼 · 发布于 2024-05-19 00:21:04

仅仅因为您没有使用affine和header正确地保存img_sobel_数据,如果您想要保存Nifti图像,您必须在保存之前提供header和affineimg_sobel = nib.Nifti1Image(img_sobel_data, affine=img_sobel_affine, header=header)。否则,您可以使用cv2库使用cv2.imwrite以其他格式保存图像,以JPG或PNG扩展名保存图像

#======================================
# Importing Necessary Libs
#======================================
import nibabel as nib
import numpy as np 
from scipy import ndimage, misc
import matplotlib.pyplot as plt
#==============================
img  = nib.load(Nifti_img_path)
img_sobel  = nib.load(Nifti_img_sobel_path)
#==============================
if True: 
    # Name the interested data  
    img_data = img.get_fdata()
    img_sobel_data = img_sobel.get_fdata()
    img_sobel_affine = img_sobel.affine
    header = img.header
    nb_img = header.get_data_shape()
    nb_img_h = nb_img[2] #Hauteur

    for sl in range(0,nb_img_h):
            slice_h = img_data[:, :, sl]
            #Sobel
            sx = ndimage.sobel(slice_h, axis=0, mode='constant')
            sy = ndimage.sobel(slice_h, axis=1, mode='constant')
            sobel_h = np.hypot(sx, sy)

            img_sobel_data[:, :, sl] = sobel_h #Change the image slice to the sobel one
# Save Sobel:
img_sobel = nib.Nifti1Image(img_sobel_data, affine=img_sobel_affine, header=header)
nib.save(img_sobel,imSobel_path)
#==============================

相关问题 更多 >

    热门问题