【问题标题】:TypeError: Image data cannot be converted to float Image data cannot be converted to floatTypeError:图像数据无法转换为浮点数图像数据无法转换为浮点数
【发布时间】:2019-03-14 06:51:06
【问题描述】:

当我尝试使用开放的cvflask 模块处理python 以从图像中删除背景颜色时。在运行代码时,我收到此错误:

File "new.py", line 82, in <module>
    plt.imshow(None)
  File "C:\Users\USER\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 2699, in imshow
    None else {}), **kwargs)
  File "C:\Users\USER\Anaconda3\lib\site-packages\matplotlib\__init__.py", line 1810, in inner
    return func(ax, *args, **kwargs)
  File "C:\Users\USER\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py", line 5494, in imshow
    im.set_data(X)
  File "C:\Users\USER\Anaconda3\lib\site-packages\matplotlib\image.py", line 634, in set_data
    raise TypeError("Image data cannot be converted to float")
TypeError: Image data cannot be converted to float

我不知道如何解决这个问题。还有我正在工作的代码:

import io, traceback

from flask import Flask, request, g
from flask import send_file
from flask_mako import MakoTemplates, render_template
from plim import preprocessor
import matplotlib.pyplot as plt
from PIL import Image, ExifTags
from scipy.misc import imresize
import numpy as np
import cv2
from keras.models import load_model
import tensorflow as tf

app = Flask(__name__, instance_relative_config=True)
# For Plim templates
mako = MakoTemplates(app)
app.config['MAKO_PREPROCESSOR'] = preprocessor
app.config.from_object('config')
image= cv2.imread("1.jpg")
graph = tf.get_default_graph()

def ml_predict(image):
    with graph.as_default():
       # Add a dimension for the batch
       prediction = img.predict(image[None, :, :, :])
       prediction = prediction.reshape((224,224, -1))
       return prediction

def rotate_by_exif(image):
    try:
       for orientation in ExifTags.TAGS.keys() :
           if ExifTags.TAGS[orientation]=='Orientation' : break
           exif=dict(image._getexif().items())
           if not orientation in exif:
               return image

           if exif[orientation] == 3 :
               image=image.rotate(180, expand=True)
           elif exif[orientation] == 6 :
               image=image.rotate(270, expand=True)
           elif exif[orientation] == 8 :
               image=image.rotate(90, expand=True)
           return image
    except:
        traceback.print_exc()
        return image

THRESHOLD = 0.5

def predict():
    # Load image
    #image = request.files['file']
    image = Image.open(image)
    image = rotate_by_exif(image)
    resized_image = imresize(image, (224, 224)) / 255.0
    # Model input shape = (224,224,3)
    # [0:3] - Take only the first 3 RGB channels and drop ALPHA 4th channel in case this is a PNG
    prediction = ml_predict(resized_image[:, :, 0:3])
    print('PREDICTION COUNT', (prediction[:, :, 1]>0.5).sum())

    # Resize back to original image size
    # [:, :, 1] = Take predicted class 1 - currently in our model = Person class. Class 0 = Background
    prediction = imresize(prediction[:, :, 1], (image.height, image.width))
    prediction[prediction>THRESHOLD*255] = 255
    prediction[prediction<THRESHOLD*255] = 0

    # Append transparency 4th channel to the 3 RGB image channels.
    transparent_image = np.append(np.array(image)[:, :, 0:3], prediction[: , :, None], axis=-1)
    transparent_image = Image.fromarray(transparent_image)



plt.imshow(None)
plt.show()

非常感谢任何有关此的帮助。并预先感谢您帮助解决此问题。

【问题讨论】:

  • 也许你的意思是plt.imshow(transparent_image)?
  • @xbound 我已经尝试使用透明图像,但也出现了错误。并且错误是: Traceback(最近一次调用最后一次):文件“new.py”,第 79 行,在 plt.imshow(transparent_image) NameError: name 'transparent_image' is not defined
  • 你得到不同的错误吗?
  • @Justice_Lords 甚至 plt.imshow(Image) 都不起作用。
  • 我已经编辑了上一个消息框。请看一看。谢谢

标签: python tensorflow matplotlib


【解决方案1】:

您需要在predict 函数中调用plt.imshow(transparent_image)

它抱怨 transparent_image 未定义,因为您试图在其范围之外使用 predict 函数的局部变量。

【讨论】:

  • 我已经尝试过了,但我又遇到了一个新错误:“IndentationError: 预期缩进块”如果您可以就代码告诉我可以进行哪些更改以获得特定输出。不管怎样,谢谢你的回复
  • 显示更改后代码的外观。将带有 imshow 和 show 的行放在 predict 函数的最后一行之后,它应该可以工作。
  • 请看这段代码: # 将透明度第 4 通道附加到 3 个 RGB 图像通道。 transparent_image = np.append(np.array(image)[:, :, 0:3], prediction[: , :, None], axis=-1) transparent_image = Image.fromarray(transparent_image) plt.imshow('transparent_image ') plt.imshow()
  • 您需要将带有要显示的图像的变量传递给 imshow 函数。 plt.imshow('transparent_image') 是因为你在这里传递字符串,而不是图像。 plt.imshow() 是错误的,因为您在这里根本没有传递任何参数。您需要致电plt.imshow(transparent_image) 另外,您的最后一个错误是关于缩进的,如果您粘贴代码时没有换行,我将无法判断缩进有什么问题。
  • 非常感谢您的回复。关于缩进,我希望能清除错误。正如你所说的添加 'plt.imshow(transparent_image)' 。我尝试使用它也被执行但我没有得到预期的 o/p 。我得到的输出是::FutureWarning:可能嵌套在位置 329 ''',re.VERBOSE | re.MULTILINE) 使用 TensorFlow 后端。加载模型
猜你喜欢
  • 2015-11-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2017-11-12
  • 2021-05-23
  • 2018-05-22
相关资源
最近更新 更多