2 years ago
#58860
Derek Wu
Processing Tiff and saving to Django ImageField
The program I'm trying to write takes in a multipage Tif file/stack and processes it by:
- Changing tiffile to numpy arrays
- Taking numpy arrays and turns them into tensors
- Processes tensors and turns them back to numpy arrays
- Finally takes said numpy arrays and turns it back into a tiff stack.
My Code:
models.py :
from django.db import models
import numpy as np
import tensorflow as tf
from PIL import Image
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import InMemoryUploadedFile
# Create your models here.
class TiffModel(models.Model):
name = models.CharField(max_length=450)
image = models.ImageField(blank = True, null = True)
def __str__(self):
return self.name
def img (self):
return self.image
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
images = []
tensors = []
processedArrays = []
tiffStack = []
# Read tif, convert each page into arrays in images[]
for i in range(img.n_frames):
img.seek(i)
images.append(np.array(img))
# Read every numpy array, convert to tensorflow, process by dividing by 2
for x in images:
tensorX = tf.convert_to_tensor(x)
processedTensor = tf.math.divide(tensorX,2)
tensors.append(processedTensor)
# Convert back to numpy array
for x in tensors:
processedArrays.append(x.numpy())
# Convert to tif
for x in processedArrays:
tiffStack.append(Image.fromarray(x))
img = tiffStack[0].save(self.name + ".tiff", compression="tiff_deflate", save_all=True,
append_images=tiffStack[1:])
img.save(self)
The issue I'm running into is that it seems that the tiffile is not saving correctly into my original ImageField. How can I fix this?
django
django-models
django-rest-framework
python-imaging-library
tiff
0 Answers
Your Answer