微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ImageAI / Keras无法在Raspberry Pi上读取ResNet模型,但可以在Windows上运行 关于已采取的步骤代码追踪 python3 -m pip freeze输出 pip3 freeze输出

如何解决ImageAI / Keras无法在Raspberry Pi上读取ResNet模型,但可以在Windows上运行 关于已采取的步骤代码追踪 python3 -m pip freeze输出 pip3 freeze输出

关于

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

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

已采取的步骤

  • 每个软件包都安装了与Windows PC相同的pip版本
  • 使用的virtualenv
  • 从不同的轮子(不仅仅是点子)重新安装了Tensorflow
  • 搜索ImageAI的issues。有几个类似的问题,但没有有效的解决方
  • 在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.
RaspBerry Pi的

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
Windows PC的

pip3 freeze输出

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

编辑:为Windows添加pip3 freeze

解决方法

我遇到了同样的问题。因为安装所有冻结的软件包对我来说不是一个选择,所以我检查了我们共有的那些软件包,这很有意义,这会给keras加载h5文件带来麻烦

结果是: h5py 是问题

使用pip install h5py==2.10.0解决了问题

,

这很奇怪...

我通过以与Windows计算机相同的版本安装每个软件包来解决此问题。

步骤:

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

似乎毕竟是包装错误。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。