Skip to content

Instantly share code, notes, and snippets.

@OlafenwaMoses
Last active August 13, 2022 17:11
Show Gist options
  • Save OlafenwaMoses/38e68a0f3bcb7350785b67d2e6bc06ce to your computer and use it in GitHub Desktop.
Save OlafenwaMoses/38e68a0f3bcb7350785b67d2e6bc06ce to your computer and use it in GitHub Desktop.
Object detection in 10 lines of code
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"] )
@khatabi-abderrahim
Copy link

hello;
i try to use your script for objet detection, but it give me this erro:

from imageai.Detection import ObjectDetection

ModuleNotFoundError: No module named 'imageai'

@jpark77
Copy link

jpark77 commented Aug 28, 2018

@abdDO87

I think you first need to get the ImageAI file from the developers' git repo (https://github.com/OlafenwaMoses/ImageAI/releases/download/2.0.2/imageai-2.0.2-py3-none-any.whl)

By executing the command "pip install imageai-2.0.2-py3-none-any.whl", you can install ImageAI.

@addy1997
Copy link

addy1997 commented Sep 1, 2018

it didnt run for me as well

@varunajmera0
Copy link

Traceback (most recent call last):
File "imaged.py", line 9, in
detector.loadModel()
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/init.py", line 184, in loadModel
model = resnet50_retinanet(num_classes=80)
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/resnet.py", line 86, in resnet50_retinanet
return resnet_retinanet(num_classes=num_classes, backbone='resnet50', inputs=inputs, **kwargs)
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/resnet.py", line 80, in resnet_retinanet
model = retinanet.retinanet_bbox(inputs=inputs, num_classes=num_classes, backbone=resnet, **kwargs)
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/retinanet.py", line 347, in retinanet_bbox
model = retinanet(inputs=inputs, num_classes=num_classes, **kwargs)
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/retinanet.py", line 310, in retinanet
pyramids = __build_pyramid(submodels, features)
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/retinanet.py", line 239, in __build_pyramid
return [__build_model_pyramid(n, m, features) for n, m in models]
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/retinanet.py", line 239, in
return [__build_model_pyramid(n, m, features) for n, m in models]
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/retinanet.py", line 226, in __build_model_pyramid
return keras.layers.Concatenate(axis=1, name=name)([model(f) for f in features])
File "/usr/local/lib/python3.7/site-packages/keras/engine/topology.py", line 603, in call
output = self.call(inputs, **kwargs)
File "/usr/local/lib/python3.7/site-packages/keras/layers/merge.py", line 347, in call
return K.concatenate(inputs, axis=self.axis)
File "/usr/local/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py", line 1768, in concatenate
return tf.concat([to_dense(x) for x in tensors], axis)
File "/usr/local/lib/python3.7/site-packages/tensorflow/python/ops/array_ops.py", line 1075, in concat
dtype=dtypes.int32).get_shape(
File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 669, in convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py", line 176, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py", line 165, in constant
tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape))
File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py", line 367, in make_tensor_proto
_AssertCompatible(values, dtype)
File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py", line 302, in _AssertCompatible
(dtype.name, repr(mismatch), type(mismatch).name))
TypeError: Expected int32, got list containing Tensors of type '_Message' instead.

@alegolas79
Copy link

