使用 ImageField 在我的 django 应用程序中上传图像后如何将图像用作函数的输入

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

我有一个 Django 应用程序可以上传图像以将其传递给 OCR 模型。我的 OCR 的第一步是预处理步骤,因为它需要使用 cv2.imread() 函数打开图像。为了上传图像,我使用了“ImageField”。 当我上传图片时出现错误:attributeerror 'imagefield' object has no attribute 'copy'

据我了解,我需要更改 ImageField 的对象类型。这是问题吗?如果是怎么改正呢?

Django 模型:

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 视图:

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()

预处理函数:

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)

要获取 Facture.img 的图像文件,您首先需要获取用户在模板端/以以下形式上传的文件列表:

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

然后您必须使用 Python 的 with 功能将文件保存在媒体文件夹中。

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)