Search code examples
pythondjangodjango-modelsimagefield

How to use an image as an input to a function after uploading it in my django app with ImageField


I have a django app that upload an image to pass it to an OCR model. The first step of my OCR is the preprocess step for that it need to open the image with the cv2.imread() function. For uploading the image I used "ImageField". When I upload the image I get the error: attributeerror 'imagefield' object has no attribute 'copy'

As far as what I understand it that I need to change the object type of the ImageField. Is this the problem? If it is how to correct it?

Django Model:

class Facture(models.Model):
Client = models.ForeignKey(Client, null=True, on_delete= models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True, null=True)
STATUS = (('Non Validé', 'Non Validé'),('Validé', 'Validé'),)
status = models.CharField(max_length=200, null=True, choices=STATUS, default='Non Validé')
note = models.CharField(max_length=1000, null=True)
Img = models.ImageField(upload_to='images/')

Django View:

if request.method == 'POST':

form = FactureForm(request.POST, request.FILES)

if form.is_valid():
facture=Facture()
facture.Img = form.cleaned_data["Img"]
facture.note = form.cleaned_data["note"]
img = cv2.imread(facture.Img)
blob,rW,rH = preprocess(img)
res=EASTmodel(blob)
sent=tesseract (res,rH,rW)
print(sent)
client=Client.objects.filter(user=request.user).first()
facture.Client=client
facture.save()

The preprocess function:

def preprocess(img):

#Saving a original image and shape
image = img.copy()
(origH, origW) = image.shape[:2]

# set the new height and width to default 320 by using args #dictionary.  
(newW, newH) = (3200, 3200)

#Calculate the ratio between original and new image for both height and weight.
#This ratio will be used to translate bounding box location on the original image.
rW = origW / float(newW)
rH = origH / float(newH)

# resize the original image to new dimensions
image = cv2.resize(image, (newW, newH))
(H, W) = image.shape[:2]

# construct a blob from the image to forward pass it to EAST model
blob = cv2.dnn.blobFromImage(image, 1.0, (W, H),
(123.68, 116.78, 103.94), swapRB=True, crop=False)

return (blob,rW,rH)

Solution

  • To get the image file for Facture.img you first need to getlist of files uploaded by your user on the template side / in the form:

    files_uploaded = self.request.FILES.getlist('user_file_images')
    

    You then have to save the file using the with functionality of Python in the media folder.

    filename = 'Myimage.jpg'
    pathname = os.path.join(settings.BASE_DIR, '/images/')
    with (pathname + filename, 'w') as f:
      f.write(files_uploaded)
    backend_saving_path = os.path.join ('/images/', filename)
    Facture.img = backend_saving_path
    img = cv2.imread(pathname + filename)