importing the package in pycharm is a mess
plus it made python crash a few times.
I guess i go back to TensorFlow :(

@fhamraz
Copy link

fhamraz commented Nov 28, 2018

Doesn't work lol
Who wrote this? lol

@kevinabraham
Copy link

Traceback (most recent call last):
File "imaged.py", line 9, in
detector.loadModel()
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/init.py", line 184, in loadModel
model = resnet50_retinanet(num_classes=80)
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/resnet.py", line 86, in resnet50_retinanet
return resnet_retinanet(num_classes=num_classes, backbone='resnet50', inputs=inputs, **kwargs)
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/resnet.py", line 80, in resnet_retinanet
model = retinanet.retinanet_bbox(inputs=inputs, num_classes=num_classes, backbone=resnet, **kwargs)
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/retinanet.py", line 347, in retinanet_bbox
model = retinanet(inputs=inputs, num_classes=num_classes, **kwargs)
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/retinanet.py", line 310, in retinanet
pyramids = __build_pyramid(submodels, features)
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/retinanet.py", line 239, in __build_pyramid
return [__build_model_pyramid(n, m, features) for n, m in models]
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/retinanet.py", line 239, in
return [__build_model_pyramid(n, m, features) for n, m in models]
File "/usr/local/lib/python3.7/site-packages/imageai/Detection/keras_retinanet/models/retinanet.py", line 226, in __build_model_pyramid
return keras.layers.Concatenate(axis=1, name=name)([model(f) for f in features])
File "/usr/local/lib/python3.7/site-packages/keras/engine/topology.py", line 603, in call
output = self.call(inputs, **kwargs)
File "/usr/local/lib/python3.7/site-packages/keras/layers/merge.py", line 347, in call
return K.concatenate(inputs, axis=self.axis)
File "/usr/local/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py", line 1768, in concatenate
return tf.concat([to_dense(x) for x in tensors], axis)
File "/usr/local/lib/python3.7/site-packages/tensorflow/python/ops/array_ops.py", line 1075, in concat
dtype=dtypes.int32).get_shape(
File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 669, in convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py", line 176, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py", line 165, in constant
tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape))
File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py", line 367, in make_tensor_proto
_AssertCompatible(values, dtype)
File "/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py", line 302, in _AssertCompatible
(dtype.name, repr(mismatch), type(mismatch).name))
TypeError: Expected int32, got list containing Tensors of type '_Message' instead.

I ran into the same errors. Did anyone get past this?

@jasonsalas
Copy link

I had similar issues, but I solved it by messing with my environment. I tried "pip install..." instead of "pip3 install..." and got the imageai library to be recognized within the Jupyter notebook. Hope this helps!

@J-Omana
Copy link

J-Omana commented Feb 12, 2019

ImportError Traceback (most recent call last)
in ()
----> 1 from imageai.Detection import ObjectDetection
2 import os
3
4 execution_path = os.getcwd()
5

~\Anaconda3\lib\site-packages\imageai\Detection_init_.py in ()
----> 1 import cv2
2
3 from imageai.Detection.keras_retinanet.models.resnet import resnet50_retinanet
4 from imageai.Detection.keras_retinanet.utils.image import read_image_bgr, read_image_array, read_image_stream, preprocess_image, resize_image
5 from imageai.Detection.keras_retinanet.utils.visualization import draw_box, draw_caption

~\Anaconda3\lib\site-packages\cv2_init_.py in ()
1 import importlib
2
----> 3 from .cv2 import *
4 from .data import *
5

ImportError: DLL load failed: The specified module could not be found.

Please check what am supposed to do for this error. I have done as such you mentioned in tutorial.

@IcyW
Copy link

IcyW commented Apr 13, 2019

@Vin1412
Copy link

Vin1412 commented Jun 8, 2019

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.0.1.h5"))
detector.loadModel()
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "IMG_20160213_205925892.jpg"))

I ran above code and it gave me error as below:
TypeError Traceback (most recent call last)
in ()
6 detector.setModelTypeAsRetinaNet()
7 detector.setModelPath(os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5"))
----> 8 detector.loadModel()
9 detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "IMG_20160213_205925892.jpg"))

