numpy 尝试在tensorflow中预测图像时出错

falq053o  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(155)

我正在尝试创建一个网站,可以使用tensorflow,flask和python对图像进行预测。这是我的代码:

from flask import Flask, render_template
import os
import numpy as np
import pandas as pd

app = Flask(__name__)

@app.route('/')
def index():
  return render_template('index.html')

import tensorflow as tf
import tensorflow_hub as hub
model = tf.keras.models.load_model(MODEL_PATH)

IMG_SIZE = 224
BATCH_SIZE = 32

custom_path = "http://t1.gstatic.com/licensed-image?q=tbn:ANd9GcQd6lM4HtInRF3cxw6h3MgUZIIiJCdMgFvXKrhaJrbw61tN3aYpMIVBi0dx0KPv1sdCrLk0sBhPeNVt8m0"

custom_data = create_data_batches(custom_path, test_data=True)

custom_preds = model.predict(custom_data)

# Get custom image prediction labels
custom_pred_labels = [get_pred_label(custom_preds[i]) for i in range(len(custom_preds))]
print(custom_pred_labels)

@app.route('/my-link/')
def my_link():
  return f"The predictions are: {custom_pred_labels}"
  
  

if __name__ == '__main__':
  app.run(host="localhost", port=3000, debug=True)

process_image函数:

def process_image(image_path, img_size=IMG_SIZE):
  """
  Takes an image file path and turns the image into a Tensor.
  """
  image = tf.io.read_file(image_path)
  image = tf.image.decode_jpeg(image, channels=3)
  image = tf.image.convert_image_dtype(image, tf.float32)
  image = tf.image.resize(image, size=[img_size, img_size])

  return image

create_data_batches函数所需部分:

def create_data_batches(X, y=None, batch_size=BATCH_SIZE, valid_data=False, test_data=False):
  """
  Creates batches out of data out of image (X) and label (y) pairs.
  Shuffles the data if it's training data but doesn't shuffle if it's validation data.
  Also accepts test data as input (no labels)
  """
  if test_data:
    print("Creating test data batches...")
    data = tf.data.Dataset.from_tensor_slices((tf.constant(X))) # only filepaths (no labels)
    data_batch = data.map(process_image).batch(BATCH_SIZE)
    return data_batch

get_image_label函数:

def get_image_label(image_path, label):
  """
  Takes an image file path name and the associated label, processes the image and returns a tuple of (image, label).
  """

  image = process_image(image_path)
  return image, label

get_pred_label函数:

def get_pred_label(prediction_probabilites):
  """
  Turns an array of prediction probabilities into a label.
  """
  return unique_breeds[np.argmax(prediction_probabilites)]

现在当我运行这个,我得到以下错误:

ValueError: Unbatching a tensor is only supported for rank >= 1

我试着把它变成一个列表,因为我找到的解决方案之一说:

custom_path = ["http://t1.gstatic.com/licensed-image?q=tbn:ANd9GcQd6lM4HtInRF3cxw6h3MgUZIIiJCdMgFvXKrhaJrbw61tN3aYpMIVBi0dx0KPv1sdCrLk0sBhPeNVt8m0"]

但是当我运行它时,我得到了这个错误:

UNIMPLEMENTED:  File system scheme 'http' not implemented (file: 'http://t1.gstatic.com/licensed-image?q=tbn:ANd9GcQd6lM4HtInRF3cxw6h3MgUZIIiJCdMgFvXKrhaJrbw61tN3aYpMIVBi0dx0KPv1sdCrLk0sBhPeNVt8m0')

任何帮助将不胜感激。

yebdmbv4

yebdmbv41#

尝试像这样将图像加载到内存中,然后将其馈送到tensorflow :

import urllib.request
def imageLoad(URL):
        headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Safari/605.1.15'}
        req = urllib.request.Request(URL, headers=headers)
        with urllib.request.urlopen(req) as url:
            img = image.load_img(BytesIO(url.read())).resize((180, 180))
            img_array = np.array(img)
    
        return img_array
    
img = imageLoad(image_path)

相关问题