I’m on Windows 10 laptop running Python 3.7.9. In a minimal python script, when I try to import ObjectDetection as below, it fails:
from imageai.Detection import ObjectDetection
with the following stack trace:
File "D:Program FilesPython37libsite-packagesimageaiDetection__init__.py", line 17, in <module>
from imageai.Detection.YOLO.utils import letterbox_image, yolo_eval, preprocess_input, retrieve_yolo_detections, draw_boxes
File "D:Program FilesPython37libsite-packagesimageaiDetectionYOLOutils.py", line 2, in <module>
from keras import backend as K
File "D:Program FilesPython37libsite-packageskeras__init__.py", line 20, in <module>
from . import initializers
File "D:Program FilesPython37libsite-packageskerasinitializers__init__.py", line 124, in <module>
populate_deserializable_objects()
File "D:Program FilesPython37libsite-packageskerasinitializers__init__.py", line 49, in populate_deserializable_objects
LOCAL.GENERATED_WITH_V2 = tf.__internal__.tf2.enabled()
AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'tf2'
pip check doesn’t return any problems. Here is a list of my Python packages:
absl-py==0.10.0
adal==1.2.7
aiofiles==0.6.0
aiohttp==3.7.4.post0
aiosqlite==0.17.0
alembic==1.4.3
anyio==2.2.0
anytree==2.8.0
appdirs==1.4.4
argon2-cffi==20.1.0
ase==3.20.1
astor==0.8.1
astroid==2.5.2
astunparse==1.6.3
async-generator==1.10
async-timeout==3.0.1
asyncua==0.9.14
atari-py==0.2.6
attrs==20.2.0
azure-common==1.1.27
azure-core==1.13.0
azure-cosmos==4.2.0
azure-identity==1.5.0
azure-iot-device==2.5.1
azure-iot-hub==2.2.3
azure-mgmt-core==1.2.2
azure-mgmt-cosmosdb==6.2.0
azure-mgmt-iothub==1.0.0
azure-mgmt-iothubprovisioningservices==0.2.0
azure-mgmt-nspkg==3.0.2
azure-mgmt-resource==16.1.0
azure-mgmt-storage==17.1.0
azure-mgmt-web==2.0.0
azure-nspkg==3.0.2
Babel==2.9.0
backcall==0.2.0
black==20.8b1
bleach==3.2.1
blis==0.4.1
cached-property==1.5.2
cachetools==4.1.1
catalogue==2.0.1
certifi==2020.6.20
cffi==1.14.3
chardet==3.0.4
click==7.1.2
cliff==3.4.0
cloudpickle==1.3.0
cmaes==0.8.2
cmd2==1.3.10
colorama==0.4.3
colorlog==4.2.1
colour==0.1.5
commonmark==0.9.1
cplex==20.1.0.1
cryptography==3.4.7
cycler==0.10.0
cymem==2.0.3
Cython==0.29.21
decorator==4.4.2
defusedxml==0.6.0
deprecation==2.1.0
dill==0.3.2
distlib==0.3.1
dlx==1.0.4
docopt==0.6.2
docplex==2.15.194
efficientnet-pytorch==0.6.3
entrypoints==0.3
et-xmlfile==1.0.1
fastdtw==0.3.4
fastjsonschema==2.14.5
filelock==3.0.12
filterpy==1.4.5
flake8==3.9.0
flatbuffers==1.12
fsspec==0.8.5
future==0.18.2
gast==0.3.3
gitdb==4.0.7
GitPython==3.1.14
google-auth==1.21.3
google-auth-oauthlib==0.4.1
google-pasta==0.2.0
googledrivedownloader==0.4
graphviz==0.16
grpcio==1.32.0
gym==0.18.0
h5py==2.10.0
hyperopt==0.2.5
idna==2.10
imageai==2.1.6
importlib-metadata==1.7.0
inflection==0.5.1
ipaddress==1.0.23
ipykernel==5.3.4
ipython==7.18.1
ipython-genutils==0.2.0
ipywidgets==7.5.1
isodate==0.6.0
isort==5.5.3
janus==0.4.0
jdcal==1.4.1
jedi==0.17.2
Jinja2==2.11.2
joblib==0.16.0
json5==0.9.5
jsonschema==3.2.0
jupyter==1.0.0
jupyter-client==6.1.7
jupyter-console==6.2.0
jupyter-core==4.6.3
jupyter-packaging==0.7.12
jupyter-server==1.5.1
jupyterlab==3.0.12
jupyterlab-pygments==0.1.1
jupyterlab-server==2.4.0
Keras==2.4.3
Keras-Applications==1.0.8
keras-nightly==2.5.0.dev2021032900
Keras-Preprocessing==1.1.2
keras-resnet==0.2.0
kiwisolver==1.2.0
lark-parser==0.11.2
lazy-object-proxy==1.4.3
lightgbm==3.2.0
llvmlite==0.36.0
lxml==4.6.3
Mako==1.1.3
ManimPango==0.2.5.post0
Markdown==3.2.2
MarkupSafe==1.1.1
marshmallow==3.8.0
marshmallow-polyfield==5.10
matplotlib==3.3.2
mccabe==0.6.1
mip==1.13.0
mistune==0.8.4
mock==4.0.3
more-itertools==8.5.0
mpmath==1.1.0
msal==1.11.0
msal-extensions==0.3.0
msrest==0.6.21
msrestazure==0.6.4
multidict==5.1.0
multitasking==0.0.9
munch==2.5.0
murmurhash==1.0.2
mypy-extensions==0.4.3
nbclassic==0.2.6
nbclient==0.5.0
nbconvert==6.0.6
nbformat==5.0.7
nest-asyncio==1.4.0
networkx==2.5
notebook==6.1.4
ntlm-auth==1.5.0
numba==0.53.1
numexpr==2.7.1
numpy==1.19.3
oauthlib==3.1.0
opcua==0.98.13
opcua-client==0.8.0
opcua-widgets==0.5.10
opencv-python==4.4.0.44
openpyxl==3.0.7
opt-einsum==3.3.0
optuna==2.6.0
oyaml==1.0
packaging==20.4
paho-mqtt==1.5.1
pandas==1.2.0
pandocfilters==1.4.2
parso==0.7.1
pathspec==0.8.1
pathy==0.4.0
patsy==0.5.1
pbr==5.5.0
pep517==0.10.0
pickleshare==0.7.5
Pillow==7.0.0
pip-tools==6.1.0
pipdeptree==2.0.0
pipreqs==0.4.10
pkginfo==1.7.0
plac==1.1.3
ply==3.11
portalocker==1.7.1
preshed==3.0.2
pretrainedmodels==0.7.4
prettytable==0.7.2
progressbar==2.5
progressbar2==3.53.1
prometheus-client==0.8.0
prompt-toolkit==3.0.7
protobuf==3.13.0
psutil==5.7.2
pyasn1==0.4.8
pyasn1-modules==0.2.8
pybind11==2.6.2
pycairo==1.20.0
pycodestyle==2.7.0
pycparser==2.20
pydantic==1.7.3
pydub==0.25.1
pyflakes==2.3.1
pyglet==1.5.0
Pygments==2.7.1
PyJWT==2.0.1
pylab==0.0.2
pylint==2.7.4
pymongo==3.11.3
pyparsing==2.4.7
pyperclip==1.8.0
PyQt5==5.15.4
PyQt5-Qt5==5.15.2
PyQt5-sip==12.8.1
pyqtgraph==0.12.0
pyreadline==2.1
pyrsistent==0.17.3
PySocks==1.7.1
python-constraint==1.4.0
python-dateutil==2.8.1
python-editor==1.0.4
python-louvain==0.15
python-utils==2.4.0
pytorch-lightning==1.2.6
PyTrie==0.4.0
pytz==2020.1
pyusb==1.1.0
PyVISA==1.11.0
PyVISA-py==0.5.0
pywin32==228
pywinpty==0.5.7
PyYAML==5.3.1
pyzmq==19.0.2
qiskit==0.25.0
qiskit-aer==0.8.0
qiskit-aqua==0.9.0
qiskit-ibmq-provider==0.12.2
qiskit-ignis==0.6.0
qiskit-terra==0.17.0
qtconsole==4.7.7
QtPy==1.9.0
Quandl==3.5.2
rdflib==5.0.0
regex==2020.11.13
requests==2.24.0
requests-ntlm==1.1.0
requests-oauthlib==1.3.0
requests-unixsocket==0.2.0
retworkx==0.8.0
rich==10.1.0
rsa==4.6
SALib==1.3.12
scikit-learn==0.24.1
scipy==1.4.1
seaborn==0.11.1
segmentation-models-pytorch==0.1.3
Send2Trash==1.5.0
six==1.15.0
sklearn==0.0
smart-open==3.0.0
smmap==4.0.0
snakeviz==2.1.0
sniffio==1.2.0
sortedcontainers==2.3.0
spacy==3.0.5
spacy-legacy==3.0.2
SQLAlchemy==1.3.19
srsly==2.4.0
stable-baselines3==1.0
statsmodels==0.12.2
stevedore==3.2.2
structlog==21.1.0
sympy==1.6.2
tables==3.6.1
tabulate==0.8.9
tensorboard==2.5.0
tensorboard-data-server==0.6.1
tensorboard-plugin-wit==1.7.0
tensorflow==2.4.0
tensorflow-estimator==2.4.0
tensorflow-gpu==2.4.0
termcolor==1.1.0
terminado==0.9.1
testpath==0.4.4
thinc==8.0.2
threadpoolctl==2.1.0
timm==0.3.2
toml==0.10.2
torch==1.8.1+cu111
torch-cluster==1.5.7
torch-geometric==1.6.3
torch-scatter==2.0.5
torch-sparse==0.6.7
torch-spline-conv==1.2.0
torchaudio==0.8.1
torchmetrics==0.2.0
torchvision==0.9.1+cu111
tornado==6.1
tqdm==4.49.0
traitlets==5.0.4
typed-ast==1.4.1
typer==0.3.2
typing-extensions==3.7.4.3
uamqp==1.3.0
urllib3==1.25.10
virtualenv==20.4.3
wasabi==0.8.2
wcwidth==0.2.5
webencodings==0.5.1
websockets==8.1
Werkzeug==1.0.1
widgetsnbextension==3.5.1
wimpy==0.6
wrapt==1.12.1
xlrd==2.0.1
yarg==0.1.9
yarl==1.6.3
yfinance==0.1.54
zipp==3.2.0
Any help is appreciated!
I am working on a plant leaf detection model using imageAI library. when I create an instance of the model the following error occurs. I can not understand the error.
this is my code:
from imageai.Detection import ObjectDetection
detector = ObjectDetection()
Error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-3bc804fbfef2> in <module>()
1 from imageai.Detection import ObjectDetection
----> 2 detector = ObjectDetection()
/usr/local/lib/python3.6/dist-packages/imageai/Detection/__init__.py in __init__(self)
86 self.__yolo_model_image_size = (416, 416)
87 self.__yolo_boxes, self.__yolo_scores, self.__yolo_classes = "", "", ""
---> 88 self.sess = K.get_session()
89
90 # Unique instance variables for TinyYOLOv3.
AttributeError: module 'keras.backend' has no attribute 'get_session'
asked Nov 18, 2020 at 14:14
2
you have to use older version of keras and tensorflow.
try this
pip3 install tensorflow==1.13.1
pip3 install keras==2.2.4
or you can install tensorflow 1.14 or 1.15.1
answered Nov 18, 2020 at 14:25
![]()
faheemfaheem
5963 silver badges5 bronze badges
follow this versions..
Package Version
----------------------- ---------
absl-py 0.15.0
astunparse 1.6.3
cached-property 1.5.2
cachetools 4.2.4
certifi 2021.10.8
charset-normalizer 2.0.7
cycler 0.10.0
flatbuffers 1.12
gast 0.3.3
google-auth 2.3.0
google-auth-oauthlib 0.4.6
google-pasta 0.2.0
grpcio 1.32.0
h5py 2.10.0
idna 3.3
imageai 2.1.6
importlib-metadata 4.8.1
Keras 2.4.3
Keras-Preprocessing 1.1.2
keras-resnet 0.2.0
kiwisolver 1.3.2
Markdown 3.3.4
matplotlib 3.3.2
numpy 1.19.3
oauthlib 3.1.1
opencv-python 4.5.3.56
opt-einsum 3.3.0
Pillow 7.0.0
pip 21.2.4
protobuf 3.19.0rc1
pyasn1 0.4.8
pyasn1-modules 0.2.8
pyparsing 2.4.7
python-dateutil 2.8.2
PyYAML 6.0
requests 2.26.0
requests-oauthlib 1.3.0
rsa 4.7.2
scipy 1.4.1
setuptools 58.0.4
six 1.15.0
tensorboard 2.7.0
tensorboard-data-server 0.6.1
tensorboard-plugin-wit 1.8.0
tensorflow 2.4.0
tensorflow-estimator 2.4.0
termcolor 1.1.0
typing-extensions 3.7.4.3
urllib3 1.26.7
Werkzeug 2.0.2
wheel 0.37.0
wincertstore 0.2
wrapt 1.12.1
zipp 3.6.0
![]()
Suraj Rao
29.3k11 gold badges96 silver badges103 bronze badges
answered Oct 22, 2021 at 6:23
|
Muramur2000 3 / 3 / 0 Регистрация: 05.04.2020 Сообщений: 67 |
||||||||
|
1 |
||||||||
|
18.05.2021, 20:21. Показов 3348. Ответов 1 Метки imageai, keras, python, tensorflow2 (Все метки)
Здравствуйте. У меня стоит задача распознания людей на фото. Силуэтов, а не лиц. При распознании обьектов часто обращаются к нейронным сетям. На большинстве ресурсов для этого используют нейронные сети и модуль ImageAI. При импорте его у меня возникает проблемы. Устанавливал через pip его и все связанное Код pip install tensorflow==2.4.0 pip install keras==2.4.3 numpy==1.19.3 pillow==7.0.0 scipy==1.4.1 h5py==2.10.0 matplotlib==3.3.2 opencv-python keras-resnet==0.2.0 pip install imageai --upgrade Версия ImageAI-2.1.6
Вот код(Взял тут)
Может кто-то сталкивался с подобной проблемой?
__________________
0 |
|
3 / 3 / 0 Регистрация: 05.04.2020 Сообщений: 67 |
|
|
09.09.2021, 19:29 [ТС] |
2 |
|
Проблема была решена полной переустановкой библиотеки с ручным удалением. После этого я вручную по удалял в папке с библиотеками всё что осталось от tensorflow и установил его заново. Проблема ушла.
0 |
Hi! So everytime I run this program:
import numpy as np
import cv2
from imageai.Detection import ObjectDetection
I get an error at line 3, saying the following:
2022-10-12 10:56:14.298953: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2022-10-12 10:56:14.299073: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):
File "C:UsersAsusDesktopprojectsdetectmain.py", line 3, in <module>
from imageai.Detection import ObjectDetection
File "C:UsersAsusDesktopprojectsdetectvenvlibsite-packagesimageaiDetection__init__.py", line 17, in <module>
from imageai.Detection.YOLOv3.models import yolo_main, tiny_yolo_main
File "C:UsersAsusDesktopprojectsdetectvenvlibsite-packagesimageaiDetectionYOLOv3models.py", line 7, in <module>
from keras.layers.advanced_activations import LeakyReLU
ModuleNotFoundError: No module named 'keras.layers.advanced_activations'
I installed tensorflow and keras and imageAI. My python version is 3.9 and I use PyCharm. Can you help me fix this please? I searched everywhere online for a solution to this but couldn’t find one… I use windows 10. Thanks in advance!
У меня возникла проблема при попытке реализовать ObjectDetection как api с фреймворком Flask.
Мой исходный код — это простое использование ObjectDetection
@app.route("/")
def hello():
func()
return "Hello world"
def func():
execution_path = os.getcwd()
detector = ObjectDetection()
detector.setModelTypeAsTinyYOLOv3()
detector.setModelPath( os.path.join(execution_path , "yolo-tiny.h5"))
detector.loadModel(detection_speed="fastest")
custom_objects = detector.CustomObjects(person=True)
image_path = "sampleImage.jpg"
check = os.path.isfile(image_path)
print(check)
detections = detector.detectCustomObjectsFromImage(custom_objects=custom_objects, input_image=image_path, minimum_percentage_probability=20)
for eachObject in detections:
print(eachObject["name"] , " : " , eachObject["percentage_probability"] )
if __name__ == '__main__':
app.run(debug=True)
Проблема заключается в том, что api успешно работает только по первому запросу. Из второго запроса возникает следующая ошибка:
TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(3, 3, 3, 16), dtype=float32) is not an element of this graph.
Полная трассировка стека:
Traceback (most recent call last):
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/ptoan/Desktop/object-detection/app.py", line 15, in hello
func()
File "/Users/ptoan/Desktop/object-detection/app.py", line 24, in func
detector.loadModel(detection_speed="fastest")
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/imageai/Detection/__init__.py", line 213, in loadModel
model.load_weights(self.modelPath)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/keras/engine/network.py", line 1166, in load_weights
f, self.layers, reshape=reshape)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/keras/engine/saving.py", line 1058, in load_weights_from_hdf5_group
K.batch_set_value(weight_value_tuples)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 2470, in batch_set_value
get_session().run(assign_ops, feed_dict=feed_dict)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 929, in run
run_metadata_ptr)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1095, in _run
'Cannot interpret feed_dict key as Tensor: ' + e.args[0])
TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(3, 3, 3, 16), dtype=float32) is not an element of this graph.
Все 15 Комментарий
Кажется, эта ошибка решена после того, как я добавлю K.clear_session () перед return метода detectCustomObjectsFromImage в /imageai/Detection/__init__.py
Ошибка возникает из-за того, что для каждого вывода вы загружаете модель обнаружения. Несмотря на то, что функция K.clear_session () действительно сбрасывает экземпляр обнаружения и предотвращает ошибку, все равно будет задержка при каждой загрузке модели.
Что вы можете сделать, так это создать экземпляр обнаружения как глобальное значение и загрузить модель вне функции.
Спасибо за ответ.
Я попытался поместить экземпляр обнаружения вне функции, но он вызвал другую ошибку Ensure you specified correct input image, input type, output type and/or output image path .
Я попытался проверить входной файл с помощью
check = os.path.isfile(image_path) , он вернул истину, так что может быть проблема не в том, что ввод неверен.
Traceback (most recent call last):
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/ptoan/Desktop/object-detection/app.py", line 15, in hello
func()
File "/Users/ptoan/Desktop/object-detection/app.py", line 32, in func
detections = detector.detectCustomObjectsFromImage(custom_objects=custom_objects, input_image=image_path)
File "/Users/ptoan/Desktop/object-detection/venv/lib/python3.6/site-packages/imageai/Detection/__init__.py", line 860, in detectCustomObjectsFromImage
"Ensure you specified correct input image, input type, output type and/or output image path ")
ValueError: Ensure you specified correct input image, input type, output type and/or output image path
Я также пытаюсь использовать imageai для обнаружения объектов и сталкиваюсь с той же проблемой при создании экземпляра обнаружения в качестве глобальной переменной. Если я использую K.clear_session() время, необходимое для обнаружения объекта, увеличивается.
Мне кажется, что он не работает с несколькими потоками.
У меня такая же проблема между Flask и imageAI при создании объекта ObjectDetection в качестве глобальной переменной. Это поднимает
«ValueError: Убедитесь, что вы указали правильное изображение ввода, тип ввода, тип вывода и / или изображение вывода»
при вызове detectCustomObjectsFromImage() с пользовательским объектом input_type=array , output_type=array и передаче массива numpy в качестве изображения.
Интересно, что загружаемая мной модель yolov3 , поэтому она не должна зависеть от модели.
При более внимательном рассмотрении, похоже, возникает это исключение, когда self.sess.run вызывается с feed_dict , которое, кажется, вызывает TypeError exception указывающее, что feed_dict key can not be interpreted as a tensor.
Насколько я понимаю, при запуске в режиме отладки (именно так я запускаю flask) он по умолчанию запускается в одном потоке. Поэтому я не знаю, является ли проблема многопоточностью, хотя кажется, что между Flask и ImageAI происходит странное взаимодействие.
У меня такая же проблема, кто-то решил ее или нашел обходной путь?
Неделю назад у меня была такая же проблема.
и я решил это, установив запуск колбы в одном потоке.
вот мой пример:
from flask import Flask, Response, jsonify
app = Flask(__name__)
import os
from imageai.Detection import ObjectDetection
import time
import json
execution_path = os.getcwd()
st = time.time()
detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath(os.path.join(execution_path, "model", "resnet50_coco_best_v2.0.1.h5"))
# detector.setModelTypeAsTinyYOLOv3()
# detector.setModelPath(os.path.join(execution_path, "model", "yolo-tiny.h5"))
detector.loadModel()
# detector.loadModel(detection_speed="fastest")
print(f'Init Timer: {time.time()-st}')
@app.route('/detect/<pic_name>')
def boat_detection(pic_name):
st = time.time()
results = getDetections(pic_name)
print(f'Sum Timer: {time.time()-st}')
msg = {}
for i, result in enumerate(results, 1):
result['percentage_probability'] = float(result['percentage_probability'])
result['box_points'] = list(result['box_points'])
for index in range(len(result['box_points'])):
result['box_points'][index] = int(result['box_points'][index])
result['box_points'] = tuple(result['box_points'])
msg[str(i)] = json.dumps(result)
return jsonify(msg)
def getDetections(file_name):
start = time.time()
image_folder = os.path.join(execution_path, 'data\ship2\')
output_folder = os.path.join(execution_path, 'data\output\')
st1 = time.time()
image_file = os.path.join(image_folder, file_name)
new_image_file = os.path.join(output_folder, file_name)
print(image_file, "-->", new_image_file)
if not os.path.exists(image_file):
print("not exist.")
return
# global detector
custom_objects = detector.CustomObjects(boat=True)
detections = detector.detectCustomObjectsFromImage(
custom_objects=custom_objects,
input_image=image_file,
output_image_path=new_image_file,
minimum_percentage_probability=30)
print(f'[Info]识别到 boat{len(detections)}艘')
for eachObject in detections:
print(eachObject.items())
end = time.time()
print(f'Excute Timer: {end-st1}')
print ("耗时: ",end-start)
return detections
if __name__ == '__main__':
app.run(threaded=False) # ban the Threaded mode
наиболее важные моменты устанавливаются в app.run (threadaded = False).
версия моих пакетов:
Flask == 1.1.1
h5py == 2.9.0
Керас == 2.2.4
opencv-python == 4.1.0.25
tenorflow == 1.14.0
imageai == 2.1.0
У меня есть другое решение этой проблемы.
Недавно я нашел параметр thread_safe , он может делиться моделью с потоком, используя k.session.graph в исходном коде. Нам нужно установить его в True.
Таким образом, мы можем использовать потоки на самом деле во фляге или в другом месте с потоками.
И мой предыдущий код может измениться следующим образом:
from flask import Flask, Response, jsonify
app = Flask(__name__)
import os
from imageai.Detection import ObjectDetection
import time
import json
execution_path = os.getcwd()
st = time.time()
detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath(os.path.join(execution_path, "model", "resnet50_coco_best_v2.0.1.h5"))
# detector.setModelTypeAsTinyYOLOv3()
# detector.setModelPath(os.path.join(execution_path, "model", "yolo-tiny.h5"))
detector.loadModel()
# detector.loadModel(detection_speed="fastest")
print(f'Init Timer: {time.time()-st}')
@app.route('/detect/<pic_name>')
def boat_detection(pic_name):
st = time.time()
results = getDetections(pic_name)
print(f'Sum Timer: {time.time()-st}')
msg = {}
for i, result in enumerate(results, 1):
result['percentage_probability'] = float(result['percentage_probability'])
result['box_points'] = list(result['box_points'])
for index in range(len(result['box_points'])):
result['box_points'][index] = int(result['box_points'][index])
result['box_points'] = tuple(result['box_points'])
msg[str(i)] = json.dumps(result)
return jsonify(msg)
def getDetections(file_name):
start = time.time()
image_folder = os.path.join(execution_path, 'data\ship2\')
output_folder = os.path.join(execution_path, 'data\output\')
st1 = time.time()
image_file = os.path.join(image_folder, file_name)
new_image_file = os.path.join(output_folder, file_name)
print(image_file, "-->", new_image_file)
if not os.path.exists(image_file):
print("not exist.")
return
# global detector
custom_objects = detector.CustomObjects(boat=True)
detections = detector.detectCustomObjectsFromImage(
custom_objects=custom_objects,
input_image=image_file,
output_image_path=new_image_file,
minimum_percentage_probability=30,
thread_safe=True) # **notice this param**
print(f'[Info]识别到 boat{len(detections)}艘')
for eachObject in detections:
print(eachObject.items())
end = time.time()
print(f'Excute Timer: {end-st1}')
print ("耗时: ",end-start)
return detections
if __name__ == '__main__':
app.run(threaded=True) # we can use the threading to detect
наиболее важные моменты устанавливаются thread_safe = True . Если вы это сделаете, вы обнаружите, что мы можем загрузить модель только один раз и использовать ее во многих потоках.
@xiluzi Оба решения работали.
Привет, вы знаете решение для процедуры предсказания? Я пытаюсь сделать то же самое, что и вы, но с функцией прогнозирования, которая выдает мне ту же ошибку.
@dntzbgh Оба вышеупомянутых решения от xiluzi решают эту проблему.
@ Akashtyagi08 да, решает для функции детектирования. Я спрашивал, пытался ли кто-нибудь сделать то же самое для прогноза, поскольку я пытаюсь использовать оба в приложении фляги.
Да, при совместном использовании прогнозирования и обнаружения в одном API проблема все еще сохраняется. Я попробовал несколько обходных путей, но безуспешно.
@xiluzi, не могли бы вы помочь мне понять проблему, почему возникает ошибка, когда я пытаюсь вызвать метод detectObjectsFromImage из метода api flask без повторной загрузки модели.
Если я загружаю модель в метод api post и вызываю метод detectObjectsFromImage, он дает результаты с задержкой времени загрузки модели … но я пытаюсь уменьшить эту задержку времени загрузки модели в каждом вызове API.
Пожалуйста, обратитесь к https://github.com/OlafenwaMoses/ImageAI/issues/531, чтобы увидеть мой код.
пожалуйста, помогите понять, почему он не работает в моем коде, но отлично работает в приведенном выше коде.
заранее спасибо..
Была ли эта страница полезной?
0 / 5 — 0 рейтинги
Мой код:
from imageai.Detection import ObjectDetection
import os
execution_path = os.getcwd
detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.1.0.h5"))
detector.loadModel()
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "input.jpg"), output_image_path=os.path.join(execution_path , "output.jpg"))
Ошибка:
from imageai.Detection import ObjectDetection
2021-12-01 22:55:53.147595: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2021-12-01 22:55:53.153409: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:UsersUserAppDataLocalProgramsPythonPython39libsite-packagesimageaiDetection__init__.py", line 18, in <module>
from imageai.Detection.YOLOv3.models import yolo_main, tiny_yolo_main
File "C:UsersUserAppDataLocalProgramsPythonPython39libsite-packagesimageaiDetectionYOLOv3models.py", line 8, in <module>
from keras.layers.normalization import BatchNormalization
ImportError: cannot import name 'BatchNormalization' from 'keras.layers.normalization' (C:UsersUserAppDataLocalProgramsPythonPython39libsite-packageskeraslayersnormalization__init__.py)
У меня версия python 3.9.0, я пытался обновить библиотеку и все ее зависимости, не вышло.
Прошарил все сайты, ответа не нашел, скопировал код из документации, но ошибка только в одном:
ImportError: cannot import name ‘BatchNormalization’ from ‘keras.layers.normalization
Уведомления
- Начало
- » Python для новичков
- » object recognition
#1 Май 9, 2022 14:22:03
object recognition
hello! I am doing object recognition in python. Here is my code:
from imageai.Detection import ObjectDetection
detector = ObjectDetection()
model_path = “./models/yolo-tiny.h5”
input_path = “./input/test45.jpg”
output_path = “./output/newimage.jpg”
detector.setModelTypeAsTinyYOLOv3()
detector.setModelPath(model_path)
detector.loadModel()
detection = detector.detectObjectsFromImage(input_image=input_path, output_image_path=output_path)
for eachItem in detection:
print(eachItem , “ : ”, eachItem)
This code throws an error:
Traceback (most recent call last):
File “C:UsersДаниилPycharmProjectsobject_detectionmain.py”, line 1, in <module>
from imageai.Detection import ObjectDetection
File “C:UsersДаниилPycharmProjectsobject_detectionvenvlibsite-packagesimageaiDetection__init__.py”, line 17, in <module>
from imageai.Detection.YOLOv3.models import yolo_main, tiny_yolo_main
File “C:UsersДаниилPycharmProjectsobject_detectionvenvlibsite-packagesimageaiDetectionYOLOv3models.py”, line 8, in <module>
from keras.layers.normalization import BatchNormalization
ImportError: cannot import name ‘BatchNormalization’ from ‘keras.layers.normalization’ (C:UsersДаниилPycharmProjectsobject_detectionvenvlibsite-packageskeraslayersnormalization__init__.py)
Help solve the problem. Thanks in advance.
Отредактировано dankochkurov (Май 9, 2022 20:24:33)
Прикреплённый файлы:
main.py (484 байта)
Офлайн
- Пожаловаться
#2 Май 9, 2022 20:16:35
object recognition
Даниил спик русиан плиз анд корект формат юор пост
ит сиимс ту ми ю ниид ту инсталл коретли зис либари
1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите
и вставьте ссылку на его url
…
есчщо
Офлайн
- Пожаловаться
#3 Май 9, 2022 20:23:52
object recognition
AD0DE412
Даниил спик русиан плиз анд корект формат юор постит сиимс ту ми ю ниид ту инсталл коретли зис либари
Привет! Я делаю распознавание объектов в python. Вот мой код:
from imageai.Detection import ObjectDetection
detector = ObjectDetection()
model_path = “./models/yolo-tiny.h5”
input_path = “./input/test45.jpg”
output_path = “./output/newimage.jpg”
detector.setModelTypeAsTinyYOLOv3()
detector.setModelPath(model_path)
detector.loadModel()
detection = detector.detectObjectsFromImage(input_image=input_path, output_image_path=output_path)
for eachItem in detection:
print(eachItem , “ : ”, eachItem)
Этот код выдает ошибку:
Traceback (most recent call last):
File “C:UsersДаниилPycharmProjectsobject_detectionmain.py”, line 1, in
from imageai.Detection import ObjectDetection
File “C:UsersДаниилPycharmProjectsobject_detectionvenvlibsite-packagesimageaiDetection__init__.py”, line 17, in
from imageai.Detection.YOLOv3.models import yolo_main, tiny_yolo_main
File “C:UsersДаниилPycharmProjectsobject_detectionvenvlibsite-packagesimageaiDetectionYOLOv3models.py”, line 8, in
from keras.layers.normalization import BatchNormalization
ImportError: cannot import name ‘BatchNormalization’ from ‘keras.layers.normalization’ (C:UsersДаниилPycharmProjectsobject_detectionvenvlibsite-packageskeraslayersnormalization__init__.py)
Помогите решить проблему. Заранее спасибо.
Прикреплённый файлы:
main.py (484 байта)
Офлайн
- Пожаловаться
#4 Май 9, 2022 20:31:49
object recognition
ImportError: cannot import name ‘BatchNormalization’ from ‘keras.layers.normalization
1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите
и вставьте ссылку на его url
…
есчщо
Офлайн
- Пожаловаться
#5 Май 9, 2022 20:40:23
object recognition
те я о том что вы уверены что у вас правильно установлена эта библиотека?
1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите
и вставьте ссылку на его url
…
есчщо
Офлайн
- Пожаловаться
#6 Май 10, 2022 09:15:23
object recognition
AD0DE412
те я о том что вы уверены что у вас правильно установлена эта библиотека?
библиотека установлена скорее всего правельно
Офлайн
- Пожаловаться
Я работаю над моделью обнаружения листьев растений с использованием библиотеки imageAI. когда я создаю экземпляр модели, возникает следующая ошибка. Не могу понять ошибку. это мой код:
from imageai.Detection import ObjectDetection
detector = ObjectDetection()
Ошибка:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-3bc804fbfef2> in <module>()
1 from imageai.Detection import ObjectDetection
----> 2 detector = ObjectDetection()
/usr/local/lib/python3.6/dist-packages/imageai/Detection/__init__.py in __init__(self)
86 self.__yolo_model_image_size = (416, 416)
87 self.__yolo_boxes, self.__yolo_scores, self.__yolo_classes = "", "", ""
---> 88 self.sess = K.get_session()
89
90 # Unique instance variables for TinyYOLOv3.
AttributeError: module 'keras.backend' has no attribute 'get_session'
1 ответ
Лучший ответ
Вам нужно использовать более старую версию keras и tensorflow.
Попробуй это
pip3 install tensorflow==1.13.1
pip3 install keras==2.2.4
Или вы можете установить tensorflow 1.14 или 1.15.1
1
faheem
18 Ноя 2020 в 14:25