Level : WORDPRESS BOOK LINKEDIN PATENT Send Mail 동냥하기 hajunho.com

반응형

Version:1.0 StartHTML:0000000100 EndHTML:0003685829 StartFragment:0000000100 EndFragment:0003685829

 

 

object_detection_tutorial Last Checkpoint: a few seconds ago (autosaved)

Python 3

 

 

 

Object Detection API Demo

Run in Google Colab View source on GitHub

Welcome to the Object Detection API. This notebook will walk you step by step through the process of using a pre-trained model to detect objects in an image.

Important: This tutorial is to help you through the first step towards using Object Detection API to build models. If you just just need an off the shelf model that does the job, see the TFHub object detection example.

Setup

Important: If you're running on a local machine, be sure to follow the installation instructions. This notebook includes only what's necessary to run in Colab.

Install

 

 

 

!pip install -U --pre --user tensorflow=="2.*"

Collecting tensorflow==2.* Using cached https://files.pythonhosted.org/packages/d5/97/fbec42dfdb93a37ec971ca0996ff70b8eb5817789a9c1880aafd4684c9af/tensorflow-2.1.0rc1-cp36-cp36m-manylinux2010_x86_64.whl Requirement already satisfied, skipping upgrade: numpy<2.0,>=1.16.0 in /home/joe/.local/lib/python3.6/site-packages (from tensorflow==2.*) (1.17.4) Collecting tensorflow-estimator<2.2.0,>=2.1.0rc0 Using cached https://files.pythonhosted.org/packages/54/3a/c3e5e835a1e0afd8106a06fdfdba1441915cc7b6e3852c7612f437f2887e/tensorflow_estimator-2.1.0rc0-py2.py3-none-any.whl Requirement already satisfied, skipping upgrade: wrapt>=1.11.1 in /home/joe/.local/lib/python3.6/site-packages (from tensorflow==2.*) (1.11.2) Requirement already satisfied, skipping upgrade: grpcio>=1.8.6 in /home/joe/.local/lib/python3.6/site-packages (from tensorflow==2.*) (1.25.0) Requirement already satisfied, skipping upgrade: six>=1.12.0 in /home/joe/.local/lib/python3.6/site-packages (from tensorflow==2.*) (1.13.0) Requirement already satisfied, skipping upgrade: absl-py>=0.7.0 in /home/joe/.local/lib/python3.6/site-packages (from tensorflow==2.*) (0.8.1) Processing /home/joe/.cache/pip/wheels/2c/b1/94/43d03e130b929aae7ba3f8d15cbd7bc0d1cb5bb38a5c721833/opt_einsum-3.1.0-cp36-none-any.whl Requirement already satisfied, skipping upgrade: protobuf>=3.8.0 in /home/joe/.local/lib/python3.6/site-packages (from tensorflow==2.*) (3.11.1) Requirement already satisfied, skipping upgrade: termcolor>=1.1.0 in /home/joe/.local/lib/python3.6/site-packages (from tensorflow==2.*) (1.1.0) Requirement already satisfied, skipping upgrade: wheel>=0.26; python_version >= "3" in /home/joe/.local/lib/python3.6/site-packages (from tensorflow==2.*) (0.33.6) Requirement already satisfied, skipping upgrade: google-pasta>=0.1.6 in /home/joe/.local/lib/python3.6/site-packages (from tensorflow==2.*) (0.1.8) Requirement already satisfied, skipping upgrade: astor>=0.6.0 in /home/joe/.local/lib/python3.6/site-packages (from tensorflow==2.*) (0.8.1) Collecting tensorboard<2.2.0,>=2.1.0 Using cached https://files.pythonhosted.org/packages/40/23/53ffe290341cd0855d595b0a2e7485932f473798af173bbe3a584b99bb06/tensorboard-2.1.0-py3-none-any.whl Requirement already satisfied, skipping upgrade: keras-preprocessing>=1.1.0 in /home/joe/.local/lib/python3.6/site-packages (from tensorflow==2.*) (1.1.0) Requirement already satisfied, skipping upgrade: keras-applications>=1.0.8 in /home/joe/.local/lib/python3.6/site-packages (from tensorflow==2.*) (1.0.8) Processing /home/joe/.cache/pip/wheels/5c/2e/7e/a1d4d4fcebe6c381f378ce7743a3ced3699feb89bcfbdadadd/gast-0.2.2-cp36-none-any.whl Requirement already satisfied, skipping upgrade: setuptools in /home/joe/.local/lib/python3.6/site-packages (from protobuf>=3.8.0->tensorflow==2.*) (42.0.2) Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /home/joe/.local/lib/python3.6/site-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow==2.*) (3.1.1) Collecting google-auth<2,>=1.6.3 Using cached https://files.pythonhosted.org/packages/54/31/f944cbd5bdbcc90d5b36f0615036308c8ec1e41b4788da5b55d4900f6803/google_auth-1.8.2-py2.py3-none-any.whl Requirement already satisfied, skipping upgrade: werkzeug>=0.11.15 in /home/joe/.local/lib/python3.6/site-packages (from tensorboard<2.2.0,>=2.1.0->tensorflow==2.*) (0.16.0) Collecting google-auth-oauthlib<0.5,>=0.4.1 Using cached https://files.pythonhosted.org/packages/7b/b8/88def36e74bee9fce511c9519571f4e485e890093ab7442284f4ffaef60b/google_auth_oauthlib-0.4.1-py2.py3-none-any.whl Collecting requests<3,>=2.21.0 Using cached https://files.pythonhosted.org/packages/51/bd/23c926cd341ea6b7dd0b2a00aba99ae0f828be89d72b2190f27c11d4b7fb/requests-2.22.0-py2.py3-none-any.whl Requirement already satisfied, skipping upgrade: h5py in /home/joe/.local/lib/python3.6/site-packages (from keras-applications>=1.0.8->tensorflow==2.*) (2.10.0) Collecting rsa<4.1,>=3.1.4 Using cached https://files.pythonhosted.org/packages/02/e5/38518af393f7c214357079ce67a317307936896e961e35450b70fad2a9cf/rsa-4.0-py2.py3-none-any.whl Collecting cachetools<3.2,>=2.0.0 Using cached https://files.pythonhosted.org/packages/2f/a6/30b0a0bef12283e83e58c1d6e7b5aabc7acfc4110df81a4471655d33e704/cachetools-3.1.1-py2.py3-none-any.whl Collecting pyasn1-modules>=0.2.1 Using cached https://files.pythonhosted.org/packages/52/50/bb4cefca37da63a0c52218ba2cb1b1c36110d84dcbae8aa48cd67c5e95c2/pyasn1_modules-0.2.7-py2.py3-none-any.whl Collecting requests-oauthlib>=0.7.0 Using cached https://files.pythonhosted.org/packages/a3/12/b92740d845ab62ea4edf04d2f4164d82532b5a0b03836d4d4e71c6f3d379/requests_oauthlib-1.3.0-py2.py3-none-any.whl Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/lib/python3/dist-packages (from requests<3,>=2.21.0->tensorboard<2.2.0,>=2.1.0->tensorflow==2.*) (1.22) Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /usr/lib/python3/dist-packages (from requests<3,>=2.21.0->tensorboard<2.2.0,>=2.1.0->tensorflow==2.*) (2.6) Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /usr/lib/python3/dist-packages (from requests<3,>=2.21.0->tensorboard<2.2.0,>=2.1.0->tensorflow==2.*) (3.0.4) Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/lib/python3/dist-packages (from requests<3,>=2.21.0->tensorboard<2.2.0,>=2.1.0->tensorflow==2.*) (2018.1.18) Collecting pyasn1>=0.1.3 Using cached https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl Collecting oauthlib>=3.0.0 Using cached https://files.pythonhosted.org/packages/05/57/ce2e7a8fa7c0afb54a0581b14a65b56e62b5759dbc98e80627142b8a3704/oauthlib-3.1.0-py2.py3-none-any.whl Installing collected packages: tensorflow-estimator, opt-einsum, pyasn1, rsa, cachetools, pyasn1-modules, google-auth, oauthlib, requests, requests-oauthlib, google-auth-oauthlib, tensorboard, gast, tensorflow Found existing installation: tensorflow-estimator 1.14.0 Uninstalling tensorflow-estimator-1.14.0: Successfully uninstalled tensorflow-estimator-1.14.0 WARNING: The scripts pyrsa-decrypt, pyrsa-encrypt, pyrsa-keygen, pyrsa-priv2pub, pyrsa-sign and pyrsa-verify are installed in '/home/joe/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: The script google-oauthlib-tool is installed in '/home/joe/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Found existing installation: tensorboard 1.14.0 Uninstalling tensorboard-1.14.0: Successfully uninstalled tensorboard-1.14.0 WARNING: The script tensorboard is installed in '/home/joe/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Found existing installation: gast 0.3.2 Uninstalling gast-0.3.2: Successfully uninstalled gast-0.3.2 Found existing installation: tensorflow 1.14.0 Uninstalling tensorflow-1.14.0: Successfully uninstalled tensorflow-1.14.0 WARNING: The scripts estimator_ckpt_converter, saved_model_cli, tensorboard, tf_upgrade_v2, tflite_convert, toco and toco_from_protos are installed in '/home/joe/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed cachetools-3.1.1 gast-0.2.2 google-auth-1.8.2 google-auth-oauthlib-0.4.1 oauthlib-3.1.0 opt-einsum-3.1.0 pyasn1-0.4.8 pyasn1-modules-0.2.7 requests-2.22.0 requests-oauthlib-1.3.0 rsa-4.0 tensorboard-2.1.0 tensorflow-2.1.0rc1 tensorflow-estimator-2.1.0rc0

