1

关于

我正在尝试加载和使用 ImageAI ResNet 模型,然后通过 Flask 服务器访问它。有关该项目的更多详细信息,请参见我的 Github存储库

我的代码在 Windows 上运行良好,但在 Linux 上运行不佳。我将所有文件直接克隆到 Raspberry Pi,然后安装了所有 pip 依赖项。但是,在初始化 Predictor 类时程序会中断。

采取的步骤

  • 安装了与我的 Windows PC 相同的每个包的 pip 版本
  • 使用过的虚拟环境
  • 从不同的轮子重新安装了 Tensorflow(不仅仅是 pip)
  • 搜索 ImageAI 的问题。有几个类似的问题,但没有有效的解决方案
  • 在 ImageAI 存储库中创建了一个问题;还没有回应
  • 使用不同的 Raspberry Pi(Pi 2B 和 3B)
  • 在 StackOverflow 上搜索 Raspberry Pi Tensorflow 问题。数量惊人!但是,安装不同版本的 Tensorflow 并不起作用。我找不到任何其他建议的解决方案。
  • 使用 SHA-256 校验和来验证我的所有文件是否与我的 Windows PC 完全相同

再一次,这个项目的相同版本可以在我的 Windows PC 上运行。这可能是 Linux/Raspberry Pi 软件包问题,对吧?

代码

import base64
from binascii import a2b_base64
from difflib import ndiff
import json
from flask import Flask, request
from imageai.Prediction.Custom import CustomImagePrediction
from io import BytesIO
import logging
import numpy as np
import os
from PIL import Image
import tempfile


# Contains ImageAI Predictor class
class Predictor:
    def __init__(self, model):
        execution_path = os.getcwd()
        print(execution_path)
        self.prediction = CustomImagePrediction()
        self.prediction.setModelTypeAsResNet()
        self.prediction.setModelPath(os.path.join(
            execution_path, "training_data/models/" + model))
        self.prediction.setJsonPath(os.path.join(
            execution_path, "training_data/json/model_class.json"))
        self.prediction.loadModel(num_objects=3)

    def predict(self, image):
        predictions, probabilities = self.prediction.predictImage(
            image, result_count=3)
        result = {}
        for prediction, probability in zip(predictions, probabilities):
            result[prediction] = "{0:.8f}".format(probability.item())
        return result


# Intentionally global variable
predictor = Predictor("model_ex-067_acc-0.953125.h5")

log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
app = Flask(__name__)


# API's only route
@app.route("/mask", methods=["POST"])
def post_mask():
    image_uri = request.args.get("image").replace(" ", "+")
    image_encoded = image_uri.split(",")[1]
    binary_data = a2b_base64(image_encoded)
    with tempfile.NamedTemporaryFile(delete=False) as f:
        f.write(binary_data)
        filename = f.name
    prediction = predictor.predict(filename)
    os.remove(filename)
    return app.response_class(
        response=json.dumps(prediction),
        status=200,
        mimetype="application/json"
    )


if __name__ == "__main__":
    app.run("192.168.1.20", 8083)

追溯

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/imageai/Prediction/Custom/__init__.py", line 487, in loadModel
    model = ResNet50(model_path=self.modelPath, weights="trained", model_input=image_input, num_classes=self.numObjects)
  File "/usr/local/lib/python3.7/dist-packages/imageai/Prediction/ResNet/resnet50.py", line 119, in ResNet50
    model.load_weights(weights_path)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/engine/training.py", line 182, in load_weights
    return super(Model, self).load_weights(filepath, by_name)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/engine/network.py", line 1373, in load_weights
    saving.load_weights_from_hdf5_group(f, self.layers)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/saving/hdf5_format.py", line 645, in load_weights_from_hdf5_group
    original_keras_version = f.attrs['keras_version'].decode('utf8')
AttributeError: 'str' object has no attribute 'decode'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "app.py", line 38, in <module>
    predictor = Predictor("model_ex-067_acc-0.953125.h5")
  File "app.py", line 26, in __init__
    self.prediction.loadModel(num_objects=3)
  File "/usr/local/lib/python3.7/dist-packages/imageai/Prediction/Custom/__init__.py", line 491, in loadModel
    raise ValueError("You have specified an incorrect path to the ResNet model file.")
ValueError: You have specified an incorrect path to the ResNet model file.

python3 -m pip freeze树莓派的输出

absl-py==0.11.0
appdirs==1.4.4
asn1crypto==0.24.0
astor==0.8.1
cached-property==1.5.2
cachetools==4.1.1
certifi==2020.6.20
chardet==3.0.4
click==7.1.2
cryptography==2.6.1
cycler==0.10.0
distlib==0.3.1
entrypoints==0.3
filelock==3.0.12
Flask==0.12.2
gast==0.2.2
google-auth==1.23.0
google-auth-oauthlib==0.4.2
google-pasta==0.2.0
grpcio==1.33.2
h5py==2.10.0
idna==2.6
imageai==2.1.5
importlib-metadata==2.0.0
itsdangerous==1.1.0
Jinja2==2.11.2
Keras==2.4.3
Keras-Applications==1.0.8
Keras-Preprocessing==1.1.2
keyring==17.1.1
keyrings.alt==3.1.1
kiwisolver==1.3.0
Markdown==3.3.3
MarkupSafe==1.1.1
matplotlib==3.3.2
numpy==1.18.5
oauthlib==3.1.0
opencv-python==4.4.0.44
opt-einsum==3.3.0
Pillow==8.0.0
protobuf==3.13.0
pyasn1==0.4.8
pyasn1-modules==0.2.8
pycrypto==2.6.1
PyGObject==3.30.4
pyparsing==2.4.7
python-apt==1.8.4.1
python-dateutil==2.8.1
pyxdg==0.25
PyYAML==5.3.1
requests==2.21.0
requests-oauthlib==1.3.0
rsa==4.6
scipy==1.4.1
SecretStorage==2.3.1
six==1.12.0
ssh-import-id==5.7
tensorboard==1.15.0
tensorflow==1.15.2
tensorflow-estimator==1.15.1
termcolor==1.1.0
urllib3==1.24.1
virtualenv==20.1.0
Werkzeug==1.0.1
wrapt==1.12.1
zipp==3.4.0

pip3 freeze从 Windows PC 输出

absl-py==0.10.0
astor==0.8.1
autopep8==1.5.4
certifi==2020.6.20
click==7.1.2
cycler==0.10.0
Flask==0.12.2
gast==0.2.2
google-pasta==0.2.0
grpcio==1.33.1
h5py==2.10.0
imageai==2.1.5
importlib-metadata==2.0.0
itsdangerous==1.1.0
Jinja2==2.11.2
Keras==2.4.3
Keras-Applications==1.0.8
Keras-Preprocessing==1.1.2
kiwisolver==1.2.0
Markdown==3.3.2
MarkupSafe==1.1.1
matplotlib==3.3.2
numpy==1.18.5
opencv-python==4.4.0.44
opt-einsum==3.3.0
Pillow==8.0.0
protobuf==3.13.0
pycodestyle==2.6.0
pyparsing==2.4.7
python-dateutil==2.8.1
PyYAML==5.3.1
scipy==1.4.1
six==1.15.0
tensorboard==1.14.0
tensorflow==1.14.0
tensorflow-estimator==1.14.0
termcolor==1.1.0
toml==0.10.1
Werkzeug==1.0.1
wrapt==1.12.1
zipp==3.3.1

编辑:pip3 freeze为 Windows添加

4

2 回答 2

1

我遇到过同样的问题。由于安装所有冻结的软件包对我来说不是一个选项,我检查了我们有哪些共同的软件包,这是有道理的,它会在 keras 加载 h5 文件时遇到麻烦

结果是:h5py是问题所在

使用pip install h5py==2.10.0修复了问题

于 2020-11-11T07:48:59.907 回答
0

嗯,这很奇怪...

我通过将每个软件包安装在与我的 Windows 机器相同的版本来解决这个问题。

脚步:

  1. 使用Windows 输出dependencies.txt的内容创建文件pip3 freeze
  2. 运行python3 -m pip install -r dependencies.txt。这迫使 pip 将每个依赖项安装在同一版本中。
  3. 运行程序sudo python3 app.py

毕竟这似乎是一个包错误。

于 2020-11-02T17:48:06.820 回答