【问题标题】:Using Nibabel in Django在 Django 中使用 Nibabel
【发布时间】:2020-06-15 13:26:14
【问题描述】:

我正在制作一个将 .nii 文件转换为 png(zip) 的网络应用程序。 我已经在 python 中实现了主要逻辑,但是在将其移植到网络应用程序时遇到了问题。

所以我想创建一个接受 .nii 文件并输出包含所有 .png 切片的 zip 文件的表单。到目前为止,我已经写了一个简单的视图:

Views.py

from django.shortcuts import render
from .forms import SharingForms

from django.http import HttpResponse
import imageio,nibabel,numpy
from zipfile import ZipFile
from .models import NII


def index(request, **kwargs):
    if request.method == 'POST':
        form = SharingForms(request.POST,request.FILES)
        if form.is_valid():
            for field in request.FILES.keys():
                for formfile in request.FILES.getlist(field):
                    file = NII(file = formfile)
                    file.save()

                    response = HttpResponse(content_type='application/zip')
                    zip_file = ZipFile(response, 'w')
                    image_array = nibabel.load(file).get_fdata()

                    if len(image_array.shape) == 4:
                      # set 4d array dimension values
                        nx, ny, nz, nw = image_array.shape

                    total_volumes = image_array.shape[3]
                    total_slices = image_array.shape[2] 

                    for current_volume in range(0, total_volumes):
                        slice_counter = 0
                        # iterate through slices
                        for current_slice in range(0, total_slices):
                            if (slice_counter % 1) == 0:
                                # rotate or no rotate
                                data = image_array[:, :, current_slice, current_volume]

                            #alternate slices and save as png
                            print('Saving image...')
                            image_name = file[:-4] + "_t" + "{:0>3}".format(str(current_volume+1)) + "_z" + "{:0>3}".format(str(current_slice+1))+ ".png"
                            imageio.imwrite(image_name, data)
                            print('Saved.')

                            zip_file.write(image_name)

                    zip_file.close()
                    response['Content-Disposition'] = 'attachment; filename={}'.format(file)
                    return response

                   #response = HttpResponse(content_type='application/zip')
                    #zip_file = zipfile.ZipFile(response, 'w')
                    #for filename in filenames:
                    #  zip_file.write(filename)
                    #response['Content-Disposition'] = 'attachment; filename={}'.format(zipfile_name)
                    #return response


    else:
        form = SharingForms(request.POST,request.FILES)
    return render(request,'index.html',{'form':form})

模型.py

from django.db import models

class NII(models.Model):
    file = models.FileField(upload_to='upload_data')

    def __str__(self):
        return str(file)

不出所料,它不起作用,因为 nibabel.load 函数需要一个路径,而不是一个反对者 InMemoryUploadedFile。但我不知道还能做什么!

【问题讨论】:

  • 如果nibabel.load真的只对文件进行操作,你应该从客户端的POST中获取文件数据,保存为临时文件,交给.load,然后删除临时文件。这是上下文管理器的一个很好的用例(__enter__ 和__exit__)。还要检查nibabel 模块是否有类似于load 的方法,它接受数据而不是文件名。

标签: python django nifti


【解决方案1】:

所以我通过使用不同的文件上传处理程序解决了这个问题,

FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.TemporaryFileUploadHandler']

这有一个函数temporary_file_path() 然后我将它传递给nibabel.load() 函数,瞧!问题解决了。

参考:https://docs.djangoproject.com/en/3.0/ref/files/uploads/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多