/ index /的TypeError:预期的二进制或unicode字符串,得到<image:43474673_7bb4465a86.jpg =“”>

时间:2017-06-02 15:45:41

标签: django tensorflow

我想使用重新训练的模型来使用Django对图像进行分类。

在我的Django项目中:

  

model.py:

from django.db import models

class Image(models.Model):

    photo = models.ImageField(null=True, blank=True)

    def __str__(self):
        return self.photo.name
  

setttings.py

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'imageupload')
  

urls.py

from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from imageupload import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index, name='index'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  

views.py

from django.shortcuts import render
from .form import UploadImageForm
from .models import Image

import os, sys
import tensorflow as tf


def index(request):

    if request.method == 'POST':
        form = UploadImageForm(request.POST, request.FILES)
        if form.is_valid():
            picture = Image(photo=request.FILES['image'])
            picture.save()


            #if os.path.isfile(picture.photo.url):

            os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

            image_path = picture

            # Read in the image_data
            image_data = tf.gfile.FastGFile(image_path, 'rb').read()

            # Loads label file, strips off carriage return
            label_lines = [line.rstrip() for line in 
                           tf.gfile.GFile("retrained_labels.txt")]

            # Unpersists graph from file
            with tf.gfile.FastGFile("retrained_graph.pb", 'rb') as f:
                graph_def = tf.GraphDef()
                graph_def.ParseFromString(f.read())
                tf.import_graph_def(graph_def, name='')

            with tf.Session() as sess:
                # Feed the image_data as input to the graph and get first prediction
                softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')

                predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data})

                # Sort to show labels of first prediction in order of confidence
                top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]

                a =[]
                label = []

                for node_id in top_k:
                    human_string = label_lines[node_id]
                    score = predictions[0][node_id]
                    a = [human_string, score]
                    label.append(a)

            return render(request, 'show.html', {'picture':picture, 'label':label})

    else:
        form = UploadImageForm()

        return render(request, 'index.html', {'form': form})
  

的index.html

<p>hello index!</p>

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}

    <input type="submit" value="Submit" />
</form>
  

show.html

<h1>This is show!!</h1>
<img src="{{ picture.photo.url }}" />
<br>
    <p>Picture'name is: </p>{{ picture.photo.name }}
<br>
    <p>The picture's label:</p>
    {{ label }}
<br>

我稍后成功上传了一张图片,浏览器出现错误:

the screenshot of the error

谢谢!

  

这个问题已经解决了!!这就是改变:

image_path = picture.photo.path

有两个要改变:

1. label_lines = [line.rstrip() for line in tf.gfile.GFile("imageupload/retrained_labels.txt")]

2. with tf.gfile.FastGFile("imageupload/retrained_graph.pb", 'rb') as f:

更改为relative path

2 个答案:

答案 0 :(得分:0)

我的猜测是错误就在于你拥有这一行:

image_path = picture

您已保存图片,因此image_path变量中您真正想要的是它存储在磁盘上的路径。您可能希望您在model.py中定义的__str__函数会为您执行此操作,但在这种情况下,没有转换为字符串。

答案 1 :(得分:0)

image_path是图片,而不是路径:

...
image_path = picture

# Read in the image_data
image_data = tf.gfile.FastGFile(image_path, 'rb').read()
...

获取图片的文件路径并将其传递给FastGFile