python - 在/image/expected string 或 Unicode 对象处出现 TypeError,InMemoryUploadedFile 已找到

标签 python django opencv machine-learning

我已经构建了一个图像处理分类器,在这段代码中,我正在制作一个 api,它采用输入图像形式键“test_image”并预测图像的类别,但 cv2.imread() 是给我这个错误

TypeError at /image/ expected string or Unicode object, InMemoryUploadedFile found

我知道cv2.imread只接受图像的url,但我不知道如何解决这个问题。

我的代码:

def classify_image(request):
    if request.method == 'POST' and request.FILES['test_image']:
        test_image = request.FILES['test_image']
        test_image = cv2.imread(test_image)
        test_image = cv2.resize(test_image, (128, 128))
        test_image = np.array(test_image)
        test_image = test_image.astype('float32')
        test_image /= 255
        print(test_image.shape)

        test_image = np.expand_dims(test_image, axis=0)
        pred = model.predict_classes(test_image)
        print(pred)

   return JsonResponse(pred, safe=False)

最佳答案

看起来 imread 方法旨在从文件中读取图像。有一种不同的方法,imdecode,用于从内存中读取图像。尝试用以下内容替换代码的第 4 行:

test_image = cv2.imdecode(test_image.read())

来源:

https://docs.opencv.org/3.0-beta/modules/imgcodecs/doc/reading_and_writing_images.html

https://docs.djangoproject.com/en/1.11/ref/files/uploads/

关于python - 在/image/expected string 或 Unicode 对象处出现 TypeError,InMemoryUploadedFile 已找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47291987/

相关文章:

python - Django 使用 .extra() 仅查询模型的一个字段,而不使用 .defer() 或 .only()

python - Django:数据库级别或代码级别的TextField(字符串)数据压缩

python - 如何从使用python从openCV获得的颜色检测结果区域获取屏幕坐标?

python - 在Python中的嵌套字典中存储目录结构

python - 如何在 keras/tensorflow 中为占位符提供值

django - 在 django-rest-framework 中过滤 ListAPIView

django - 定义 django 模型关系

python - django auth 用户截断电子邮件字段

python - Opencv VideoCapture速度较慢,人们无法检测

OpenCV 的 Python 模块需要一个 Ubuntu 14.04 不可用的库