From imageai detection import objectdetection ошибка

I installed imageai,tensorflow,keras in python with pip

i typed this code

from imageai.Detection import ObjectDetection

it shows this error

ModuleNotFoundError: No module named 'keras.layers.advanced_activations'

module versions
imageai — 2.0.2
keras — 2.90
tensorflow — 2.9.1

im running on windows 10 pro

asked Aug 7, 2022 at 3:26

woraxe8641's user avatar

1

Try to update version of imageai to new versions.
try this

answered Aug 7, 2022 at 3:56

john_orge's user avatar

As imageai now uses Pytorch in backend, you must install a few library dependencies before installing imageai. Please refer to this link for the same.

pip install cython pillow>=7.0.0 numpy>=1.18.1 opencv-python>=4.1.2 torch>=1.9.0 --extra-index-url https://download.pytorch.org/whl/cpu torchvision>=0.10.0 --extra-index-url https://download.pytorch.org/whl/cpu pytest==7.1.3 tqdm==4.64.1 scipy>=1.7.3 matplotlib>=3.4.3 mock==4.0.3

pip install imageai --upgrade

Import the Object detection api from imageai

from imageai.Detection import ObjectDetection

Let us know if the issue still persists. Thank you.

answered Dec 27, 2022 at 16:01

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!

Muramur2000

3 / 3 / 0

Регистрация: 05.04.2020

Сообщений: 68

1

18.05.2021, 20:21. Показов 3548. Ответов 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
В итоге ошибка в первой же строке при импорте

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
runfile('C:/Users/dub-g/Downloads/try3/main.py', wdir='C:/Users/dub-g/Downloads/try3')
 
2021-05-18 22:08:56.450295: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2021-05-18 22:08:56.450423: 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:Usersdub-gDownloadstry3main.py", line 1, in <module>
    from imageai.Detection import ObjectDetection
 
  File "C:Usersdub-ganaconda3libsite-packagesimageaiDetection__init__.py", line 3, in <module>
    from imageai.Detection.keras_retinanet.models.resnet import resnet50_retinanet
 
  File "C:Usersdub-ganaconda3libsite-packagesimageaiDetectionkeras_retinanetmodelsresnet.py", line 19, in <module>
    import keras
 
  File "C:Usersdub-ganaconda3libsite-packageskeras__init__.py", line 20, in <module>
    from . import initializers
 
  File "C:Usersdub-ganaconda3libsite-packageskerasinitializers__init__.py", line 124, in <module>
    populate_deserializable_objects()
 
  File "C:Usersdub-ganaconda3libsite-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'

Вот код(Взял тут)

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
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 , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"))
 
for eachObject in detections:
    print(eachObject["name"] , " : " , eachObject["percentage_probability"] )

Может кто-то сталкивался с подобной проблемой?



0



3 / 3 / 0

Регистрация: 05.04.2020

Сообщений: 68

09.09.2021, 19:29

 [ТС]

2

Проблема была решена полной переустановкой библиотеки с ручным удалением.

После этого я вручную по удалял в папке с библиотеками всё что осталось от tensorflow и установил его заново. Проблема ушла.



0



По видео-уроку Гоши Дударя по imageai , я повторил код , но он не работает и выдает ошибку. Я установил все нужные библиотеки с документации, но у меня все равно возникает ошибка. Как можно это устранить ?

from imageai.Detection import ObjectDetection
import os

exec_path = os.getcwd()

detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath(os.path.join(exec_path, "resnet50_coco_best_v2.1.0.h5"))
detector.loadModel()

list = detector.detectObjectsFromImage(
	input_image=os.path.join(exec_path, "objects.jpg"),
	output_image_path=os.path.join(exec_path, "new_objects.jpg"),
	minimum_percentage_probability=90,
	display_percentage_probability=True,
	display_object_name=False
)

617af8e88da51753846138.png
C:UsersUserDownloadsimageAIvenvScriptspython.exe C:/Users/User/Downloads/imageAI/venv/main.py
2021-10-28 19:38:22.762717: 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-10-28 19:38:22.763252: 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:UsersUserDownloadsimageAIvenvmain.py», line 1, in
from imageai.Detection import ObjectDetection
File «C:UsersUserDownloadsimageAIvenvlibsite-packagesimageaiDetection__init__.py», line 17, in
from imageai.Detection.YOLOv3.models import yolo_main, tiny_yolo_main
File «C:UsersUserDownloadsimageAIvenvlibsite-packagesimageaiDetectionYOLOv3models.py», line 8, in
from keras.layers.normalization import BatchNormalization
ImportError: cannot import name ‘BatchNormalization’ from ‘keras.layers.normalization’ (C:UsersUserDownloadsimageAIvenvlibsite-packageskeraslayersnormalization__init__.py)

Process finished with exit code 1

  • #1

Python
сам код:
from imageai.Detection import ObjectDetection
import OS

exet_path = os.getcwd()

detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath(os.path.join(exet_path, «retinanet_resnet50_fpn_coco-eeacb38b.pth»))
detector.loadModel()

list = detector.detectObjectsFromImage(input_image=os.path.join(exet_path, «objects.jpg»),
output_image_path=os.path.join(exet_path, «new_objects.jpg»)

ошибка:
Fatal Python error: init_import_site: Failed to import the site module
Python runtime state: initialized
Traceback (most recent call last):
File «<frozen importlib._bootstrap>», line 1178, in _find_and_load
File «<frozen importlib._bootstrap>», line 1149, in _find_and_load_unlocked
File «<frozen importlib._bootstrap>», line 690, in _load_unlocked
File «<frozen importlib._bootstrap>», line 982, in exec_module
File «<frozen site>», line 616, in <module>
File «<frozen site>», line 599, in main
File «<frozen site>», line 531, in venv
File «<frozen site>», line 384, in addsitepackages
File «<frozen site>», line 226, in addsitedir
File «<frozen site>», line 179, in addpackage
File «C:Program FilesPython311Libencodingscp1252.py», line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: ‘charmap’ codec can’t decode byte 0x90 in position 1273: character maps to <undefined>

я новичок!!! не могу разобраться, помогите пожалуйста!!!)))


0

  • #3

искусственный интеллект который будет распознавать объекты!!!(извините я тут новенький и не понял что код нужно по иному прикреплять)))


0

  • #4

искусственный интеллект который будет распознавать объекты!!!

:oops:


0

  • #5

вторая строка вызывает вопросы. Почему заглавными буквами?

Последнее редактирование: Май 9, 2023


0

  • #6

вторая строка вызывает вопросы. Почему заглавными буквами?

пробовал прописать с маленькими буквами не получается все равно, одна и та же ошибка =(
может в самом пайтоне(пайчарме) дело???


0

  • #7

UnicodeDecodeError: ‘charmap’ codec can’t decode byte 0x90 in position 1273: character maps to <undefined>

это обычно выскакиевает, когда указанный кодек (charmap) не может преобразовать в юникод какой то символ, в данном случае шестнадцатеричное значение 0x90. А что там и откуда нужно разбираться с кодировкой входных данных


0

  • #8

это обычно выскакиевает, когда указанный кодек (charmap) не может преобразовать в юникод какой то символ, в данном случае шестнадцатеричное значение 0x90. А что там и откуда нужно разбираться с кодировкой входных данных

ничего не понял но очень интересно)))))))

Понравилась статья? Поделить с друзьями:
  • Fptw64 ошибка 201
  • From django contrib import admin ошибка
  • Fpt прошивка биоса ошибка 201
  • From django conf urls import url ошибка
  • Frmt read ошибка пионер