#!/usr/bin/env python # coding: utf-8 # In[1]: from imageai.Detection import ObjectDetection # In[2]: import os # ### Set up detector # In[3]: detector = ObjectDetection() detector.setModelTypeAsRetinaNet() # In[4]: # Load model model_path = 'resnet50_coco_best_v2.0.1.h5' detector.setModelPath(model_path) detector.loadModel() # In[5]: custom_objects = detector.CustomObjects(dog=True, cat=True) # ### Detect on image # In[30]: input_path = 'header_cats_and_dogs.jpg' # In[31]: output_path = 'result.png' # In[32]: detections = detector.detectCustomObjectsFromImage(input_image=input_path, output_image_path=output_path, custom_objects=custom_objects, minimum_percentage_probability=45) # In[9]: for obj in detections: print(obj['name'], obj['percentage_probability']) # In[10]: from IPython.display import Image # In[11]: Image('result.png') # ### Detect a Folder of Images # In[20]: import glob # In[21]: input_images_path = 'dog-pictures/*' # In[22]: output_images_path = 'results/' # In[25]: custom_objects = detector.CustomObjects(dog=True, cat=True, bird=True, cow=True, elephant=True, bear=True) # In[33]: detector.detectCustomObjectsFromImage(input_image='dog-pictures/dog-cat.jpg', output_image_path='results/result_0.jpg', custom_objects=custom_objects, minimum_percentage_probability=40) # In[38]: # Iterate through folder of images count = 0 for f in glob.glob(input_images_path): # Set output file path output_path = output_images_path + 'result_' + str(count) + '.jpg' # Detect print('Detecting...', output_path) detector.detectCustomObjectsFromImage(input_image=f, output_image_path=output_path, custom_objects=custom_objects, minimum_percentage_probability=40) count += 1 # In[45]: # Display results in notebook import matplotlib.pyplot as plt import matplotlib.image as mpimg get_ipython().run_line_magic('matplotlib', 'inline') images = [] output_images = output_images_path + '*' for f in glob.glob(output_images): images.append(mpimg.imread(f)) plt.figure(figsize=(200,200)) columns = 1 for i, image in enumerate(images): plt.subplot(len(images) / columns + 1, columns, i + 1) plt.imshow(image) # In[ ]: