我正在制作一个网页应用程序,把.nii文件转换成png(zip)。我在python中实现了主要逻辑,但在将其移植到web应用程序.时遇到了问题。
因此,我希望创建一个表单,该表单接受一个.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})Models.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。但我不知道还能做什么!
发布于 2020-06-24 11:16:20
所以我用不同的文件上传处理程序解决了这个问题,
FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.TemporaryFileUploadHandler']这有一个函数temporary_file_path(),然后我把它传递给nibabel.load()函数,瞧!问题解决了。
参考资料:
https://stackoverflow.com/questions/62389208
复制相似问题