当我尝试使用开放的cv
和flask
模块在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()
对此非常感谢。预先感谢您帮助解决此问题。
答案 0 :(得分:0)
您需要在plt.imshow(transparent_image)
函数内调用predict
。
它抱怨未定义transparent_image
,因为您试图在其范围之外使用predict
函数的局部变量。