【问题标题】:keras image_load() in Django expected str, bytes or os.PathLike object, not ImageFieldFileDjango 中的 keras image_load() 预期 str、bytes 或 os.PathLike 对象,而不是 ImageFieldFile
【发布时间】:2023-04-10 03:51:01
【问题描述】:

当我想使用 image_load() 加载图像时,我得到了这个错误预期的 str、字节或 os.PathLike 对象,而不是 ImageFieldFile。这是我的代码

from django.db import models
from keras.preprocessing.image import load_img, img_to_array
from keras.preprocessing import image
import numpy as np

# Create your models here.


class Image(models.Model):
    picture = models.ImageField(upload_to='article_images')
    classified = models.CharField(max_length=200, blank=True)
    uploaded = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.classified

    def save(self, *args, **kwargs):
        img = load_img(self.picture, target_size=(224, 224))
        img_arr = img_to_array(img)
        to_pred = np.expand_dims(img_arr, axis=0)  # (1,299,299,3)
        print(to_pred.shape)

        super().save(*args, **kwargs)

错误: 预期的 str、字节或 os.PathLike 对象,而不是 ImageFieldFile

【问题讨论】:

  • 你解决了吗?
  • 是的,解决了。你可以在我的 github 上查看这个项目,这里是link
  • 究竟如何?出了什么问题?
  • 你能解释一下你是怎么解决这个问题的吗?

标签: python django keras


【解决方案1】:

我正在尝试从ImageField 获取文件内容的不同方法,但都失败了。所以我通过以下方式解决了它:

  1. 先保存模型,
  2. 然后做分类(只有保存后self.picture.path不是null),
  3. 然后再次更新模型。

如下:

def save(self, *args, **kwargs):
    super().save(*args, **kwargs)
    try:
        img = load_img(self.picture.path, target_size(224, 224))
        img_array = img_to_array(img)
        to_pred = np.expand_dims(img_array, axis=0)
        prep = preprocess_input(to_pred)
        model = InceptionResNetV2(weights='imagenet')
        prediction = model.predict(prep)
        decoded = decode_predictions(prediction)[0][0][1]
        self.classified = str(decoded)
        Image.objects.filter(pk=self.id).update(classified=self.classified)
        print('success')
    except Exception as e:
        print(f"Classification failed: {e}")

【讨论】:

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