2024-07-29 21:54:20 +00:00
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "5fa21d44",
"metadata": {},
"outputs": [],
"source": [
"# Copyright (c) Meta Platforms, Inc. and affiliates.\n",
"# Lightly adapted from https://github.com/facebookresearch/segment-anything/blob/main/notebooks/automatic_mask_generator_example.ipynb"
]
},
{
"cell_type": "markdown",
"id": "b7c0041e",
"metadata": {},
"source": [
"# Automatically generating object masks with SAM"
]
},
{
"cell_type": "markdown",
"id": "289bb0b4",
"metadata": {},
"source": [
"Since SAM 2 can efficiently process prompts, masks for the entire image can be generated by sampling a large number of prompts over an image.\n",
"\n",
"The class `SAM2AutomaticMaskGenerator` implements this capability. It works by sampling single-point input prompts in a grid over the image, from each of which SAM can predict multiple masks. Then, masks are filtered for quality and deduplicated using non-maximal suppression. Additional options allow for further improvement of mask quality and quantity, such as running prediction on multiple crops of the image or postprocessing masks to remove small disconnected regions and holes."
]
},
2024-08-08 11:03:22 -07:00
{
"cell_type": "markdown",
"id": "4290fb06-a63f-4624-a70c-f7c9aae4b5d5",
"metadata": {},
"source": [
"<a target=\"_blank\" href=\"https://colab.research.google.com/github/facebookresearch/segment-anything-2/blob/main/notebooks/automatic_mask_generator_example.ipynb\">\n",
" <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
"</a>"
]
},
2024-07-29 21:54:20 +00:00
{
"cell_type": "markdown",
"id": "c0b71431",
"metadata": {},
"source": [
"## Environment Set-up"
]
},
{
"cell_type": "markdown",
"id": "47e5a78f",
"metadata": {},
"source": [
2024-08-08 11:03:22 -07:00
"If running locally using jupyter, first install `SAM 2` in your environment using the installation instructions in the repository.\n",
"\n",
"If running from Google Colab, set `using_colab=True` below and run the cell. In Colab, be sure to select 'GPU' under 'Edit'->'Notebook Settings'->'Hardware accelerator'. Note that it's recommended to use **A100 or L4 GPUs when running in Colab** (T4 GPUs might also work, but could be slow and might run out of memory in some cases)."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "a941fd2f-a960-4e5f-916b-a5a385bf3a37",
"metadata": {},
"outputs": [],
"source": [
"using_colab = False"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "c3e9a446-0d12-4b6f-ba93-03fe7453ace7",
"metadata": {},
"outputs": [],
"source": [
"if using_colab:\n",
" import torch\n",
" import torchvision\n",
" print(\"PyTorch version:\", torch.__version__)\n",
" print(\"Torchvision version:\", torchvision.__version__)\n",
" print(\"CUDA is available:\", torch.cuda.is_available())\n",
" import sys\n",
" !{sys.executable} -m pip install opencv-python matplotlib\n",
" !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/segment-anything-2.git'\n",
"\n",
" !mkdir -p images\n",
" !wget -P images https://raw.githubusercontent.com/facebookresearch/segment-anything-2/main/notebooks/images/cars.jpg\n",
"\n",
" !mkdir -p ../checkpoints/\n",
" !wget -P ../checkpoints/ https://dl.fbaipublicfiles.com/segment_anything_2/072824/sam2_hiera_large.pt"
2024-07-29 21:54:20 +00:00
]
},
{
"cell_type": "markdown",
"id": "fd2bc687",
"metadata": {},
"source": [
"## Set-up"
]
},
{
"cell_type": "code",
2024-08-08 11:03:22 -07:00
"execution_count": 4,
2024-07-29 21:54:20 +00:00
"id": "560725a2",
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import torch\n",
"import matplotlib.pyplot as plt\n",
"from PIL import Image\n",
"\n",
"# use bfloat16 for the entire notebook\n",
"torch.autocast(device_type=\"cuda\", dtype=torch.bfloat16).__enter__()\n",
"\n",
"if torch.cuda.get_device_properties(0).major >= 8:\n",
" # turn on tfloat32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices)\n",
" torch.backends.cuda.matmul.allow_tf32 = True\n",
" torch.backends.cudnn.allow_tf32 = True"
]
},
{
"cell_type": "code",
2024-08-08 11:03:22 -07:00
"execution_count": 5,
2024-07-29 21:54:20 +00:00
"id": "74b6e5f0",
"metadata": {},
"outputs": [],
"source": [
"def show_anns(anns, borders=True):\n",
" if len(anns) == 0:\n",
" return\n",
" sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True)\n",
" ax = plt.gca()\n",
" ax.set_autoscale_on(False)\n",
"\n",
" img = np.ones((sorted_anns[0]['segmentation'].shape[0], sorted_anns[0]['segmentation'].shape[1], 4))\n",
2024-08-08 11:03:22 -07:00
" img[:, :, 3] = 0\n",
2024-07-29 21:54:20 +00:00
" for ann in sorted_anns:\n",
" m = ann['segmentation']\n",
" color_mask = np.concatenate([np.random.random(3), [0.5]])\n",
" img[m] = color_mask \n",
" if borders:\n",
" import cv2\n",
2024-08-08 11:03:22 -07:00
" contours, _ = cv2.findContours(m.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) \n",
2024-07-29 21:54:20 +00:00
" # Try to smooth contours\n",
" contours = [cv2.approxPolyDP(contour, epsilon=0.01, closed=True) for contour in contours]\n",
2024-08-08 11:03:22 -07:00
" cv2.drawContours(img, contours, -1, (0, 0, 1, 0.4), thickness=1) \n",
2024-07-29 21:54:20 +00:00
"\n",
" ax.imshow(img)"
]
},
{
"cell_type": "markdown",
"id": "27c41445",
"metadata": {},
"source": [
"## Example image"
]
},
{
"cell_type": "code",
2024-08-08 11:03:22 -07:00
"execution_count": 6,
2024-07-29 21:54:20 +00:00
"id": "ad354922",
"metadata": {},
"outputs": [],
"source": [
"image = Image.open('images/cars.jpg')\n",
"image = np.array(image.convert(\"RGB\"))"
]
},
{
"cell_type": "code",
2024-08-08 11:03:22 -07:00
"execution_count": 7,
2024-07-29 21:54:20 +00:00
"id": "e0ac8c67",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABiIAAAQdCAYAAADTkVDqAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/TGe4hAAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQV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Jz0SgPEkvehHie8xm007ZMnvqTsQzbmw00xtdfIPRvAYm3MpNG11APZ7f1eXgVLr2qfEbzIvyXwzeMvb2xv2fT+tK2T4PLfLuuLPeFemwfmZsHFrwRA7Jgl2kJ5TSoGOgcqUdFtf+5D576wD5fMJnVxEpi08dRy1u/dBTsiZ54xhPHB/7lOHu+oysTYAaNuGoy89Pnh03JXTOtTphABKz1ySwfSCbDeUWtGPY+o2Wd7kswxZGvw+85PQ5a/2RD7XkFN5DzMdBx/L+8TMUxfJ+u2kiWPx76uueaWrKy3lz2TZE/zKbP3zfVVVVOKTzMq8ND4rIii1GsaVRn7PdY6xL3nEXE/nDIAdQ5r3zfHdqQv2RUv5XXktJfHHaV9hnO5wlhV5j/O6s30yaczl1PWu5u/G3LKcP/GyJDMznWS6/OxM493xjqlLiNm3Md/4fO8dxARJdLNVX7PjkZnOF56WePYnP7/ywLw3WS+K9f0//x//9w/7+Nn4zY4IckKFKjQuLgAuDKoG6HMt6EdHKwVkKC80QFEA5IotEaOQbZKogFAALkAtoFJArYJgTABUULl67gaBREBS3QFijgmqBQxGLRUYCh4CHh1cCKWVCTQQmyAnZgxSoFaoErhUKNSYfGvAGFAHsKS7UqLmuNjaBpCBxrUZ4wkC4RAsrrAQmzP
"text/plain": [
"<Figure size 2000x2000 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
2024-08-08 11:03:22 -07:00
"plt.figure(figsize=(20, 20))\n",
2024-07-29 21:54:20 +00:00
"plt.imshow(image)\n",
"plt.axis('off')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "b8c2824a",
"metadata": {},
"source": [
"## Automatic mask generation"
]
},
{
"cell_type": "markdown",
"id": "d9ef74c5",
"metadata": {},
"source": [
"To run automatic mask generation, provide a version of SAM 2 to the `SAM2AutomaticMaskGenerator` class. Set the path below to the SAM 2 checkpoint."
]
},
{
"cell_type": "code",
2024-08-08 11:03:22 -07:00
"execution_count": 8,
2024-07-29 21:54:20 +00:00
"id": "1848a108",
"metadata": {},
"outputs": [],
"source": [
"from sam2.build_sam import build_sam2\n",
"from sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator\n",
"\n",
"sam2_checkpoint = \"../checkpoints/sam2_hiera_large.pt\"\n",
"model_cfg = \"sam2_hiera_l.yaml\"\n",
"\n",
2024-08-08 11:03:22 -07:00
"sam2 = build_sam2(model_cfg, sam2_checkpoint, device='cuda', apply_postprocessing=False)\n",
2024-07-29 21:54:20 +00:00
"\n",
"mask_generator = SAM2AutomaticMaskGenerator(sam2)"
]
},
{
"cell_type": "markdown",
"id": "d6b1ea21",
"metadata": {},
"source": [
"To generate masks, just run `generate` on an image."
]
},
{
"cell_type": "code",
2024-08-08 11:03:22 -07:00
"execution_count": 9,
2024-07-29 21:54:20 +00:00
"id": "391771c1",
"metadata": {},
"outputs": [],
"source": [
"masks = mask_generator.generate(image)"
]
},
{
"cell_type": "markdown",
"id": "e36a1a39",
"metadata": {},
"source": [
"Mask generation returns a list over masks, where each mask is a dictionary containing various data about the mask. These keys are:\n",
"* `segmentation` : the mask\n",
"* `area` : the area of the mask in pixels\n",
"* `bbox` : the boundary box of the mask in XYWH format\n",
"* `predicted_iou` : the model's own prediction for the quality of the mask\n",
"* `point_coords` : the sampled input point that generated this mask\n",
"* `stability_score` : an additional measure of mask quality\n",
"* `crop_box` : the crop of the image used to generate this mask in XYWH format"
]
},
{
"cell_type": "code",
2024-08-08 11:03:22 -07:00
"execution_count": 10,
2024-07-29 21:54:20 +00:00
"id": "4fae8d66",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2024-08-08 11:03:22 -07:00
"59\n",
2024-07-29 21:54:20 +00:00
"dict_keys(['segmentation', 'area', 'bbox', 'predicted_iou', 'point_coords', 'stability_score', 'crop_box'])\n"
]
}
],
"source": [
"print(len(masks))\n",
"print(masks[0].keys())"
]
},
{
"cell_type": "markdown",
"id": "53009a1f",
"metadata": {},
"source": [
"Show all the masks overlayed on the image."
]
},
{
"cell_type": "code",
2024-08-08 11:03:22 -07:00
"execution_count": 11,
2024-07-29 21:54:20 +00:00
"id": "77ac29c5",
"metadata": {},
"outputs": [
{
"data": {
2024-08-08 11:03:22 -07:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAABiIAAAQdCAYAAADTkVDqAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/TGe4hAAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOz9WbNtW3Iehn05xlxr73PPbarqVt8ChaaKKBCdCAgMiBJBWZIZ4gMVIb35wRF+tR8c4R/jJ/sn6MUhhmUGHRQFI0iKICGCaIlqgGpQqEJ1tzln7zXHSD9kfpk55l4XuHxAOMKxZsWtvc9ec805Ro4cmV+2Q1RVcbtu1+26Xbfrdt2u23W7btftul2363bdrtt1u27X7bpdt+t23a7b9ddwtf9fD+B23a7bdbtu1+26Xbfrdt2u23W7btftul2363bdrtt1u27X7bpd//973QIRt+t23a7bdbtu1+26Xbfrdt2u23W7btftul2363bdrtt1u27X7fpru26BiNt1u27X7bpdt+t23a7bdbtu1+26Xbfrdt2u23W7btftul2363b9tV23QMTtul2363bdrtt1u27X7bpdt+t23a7bdbtu1+26Xbfrdt2u23W7/tquWyDidt2u23W7btftul2363bdrtt1u27X7bpdt+t23a7bdbtu1+26XX9t1y0Qcbtu1+26Xbfrdt2u23W7btftul2363bdrtt1u27X7bpdt+t23a6/tusWiLhdt+t23a7bdbtu1+26Xbfrdt2u23W7btftul2363bdrtt1u27XX9t1C0Tcrtt1u27X7bpdt+t23a7bdbtu1+26Xbfrdt2u23W7btftul2366/tugUibtftul2363bdrtt1u27X7bpdt+t23a7bdbtu1+26Xbfrdt2u2/XXdm3v98ZP/ur/Cb/23/0OAKCJQFUhTQAIIAIRQFUBACINUGA+7pA58dqrz/Dqq88gAH74w7fw8sVL7PsOTLsfraGdNmDbgN4hrcEfC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lb17mJyQqRh7sMwq90c+7Q5j885cT6fgxcXXmhJ1ylAB+k4AElMN6ln1P04SAxj8nAGzbneqoDO1HvbtgU/HHV+2tyAdGDMEWtOOalzmq+o4qMi91oze2LM1N+BHURiLM15ZjttIT8aKGNszL27rUZ5B9rlin0O9G1b8GXlNY6ryk3KlmfPnuHx8XGZF3V4rNthXmHbFuxYdb6ImO9oTrStY0y3bSkOynN679AxsDVZ7VIAOuaCm1Nu5/oY/5oOk0ZMTB+Jhk2+6Im5ypwxTAY+PjwGhjtiGc4NAE7nMy77ZdFTxAGU4zEPdT4R8/UFlir7v8nBDtw27G5jYa46qK4ldSnlfZUnxPLk84r5wtfneqrSsPIx5VilU2stsEjFt8ETl5TfR6x55KsjL9V7qu6hvBKRJ/tVVbFJW3RWlaW8d86Jvm0Yusre+p7jGEmXenGsyzoDaO5Div0mZjMGFtyTl+q76lx6kY9hX2Ese7jqikrjOu9qnwSPuZ467tX6XY6t6vlFlunqp6nvr+M7rinfzXcElpjFb1j4a993SBPz3fn7zlsLWxllzSoG5fO//DsfxKe+9CLGdnnZsT003H/grUUGVtpUXMT5/V/+4a8+oeO1630HIgjQ6TgLUNEknEICOgWoKPy/4vAJcOLOBgPRoLfIHBHdjKQ5J9DcWcFHqkK1QegsVQVaMzDXmgmdrhA9KAAfjy2aYgoAV8LmhHfHbbdn0IFlvw/QoOwBJFJQHIUCHKgbfkynjUKL5wj+FzpcSKXigBLyS3H8SDpY47kuoKU5DSeANp3+4YmDqISjhuSbSZhcG4VJBXcm8b1CZ0PMvwPSIE3RegshoEPRujv/RZZ5T6clAANlPnYF0PrmASH
2024-07-29 21:54:20 +00:00
"text/plain": [
"<Figure size 2000x2000 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
2024-08-08 11:03:22 -07:00
"plt.figure(figsize=(20, 20))\n",
2024-07-29 21:54:20 +00:00
"plt.imshow(image)\n",
"show_anns(masks)\n",
"plt.axis('off')\n",
"plt.show() "
]
},
{
"cell_type": "markdown",
"id": "00b3d6b2",
"metadata": {},
"source": [
"## Automatic mask generation options"
]
},
{
"cell_type": "markdown",
"id": "183de84e",
"metadata": {},
"source": [
"There are several tunable parameters in automatic mask generation that control how densely points are sampled and what the thresholds are for removing low quality or duplicate masks. Additionally, generation can be automatically run on crops of the image to get improved performance on smaller objects, and post-processing can remove stray pixels and holes. Here is an example configuration that samples more masks:"
]
},
{
"cell_type": "code",
2024-08-08 11:03:22 -07:00
"execution_count": 12,
2024-07-29 21:54:20 +00:00
"id": "68364513",
"metadata": {},
"outputs": [],
"source": [
"mask_generator_2 = SAM2AutomaticMaskGenerator(\n",
" model=sam2,\n",
" points_per_side=64,\n",
" points_per_batch=128,\n",
" pred_iou_thresh=0.7,\n",
" stability_score_thresh=0.92,\n",
" stability_score_offset=0.7,\n",
" crop_n_layers=1,\n",
" box_nms_thresh=0.7,\n",
" crop_n_points_downscale_factor=2,\n",
" min_mask_region_area=25.0,\n",
" use_m2m=True,\n",
")"
]
},
{
"cell_type": "code",
2024-08-08 11:03:22 -07:00
"execution_count": 13,
2024-07-29 21:54:20 +00:00
"id": "bebcdaf1",
"metadata": {},
"outputs": [],
"source": [
2024-08-08 11:03:22 -07:00
"masks2 = mask_generator_2.generate(image)"
2024-07-29 21:54:20 +00:00
]
},
{
"cell_type": "code",
2024-08-08 11:03:22 -07:00
"execution_count": 14,
2024-07-29 21:54:20 +00:00
"id": "fb702ae3",
"metadata": {},
"outputs": [
{
"data": {
2024-08-08 11:03:22 -07:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAABiIAAAQdCAYAAADTkVDqAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/TGe4hAAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOz9WbN2y3EeiD1Ztd69v+FMwJlwME8kAQKkRKolWep2d3sKd4ds2WE5+tf41v/CEb5whDvsCN/0hSW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LcG4AcLq6wnk/L3aKOIB6PObhsTKI+aKBpYr80xcPP3DbsJ/PgW2qvalrSVtKfV/1CbE8+bxiPtKDdqrSsPIx9VilU2stsEjFt8ET59TfR6x55KsjL9V7qu2hvhKRO/KqqtikLTar6lLea7GNDUNX3Vvfcxwj6VIvjnVZZwDNY0ghb4KIOagqdE9equ+qc+lFP4Z/hbHIcLUVlcZ13vf5gbRTR1mt3+XYqp1fdFmxmZVPKl/et6Z8N98RWGJ6vF0yrhPjbIJZ+OZqaxFfgiq21vCnX3sXn/3Nf7noprpOx8+PeLTee8TT3/jv/0f4P/7v/94dOt53fehEBAE6YIFIiDvuTTzIbUZzTDOgEVBwp+DRS4p3sUGkAdIsmRHuvwuLB6DRmgU+XPk0aTXaAdFWggYMakkQWFQhrlQtSbAzTmoBCx87fNwiBminfwYKVmcwdfj8G966mvjmOw0iqShyASyQS+NGg0EAZgmQHHdVpHmti5uBiZKQcdxfXQBpDegeLFY1Ghp+tfn5vKQdlIhH4zWAoyWRIBa05Gio6G3stua9d0AapJkQ9c2CtDosMNBa82c
2024-07-29 21:54:20 +00:00
"text/plain": [
"<Figure size 2000x2000 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
2024-08-08 11:03:22 -07:00
"plt.figure(figsize=(20, 20))\n",
2024-07-29 21:54:20 +00:00
"plt.imshow(image)\n",
"show_anns(masks2)\n",
"plt.axis('off')\n",
"plt.show() "
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.14"
}
},
"nbformat": 4,
"nbformat_minor": 5
}