首页 > 解决方案 > 如何使用 Tensorflow 模型对 Django 中 Azure 存储中的图像进行分类

问题描述

我正在开发一个 django 应用程序,用户从下拉列表中选择机器学习模型并上传图像进行分类。这个图像最初保存在项目目录中(不好,我知道),以便我可以在分类中使用它。

现在我将这些图像保存在 Azure 存储中,但目前我无法找到一种方法来访问它们而不必将它们保存在本地进行分类,所以我想我必须将它们暂时保存在项目目录中一次我在 ml 模型中使用它们,然后删除图像。

我想将此应用程序部署到 Azure Web 服务,因此我认为在项目目录中保存和删除图像是一个坏主意。

您可以在此处查看应用程序的表单

models.py
图像保存在 Azure 存储中,Azure Database for PostgreSQL 中的其他字段。

class UploadedImage(models.Model):
    image = models.ImageField(upload_to='%Y/%m/%d/')
    uploaded = models.DateTimeField(auto_now_add=False, auto_now=True)
    title = models.CharField(max_length=50)
    prediction = models.FloatField(null=True, blank=True)

    def __str__(self):
        return self.title

表格.py

class UploadImageForm(forms.ModelForm):
    EXTRA_CHOICES = [
       ('MOB', 'MobileNetV2'),
       ('VGG', 'VGG-19'),
       ('CNN', 'CNN 3BI'),
    ]
    predicted_with = forms.ChoiceField(label="Modelo Predictivo", 
                                        choices=EXTRA_CHOICES, required=True,
                                        widget=forms.Select(attrs={'class': 'form-control'})
                                      )
    class Meta:
        model = UploadedImage
        fields = [
            'image',
        ]
        widgets = {
            'image': forms.FileInput(attrs={'class':'custom-file-input'}),
        }

视图.py

def make_prediction(image_to_predict, model='MOB'):
    tf.keras.backend.reset_uids()
    folders = {'VGG': 'vgg', 'MOB': 'mobilenet', 'CNN': 'cnn3', 'MSG': 'mobile_sin_gpu'}
    model_as_json = 'upload_images/model/%s/modelo.json' % (folders[model])
    weights = 'upload_images/model/%s/modelo.h5' % (folders[model])
    json_file = open(model_as_json, 'r')    
    loaded_json_model = json_file.read()
    json_file.close()
    model = tf.keras.models.model_from_json(loaded_json_model)
    model.load_weights(weights)
    image = [image_to_predict]
    data = img_preprocessing.create_data_batches(image)
    return model.predict(data)

def upload_image_view(request):
    if request.method == 'POST':
        form = forms.UploadImageForm(request.POST, request.FILES)
        if form.is_valid():
            m = form.save(commit=False)
            try:
                pred = make_prediction(m.image.path, form.cleaned_data['predicted_with'])[0][0]
                if pred > 0.5:
                # Code continue...
            if status == 200:
                m.prediction = pred
                m.title = m.image.path
                m.save()
                # Code continue...

当我最初将图像保存在项目目录中时,上面的代码片段有效,但是当我开始将图像保存在 Azure 存储中时,我开始收到此错误: This backend doesn't support absolute paths.

所以我更改了以下行:pred = make_prediction(m.image.name, form.cleaned_data['predicted_with'])[0][0]

但是现在我有这个错误:NewRandomAccessFile failed to Create/Open: image-100.png : The system cannot find the file specified. ; No such file or directory [[{{node ReadFile}}]] [[IteratorGetNext]] [Op:__inference_predict_function_845] Function call stack: predict_function

为此,我认为我的解决方案是将图像临时保存在项目目录中,在模型中使用它,然后将其删除,但是,我认为这并不理想。

在这种情况下适合采用什么方法?

标签: djangotensorflowdjango-modelsazure-web-app-service

解决方案


推荐阅读