Make sure you have pycocotools installed

 

 

 

 

!pip install --user pycocotools

Processing /home/joe/.cache/pip/wheels/dc/e6/36/0e1ae88c868eb42d3f92181b1c9bbd0b217a7ec3da6bd62e55/pycocotools-2.0.0-cp36-cp36m-linux_x86_64.whl Installing collected packages: pycocotools Successfully installed pycocotools-2.0.0

Get tensorflow/models or cd to parent directory of the repository.

 

 

 

import osimport pathlibif "models" in pathlib.Path.cwd().parts: while "models" in pathlib.Path.cwd().parts: os.chdir('..')elif not pathlib.Path('models').exists(): !git clone --depth 1 https://github.com/tensorflow/models

 

Compile protobufs and install the object_detection package

 

 

 

%%bashcd models/research/protoc object_detection/protos/*.proto --python_out=.

 

 

 

 

%%bash cd models/researchpip install --user .

Processing /home/joe/ai/models/research Requirement already satisfied: Pillow>=1.0 in /home/joe/.local/lib/python3.6/site-packages (from object-detection==0.1) (6.2.1) Requirement already satisfied: Matplotlib>=2.1 in /home/joe/.local/lib/python3.6/site-packages (from object-detection==0.1) (3.1.2) Requirement already satisfied: Cython>=0.28.1 in /home/joe/.local/lib/python3.6/site-packages (from object-detection==0.1) (0.29.14) Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /home/joe/.local/lib/python3.6/site-packages (from Matplotlib>=2.1->object-detection==0.1) (2.4.5) Requirement already satisfied: python-dateutil>=2.1 in /home/joe/.local/lib/python3.6/site-packages (from Matplotlib>=2.1->object-detection==0.1) (2.8.1) Requirement already satisfied: numpy>=1.11 in /home/joe/.local/lib/python3.6/site-packages (from Matplotlib>=2.1->object-detection==0.1) (1.17.4) Requirement already satisfied: cycler>=0.10 in /home/joe/.local/lib/python3.6/site-packages (from Matplotlib>=2.1->object-detection==0.1) (0.10.0) Requirement already satisfied: kiwisolver>=1.0.1 in /home/joe/.local/lib/python3.6/site-packages (from Matplotlib>=2.1->object-detection==0.1) (1.1.0) Requirement already satisfied: six>=1.5 in /home/joe/.local/lib/python3.6/site-packages (from python-dateutil>=2.1->Matplotlib>=2.1->object-detection==0.1) (1.13.0) Requirement already satisfied: setuptools in /home/joe/.local/lib/python3.6/site-packages (from kiwisolver>=1.0.1->Matplotlib>=2.1->object-detection==0.1) (42.0.2) Building wheels for collected packages: object-detection Building wheel for object-detection (setup.py): started Building wheel for object-detection (setup.py): finished with status 'done' Created wheel for object-detection: filename=object_detection-0.1-cp36-none-any.whl size=1018408 sha256=b7b6c58ff616468e23fbc4235cec9f629c4d20bbe64e97aa141002aabf96fcee Stored in directory: /tmp/pip-ephem-wheel-cache-27tuvthk/wheels/66/74/0f/57548ad5db5a02c1e963e016e857cda21c07d4640bd920543c Successfully built object-detection Installing collected packages: object-detection Successfully installed object-detection-0.1

Imports

 

 

 

import numpy as npimport osimport six.moves.urllib as urllibimport sysimport tarfileimport tensorflow as tfimport zipfilefrom collections import defaultdictfrom io import StringIOfrom matplotlib import pyplot as pltfrom PIL import Imagefrom IPython.display import display

 

Import the object detection module.

 

 

 

from object_detection.utils import ops as utils_opsfrom object_detection.utils import label_map_utilfrom object_detection.utils import visualization_utils as vis_util

 

Patches:

 

 

 

# patch tf1 into `utils.ops`utils_ops.tf = tf.compat.v1# Patch the location of gfiletf.gfile = tf.io.gfile

 

Model preparation

Variables

Any model exported using the export_inference_graph.py tool can be loaded here simply by changing the path.

By default we use an "SSD with Mobilenet" model here. See the detection model zoo for a list of other models that can be run out-of-the-box with varying speeds and accuracies.

Loader

 

 

 

def load_model(model_name): base_url = 'http://download.tensorflow.org/models/object_detection/' model_file = model_name + '.tar.gz' model_dir = tf.keras.utils.get_file( fname=model_name, origin=base_url + model_file, untar=True) model_dir = pathlib.Path(model_dir)/"saved_model" model = tf.saved_model.load(str(model_dir)) model = model.signatures['serving_default'] return model

 

Loading label map

Label maps map indices to category names, so that when our convolution network predicts 5, we know that this corresponds to airplane. Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine

 

 

 

 

# List of the strings that is used to add correct label for each box.PATH_TO_LABELS = 'models/research/object_detection/data/mscoco_label_map.pbtxt'category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)

 

For the sake of simplicity we will test on 2 images:

 

 

 

 

# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.PATH_TO_TEST_IMAGES_DIR = pathlib.Path('models/research/object_detection/test_images')TEST_IMAGE_PATHS = sorted(list(PATH_TO_TEST_IMAGES_DIR.glob("*.jpg")))TEST_IMAGE_PATHS

[PosixPath('models/research/object_detection/test_images/image1.jpg'), PosixPath('models/research/object_detection/test_images/image2.jpg')]

Detection

Load an object detection model:

 

 

 

model_name = 'ssd_mobilenet_v1_coco_2017_11_17'detection_model = load_model(model_name)

Downloading data from http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_coco_2017_11_17.tar.gz 76537856/76534733 [==============================] - 19s 0us/step INFO:tensorflow:Saver not created because there are no variables in the graph to restore

Check the model's input signature, it expects a batch of 3-color images of type uint8:

 

 

 

print(detection_model.inputs)

[<tf.Tensor 'image_tensor:0' shape=(None, None, None, 3) dtype=uint8>]

And retuns several outputs:

 

 

 

detection_model.output_dtypes

{'detection_scores': tf.float32, 'detection_classes': tf.float32, 'num_detections': tf.float32, 'detection_boxes': tf.float32}

 

 

 

detection_model.output_shapes

{'detection_scores': TensorShape([None, 100]), 'detection_classes': TensorShape([None, 100]), 'num_detections': TensorShape([None]), 'detection_boxes': TensorShape([None, 100, 4])}

Add a wrapper function to call the model, and cleanup the outputs:

 

 

 

def run_inference_for_single_image(model, image): image = np.asarray(image) # The input needs to be a tensor, convert it using `tf.convert_to_tensor`. input_tensor = tf.convert_to_tensor(image) # The model expects a batch of images, so add an axis with `tf.newaxis`. input_tensor = input_tensor[tf.newaxis,...] # Run inference output_dict = model(input_tensor) # All outputs are batches tensors. # Convert to numpy arrays, and take index [0] to remove the batch dimension. # We're only interested in the first num_detections. num_detections = int(output_dict.pop('num_detections')) output_dict = {key:value[0, :num_detections].numpy() for key,value in output_dict.items()} output_dict['num_detections'] = num_detections # detection_classes should be ints. output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64) # Handle models with masks: if 'detection_masks' in output_dict: # Reframe the the bbox mask to the image size. detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks( output_dict['detection_masks'], output_dict['detection_boxes'], image.shape[0], image.shape[1]) detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5, tf.uint8) output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy() return output_dict

 

Run it on each test image and show the results:

 

 

 

def show_inference(model, image_path): # the array based representation of the image will be used later in order to prepare the # result image with boxes and labels on it. image_np = np.array(Image.open(image_path)) # Actual detection. output_dict = run_inference_for_single_image(model, image_np) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, output_dict['detection_boxes'], output_dict['detection_classes'], output_dict['detection_scores'], category_index, instance_masks=output_dict.get('detection_masks_reframed', None), use_normalized_coordinates=True, line_thickness=8) display(Image.fromarray(image_np))

 

 

 

 

for image_path in TEST_IMAGE_PATHS: show_inference(detection_model, image_path)

Instance Segmentation

 

 

 

model_name = "mask_rcnn_inception_resnet_v2_atrous_coco_2018_01_28"masking_model = load_model("mask_rcnn_inception_resnet_v2_atrous_coco_2018_01_28")

INFO:tensorflow:Saver not created because there are no variables in the graph to restore

The instance segmentation model includes a detection_masks output:

 

 

 

masking_model.output_shapes

 

 

 

 

for image_path in TEST_IMAGE_PATHS: show_inference(masking_model, image_path)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형

'살며 생각하며,' 카테고리의 다른 글

개 발 일 지 061  (0) 2019.12.17
개 발 일 지 060  (0) 2019.12.13
개 발 일 지 058  (0) 2019.12.13
개 발 일 지 057  (0) 2019.12.13
개 발 일 지 056  (0) 2019.12.12
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기