~\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in prod(a, axis, dtype, out, keepdims, initial)
2583 """
2584 return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out, keepdims=keepdims,
-> 2585 initial=initial)
2586
2587

~\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs)
81 return reduction(axis=axis, out=out, **passkwargs)
82
---> 83 return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
84
85

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

Can any one tell me how to fix this error

@teohck
Copy link

teohck commented Jul 10, 2019

@abdDO87

I think you first need to get the ImageAI file from the developers' git repo (https://github.com/OlafenwaMoses/ImageAI/releases/download/2.0.2/imageai-2.0.2-py3-none-any.whl)

By executing the command "pip install imageai-2.0.2-py3-none-any.whl", you can install ImageAI.

If it doesn't work still, save the image manually and rename the image to "image.jpg" in the same working directory as your FirstDetection.py, then run it.

@usman-51
Copy link

ImportError: DLL load failed: The specified procedure could not be found.

still giving this error :(

@mabugamm
Copy link

Does not work!

@NateshTyagi
Copy link

How to run this model on multiple images and store the results in a text file?

@OraculoML
Copy link

OraculoML commented Aug 19, 2019

I have just set up the enviroment and dependencies but in it spits put this

Traceback (most recent call last):
File "FirstDetection.py", line 10, in
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"))
File "C:\Users\Admin\Anaconda3\envs\tfimageai\lib\site-packages\imageai\Detection_init_.py", line 526, in detectObjectsFromImage
"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

@OlafenwaMoses
Copy link
Author

Kindly ensure you install the latest version of ImageAI via the command below.
pip3 install imageai --upgrade

@tahwaru
Copy link

tahwaru commented Aug 27, 2019

I used pip3 to upgrade all the required packages. I'm getting this:
WARNING: Logging before flag parsing goes to stderr.
W0827 00:13:16.278313 11188 module_wrapper.py:136] From C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\util\module_wrapper.py:163: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead.

W0827 00:13:16.318231 11188 module_wrapper.py:136] From C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\util\module_wrapper.py:163: The name tf.nn.fused_batch_norm is deprecated. Please use tf.compat.v1.nn.fused_batch_norm instead.

W0827 00:13:17.464979 11188 module_wrapper.py:136] From C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\util\module_wrapper.py:163: The name tf.image.resize_images is deprecated. Please use tf.image.resize instead.

W0827 00:13:17.961629 11188 deprecation.py:323] From C:\ProgramData\Anaconda3\lib\site-packages\imageai\Detection\keras_retinanet\backend\tensorflow_backend.py:46: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
Traceback (most recent call last):

File "", line 1, in
runfile('C:/Users/tahawaru/Documents/ComputerVision/ObjectDetection/ImageAI/FirstDetection.py', wdir='C:/Users/tahawaru/Documents/ComputerVision/ObjectDetection/ImageAI')

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/tahawaru/Documents/ComputerVision/ObjectDetection/ImageAI/FirstDetection.py", line 17, in
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"))

File "C:\ProgramData\Anaconda3\lib\site-packages\imageai\Detection_init_.py", line 517, in detectObjectsFromImage
raise ValueError("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

W0827 00:13:22.959074 11188 module_wrapper.py:136] From C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\util\module_wrapper.py:163: The name tf.estimator.inputs is deprecated. Please use tf.compat.v1.estimator.inputs instead.

Any help to fix this would be greatly appreciated!!!!!!!

@tahwaru
Copy link

tahwaru commented Aug 27, 2019

Now I'm just getting this:

Traceback (most recent call last):

File "", line 1, in
runfile('C:/Users/tahawaru/Documents/ComputerVision/ObjectDetection/ImageAI/image/FirstDetection.py', wdir='C:/Users/tahawaru/Documents/ComputerVision/ObjectDetection/ImageAI/image')

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/tahawaru/Documents/ComputerVision/ObjectDetection/ImageAI/image/FirstDetection.py", line 10, in
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"))

File "C:\ProgramData\Anaconda3\lib\site-packages\imageai\Detection_init_.py", line 517, in detectObjectsFromImage
raise ValueError("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

Any help on this??????

@akfaisel
Copy link

akfaisel commented Feb 26, 2020

I'm getting the following error message. I'm using Python 3.7 and Tensorflow 2.0

Traceback (most recent call last):
  File "FirstDetection.py", line 6, in <module>
    detector = ObjectDetection()
  File "D:\Anaconda3\lib\site-packages\imageai\Detection\__init__.py", line 88, in __init__
    self.sess = K.get_session()
  File "D:\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py", line 174, in get_session
    default_session = tf.get_default_session()
AttributeError: module 'tensorflow' has no attribute 'get_default_session'

I solved the above error by changing self.sess = K.get_session() to self.sess = tf.compat.v1.Session() in lib\site-packages\imageai\Detection_init_.py

@ShettyMahalakshmi
Copy link

OSError Traceback (most recent call last)
in
7 detector.setModelTypeAsRetinaNet()
8 detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5"))
----> 9 detector.loadModel()
10 detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"))
11

C:\ProgramData\Anaconda3\lib\site-packages\imageai\Detection_init_.py in loadModel(self, detection_speed)
189 elif (self.__modelType == "retinanet"):
190 model = resnet50_retinanet(num_classes=80)
--> 191 model.load_weights(self.modelPath)
192 self.__model_collection.append(model)
193 self.__modelLoaded = True

C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\network.py in load_weights(self, filepath, by_name, skip_mismatch, reshape)
1155 if h5py is None:
1156 raise ImportError('load_weights requires h5py.')
-> 1157 with h5py.File(filepath, mode='r') as f:
1158 if 'layer_names' not in f.attrs and 'model_weights' in f:
1159 f = f['model_weights']

C:\ProgramData\Anaconda3\lib\site-packages\h5py_hl\files.py in init(self, name, mode, driver, libver, userblock_size, swmr, **kwds)
310 with phil:
311 fapl = make_fapl(driver, libver, **kwds)
--> 312 fid = make_fid(name, mode, userblock_size, fapl, swmr=swmr)
313
314 if swmr_support:

C:\ProgramData\Anaconda3\lib\site-packages\h5py_hl\files.py in make_fid(name, mode, userblock_size, fapl, fcpl, swmr)
140 if swmr and swmr_support:
141 flags |= h5f.ACC_SWMR_READ
--> 142 fid = h5f.open(name, flags, fapl=fapl)
143 elif mode == 'r+':
144 fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl)

h5py_objects.pyx in h5py._objects.with_phil.wrapper()

h5py_objects.pyx in h5py._objects.with_phil.wrapper()

h5py\h5f.pyx in h5py.h5f.open()

OSError: Unable to open file (file signature not found)

@aldowiratama
Copy link

!pip install tensorflow
!pip install opencv-python
!pip install keras
!pip install numpy
!pip install imageai

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.0.1.h5"))
detector.loadModel()
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "1598954196.053694.jpg"), output_image_path=os.path.join(execution_path , "an.jpg"))

for eachObject in detections:
print(eachObject["name"] , " : " , eachObject["percentage_probability"] )

AttributeError Traceback (most recent call last)
in
4 execution_path = os.getcwd()
5
----> 6 detector = ObjectDetection()
7 detector.setModelTypeAsRetinaNet()
8 detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5"))

c:\users\asus\appdata\local\programs\python\python38\lib\site-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'

@gdinn
Copy link

gdinn commented Oct 3, 2020

!pip install tensorflow
!pip install opencv-python
!pip install keras
!pip install numpy
!pip install imageai

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.0.1.h5"))
detector.loadModel()
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "1598954196.053694.jpg"), output_image_path=os.path.join(execution_path , "an.jpg"))

for eachObject in detections:
print(eachObject["name"] , " : " , eachObject["percentage_probability"] )

AttributeError Traceback (most recent call last)
in
4 execution_path = os.getcwd()
5
----> 6 detector = ObjectDetection()
7 detector.setModelTypeAsRetinaNet()
8 detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5"))

c:\users\asus\appdata\local\programs\python\python38\lib\site-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'

same here

@Savan2708
Copy link

I don't want to save images that can not be detected so what can I do ?

@rawstar134
Copy link

To detect the object from the image from scratch using python; Click here I found the best article https://debuggingsolution.blogspot.com/2022/02/object-detection-from-scratch-in-python.html

@RiderArun
Copy link

Here's what the above code is doing:

  1. We first import the ObjectDetection class from the ImageAI library.
  2. We then create an instance of the ObjectDetection class and set the model type to RetinaNet.
  3. We then set the model path to the path of the RetinaNet model file that we downloaded earlier.
  4. We then load the model into the ObjectDetection class instance.
  5. We then call the detectObjectsFromImage method, passing in the input image path and the output image path.
  6. We then print the name of the object and the percentage probability that the object detected is the correct one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment