{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Mask R-CNN Demo\n", "\n", "Demo of object detection" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Download code from github" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#!git clone https://github.com/matterport/Mask_RCNN.git\n", "!pip3 install -U cython\n", "!pip3 install pycocotools\n", "!pip3 install imgaug" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Import and setting the path" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import sys\n", "import random\n", "import math\n", "import numpy as np\n", "import skimage.io\n", "import matplotlib\n", "import matplotlib.pyplot as plt\n", "\n", "# Root directory of the project\n", "ROOT_DIR = os.path.abspath(\"Mask_RCNN/\")\n", "\n", "# Import Mask RCNN\n", "sys.path.append(ROOT_DIR) # To find local version of the library\n", "from mrcnn import utils\n", "import mrcnn.model as modellib\n", "from mrcnn import visualize\n", "# Import COCO config\n", "sys.path.append(os.path.join(ROOT_DIR, \"samples/coco/\")) # To find local version\n", "import coco\n", "\n", "%matplotlib inline \n", "\n", "# Directory to save logs and trained model\n", "MODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\n", "\n", "# Local path to trained weights file\n", "COCO_MODEL_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n", "# Download COCO trained weights from Releases if needed\n", "if not os.path.exists(COCO_MODEL_PATH):\n", " utils.download_trained_weights(COCO_MODEL_PATH)\n", "\n", "# Directory of images to run detection on\n", "IMAGE_DIR = os.path.join(ROOT_DIR, \"images\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Configurations\n", "\n", "We'll be using a model trained on the MS-COCO dataset. The configurations of this model are in the ```CocoConfig``` class in ```coco.py```.\n", "\n", "For inferencing, modify the configurations a bit to fit the task. To do so, sub-class the ```CocoConfig``` class and override the attributes you need to change." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class InferenceConfig(coco.CocoConfig):\n", " # Set batch size to 1 since we'll be running inference on\n", " # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n", " GPU_COUNT = 1\n", " IMAGES_PER_GPU = 1\n", "\n", "config = InferenceConfig()\n", "config.display()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create Model and Load Trained Weights" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "# Create model object in inference mode.\n", "model = modellib.MaskRCNN(mode=\"inference\", model_dir=MODEL_DIR, config=config)\n", "\n", "# Load weights trained on MS-COCO\n", "model.load_weights(COCO_MODEL_PATH, by_name=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Class Names\n", "\n", "The model classifies objects and returns class IDs, which are integer value that identify each class. Some datasets assign integer values to their classes and some don't. For example, in the MS-COCO dataset, the 'person' class is 1 and 'teddy bear' is 88. The IDs are often sequential, but not always. The COCO dataset, for example, has classes associated with class IDs 70 and 72, but not 71.\n", "\n", "To improve consistency, and to support training on data from multiple sources at the same time, our ```Dataset``` class assigns it's own sequential integer IDs to each class. For example, if you load the COCO dataset using our ```Dataset``` class, the 'person' class would get class ID = 1 (just like COCO) and the 'teddy bear' class is 78 (different from COCO). Keep that in mind when mapping class IDs to class names.\n", "\n", "To get the list of class names, you'd load the dataset and then use the ```class_names``` property like this.\n", "```\n", "# Load COCO dataset\n", "dataset = coco.CocoDataset()\n", "dataset.load_coco(COCO_DIR, \"train\")\n", "dataset.prepare()\n", "\n", "# Print class names\n", "print(dataset.class_names)\n", "```\n", "\n", "We don't want to require you to download the COCO dataset just to run this demo, so we're including the list of class names below. The index of the class name in the list represent its ID (first class is 0, second is 1, third is 2, ...etc.)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# COCO Class names\n", "# Index of the class in the list is its ID. For example, to get ID of\n", "# the teddy bear class, use: class_names.index('teddy bear')\n", "class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',\n", " 'bus', 'train', 'truck', 'boat', 'traffic light',\n", " 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',\n", " 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',\n", " 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',\n", " 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\n", " 'kite', 'baseball bat', 'baseball glove', 'skateboard',\n", " 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',\n", " 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',\n", " 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\n", " 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',\n", " 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',\n", " 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',\n", " 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',\n", " 'teddy bear', 'hair drier', 'toothbrush']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Run Object Detection\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "# Load a random image from the images folder\n", "file_names = next(os.walk(IMAGE_DIR))[2]\n", "image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))\n", "\n", "# Run detection\n", "results = model.detect([image], verbose=1)\n", "\n", "# Visualize results\n", "r = results[0]\n", "visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], \n", " class_names, r['scores'])" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## Task\n", "\n", "1. Let's test the network with another image! " ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.12" } }, "nbformat": 4, "nbformat_minor": 2 }