File size: 11,839 Bytes
6d72a48 1e0c0b7 6d72a48 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from mask2former import Mask2Former\n",
"import torch as tr\n",
"import os\n",
"from datetime import datetime\n",
"import numpy as np\n",
"from PIL import Image\n",
"from vre.utils import (FFmpegVideo, collage_fn, semantic_mapper, FakeVideo,\n",
" colorize_semantic_segmentation, image_resize, image_write)\n",
"from pathlib import Path\n",
"import pandas as pd\n",
"from torchmetrics.functional.classification import multiclass_stat_scores\n",
"\n",
"%load_ext autoreload\n",
"%autoreload 2\n",
"%matplotlib inline"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mapi_mapping = {\n",
" \"land\": [\"Terrain\", \"Sand\", \"Snow\"],\n",
" \"forest\": [\"Vegetation\"],\n",
" \"residential\": [\"Building\", \"Utility Pole\", \"Pole\", \"Fence\", \"Wall\", \"Manhole\", \"Street Light\", \"Curb\",\n",
" \"Guard Rail\", \"Caravan\", \"Junction Box\", \"Traffic Sign (Front)\", \"Billboard\", \"Banner\",\n",
" \"Mailbox\", \"Traffic Sign (Back)\", \"Bench\", \"Fire Hydrant\", \"Trash Can\", \"CCTV Camera\",\n",
" \"Traffic Light\", \"Barrier\", \"Rail Track\", \"Phone Booth\", \"Curb Cut\", \"Traffic Sign Frame\",\n",
" \"Bike Rack\"],\n",
" \"road\": [\"Road\", \"Lane Marking - General\", \"Sidewalk\", \"Bridge\", \"Other Vehicle\", \"Motorcyclist\", \"Pothole\",\n",
" \"Catch Basin\", \"Car Mount\", \"Tunnel\", \"Parking\", \"Service Lane\", \"Lane Marking - Crosswalk\",\n",
" \"Pedestrian Area\", \"On Rails\", \"Bike Lane\", \"Crosswalk - Plain\"],\n",
" \"little-objects\": [\"Car\", \"Person\", \"Truck\", \"Boat\", \"Wheeled Slow\", \"Trailer\", \"Ground Animal\", \"Bicycle\",\n",
" \"Motorcycle\", \"Bird\", \"Bus\", \"Ego Vehicle\", \"Bicyclist\", \"Other Rider\"],\n",
" \"water\": [\"Water\"],\n",
" \"sky\": [\"Sky\"],\n",
" \"hill\": [\"Mountain\"]\n",
"}\n",
"\n",
"coco_mapping = {\n",
" \"land\": [\"grass-merged\", \"dirt-merged\", \"sand\", \"gravel\", \"flower\", \"playingfield\", \"snow\", \"platform\"],\n",
" \"forest\": [\"tree-merged\"],\n",
" \"residential\": [\"building-other-merged\", \"house\", \"roof\", \"fence-merged\", \"wall-other-merged\", \"wall-brick\",\n",
" \"rock-merged\", \"tent\", \"bridge\", \"bench\", \"window-other\", \"fire hydrant\", \"traffic light\",\n",
" \"umbrella\", \"wall-stone\", \"clock\", \"chair\", \"sports ball\", \"floor-other-merged\",\n",
" \"floor-wood\", \"stop sign\", \"door-stuff\", \"banner\", \"light\", \"net\", \"surfboard\", \"frisbee\",\n",
" \"rug-merged\", \"potted plant\", \"parking meter\", \"tennis racket\", \"sink\", \"hair drier\",\n",
" \"food-other-merged\", \"curtain\", \"mirror-stuff\", \"baseball glove\", \"baseball bat\", \"zebra\",\n",
" \"spoon\", \"towel\", \"donut\", \"apple\", \"handbag\", \"couch\", \"orange\", \"wall-wood\",\n",
" \"window-blind\", \"pizza\", \"cabinet-merged\", \"skateboard\", \"remote\", \"bottle\", \"bed\",\n",
" \"table-merged\", \"backpack\", \"bear\", \"wall-tile\", \"cup\", \"scissors\", \"ceiling-merged\",\n",
" \"oven\", \"cell phone\", \"microwave\", \"toaster\", \"carrot\", \"fork\", \"giraffe\", \"paper-merged\",\n",
" \"cat\", \"book\", \"sandwich\", \"wine glass\", \"pillow\", \"blanket\", \"tie\", \"bowl\", \"snowboard\",\n",
" \"vase\", \"toothbrush\", \"toilet\", \"dining table\", \"laptop\", \"tv\", \"cardboard\", \"keyboard\",\n",
" \"hot dog\", \"cake\", \"knife\", \"suitcase\", \"refrigerator\", \"fruit\", \"shelf\", \"counter\", \"skis\",\n",
" \"banana\", \"teddy bear\", \"broccoli\", \"mouse\"],\n",
" \"road\": [\"road\", \"railroad\", \"pavement-merged\", \"stairs\"],\n",
" \"little-objects\": [\"truck\", \"car\", \"boat\", \"horse\", \"person\", \"train\", \"elephant\", \"bus\", \"bird\", \"sheep\",\n",
" \"cow\", \"motorcycle\", \"dog\", \"bicycle\", \"airplane\", \"kite\"],\n",
" \"water\": [\"river\", \"water-other\", \"sea\"],\n",
" \"sky\": [\"sky-other-merged\"],\n",
" \"hill\": [\"mountain-merged\"]\n",
"}\n",
"\n",
"color_map = [[0, 255, 0], [0, 127, 0], [255, 255, 0], [255, 255, 255],\n",
" [255, 0, 0], [0, 0, 255], [0, 255, 255], [127, 127, 63]]\n",
"\n",
"def eval(y: np.ndarray, gt: np.ndarray) -> float:\n",
" tp, fp, _, fn = multiclass_stat_scores(tr.from_numpy(y), tr.from_numpy(gt), num_classes=8, average=None)[:, 0:4].T\n",
" iou = (tp / (tp + fp + fn)).nan_to_num(0, 0, 0)\n",
" weights = tr.FloatTensor([0.28172092, 0.30589653, 0.13341699, 0.05937348,\n",
" 0.00474491, 0.05987466, 0.08660721, 0.06836531])\n",
" iou_avg = (iou * weights).sum().item()\n",
" return iou_avg\n",
"\n",
"def collage_fn2(images: list[np.ndarray], size: tuple[int, int], **kwargs):\n",
" images_rsz = [image_resize(image, *size) for image in images]\n",
" return collage_fn(images_rsz, **kwargs)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"video = FFmpegVideo((\"/export/home/proiecte/aux/mihai_cristian.pirvu/datasets/dronescapes/raw_data/videos\"\n",
" \"/norway_210821_DJI_0015_full/DJI_0015.MP4\"))\n",
"gt_dir = (\"/export/home/proiecte/aux/mihai_cristian.pirvu/datasets/dronescapes/data/\"\n",
" \"test_set_annotated_only/semantic_segprop8/norway_210821_DJI_0015_full_\")\n",
"print(video)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_id = \"49189528_0\" # \"49189528_1\" (r50/mapillary), \"47429163_0\" (swin/coco), \"49189528_0\" (swin/mapillary)\n",
"os.environ[\"VRE_DEVICE\"] = device = \"cuda\" #\"cpu\"\n",
"os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"7\"\n",
"\n",
"m2f_1 = Mask2Former(model_id, disk_data_argmax=False, name=\"m2f\", dependencies=[])\n",
"m2f_2 = Mask2Former(\"47429163_0\", disk_data_argmax=False, name=\"m2f\", dependencies=[])\n",
"m2f_3 = Mask2Former(\"49189528_1\", disk_data_argmax=False, name=\"m2f\", dependencies=[])\n",
"\n",
"m2f_1.device = \"cuda\" if tr.cuda.is_available() else \"cpu\"\n",
"m2f_2.device = \"cuda\" if tr.cuda.is_available() else \"cpu\"\n",
"m2f_3.device = \"cuda\" if tr.cuda.is_available() else \"cpu\"\n",
"\n",
"metrics = {}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"frame_ix = 900\n",
"def load_gt(ix: int) -> np.ndarray:\n",
" gt_path = f\"{gt_dir}{ix}.npz\"\n",
" assert Path(gt_path).exists(), gt_path\n",
" gt_data = np.load(gt_path)[\"arr_0\"]\n",
" return gt_data\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def m2f_do_one(m2f: Mask2Former, frame: np.ndarray, gt_data_shape, mapping: dict) -> tuple[np.ndarray, np.ndarray]:\n",
" m2f_1.vre_free() if m2f_1.setup_called and id(m2f) != id(m2f_1) else None\n",
" m2f_2.vre_free() if m2f_2.setup_called and id(m2f) != id(m2f_1) else None\n",
" m2f_3.vre_free() if m2f_3.setup_called and id(m2f) != id(m2f_1) else None\n",
" m2f.vre_setup() if not m2f.setup_called else None\n",
"\n",
" now = datetime.now()\n",
" m2f.data = None\n",
" m2f.compute(FakeVideo(frame[None], fps=1), [0])\n",
" print(f\"Pred took: {datetime.now() - now}\"); now = datetime.now()\n",
" m2f_mapped = semantic_mapper(m2f.data.output.argmax(-1)[0], mapping, m2f.classes)\n",
" m2f_mapped = image_resize(m2f_mapped, *gt_data_shape, interpolation=\"nearest\")\n",
" print(f\"semantic_mapper took: {datetime.now() - now}\"); now = datetime.now()\n",
" m2f_colorized = colorize_semantic_segmentation(m2f_mapped[None], list(mapping), color_map, rgb=rgb_rsz[None])[0]\n",
" print(f\"colorize took: {datetime.now() - now}\"); now = datetime.now()\n",
" return m2f_mapped, m2f_colorized\n",
"\n",
"def eval_and_store(frame, frame_ix, res_all: list[tuple[np.ndarray], np.ndarray], gt_color: np.ndarray,\n",
" columns: list[str]):\n",
" collage_data = []\n",
" for item in res_all:\n",
" collage_data.extend([frame, item[1], gt_color])\n",
" clg = collage_fn2(collage_data, size=gt_color.shape[0:2], rows_cols=(-1, 3))\n",
" image_write(clg, f\"collage_{frame_ix}.png\")\n",
" display(Image.fromarray(clg))\n",
" evals = [eval(item[0], gt_data) for item in res_all]\n",
"\n",
" try:\n",
" metrics = pd.read_csv(\"metrics.csv\", index_col=0)\n",
" except Exception as e:\n",
" metrics = pd.DataFrame(None, columns=columns)\n",
"\n",
" metrics.loc[frame_ix] = evals\n",
" display(metrics.sort_index())\n",
" metrics.to_csv(\"metrics.csv\")\n",
"\n",
"for frame_ix in [60, 120, 300, 600, 900, 1200, 1500]:\n",
" frame, gt_data = video[frame_ix], load_gt(frame_ix)\n",
" rgb_rsz = image_resize(frame, *gt_data.shape)\n",
" gt_color = colorize_semantic_segmentation(gt_data[None], classes=list(mapi_mapping), color_map=color_map,\n",
" rgb=rgb_rsz[None])[0]\n",
" mapped1, colorized1 = m2f_do_one(m2f_1, frame, gt_data.shape, mapi_mapping)\n",
" mapped2, colorized2 = m2f_do_one(m2f_2, frame, gt_data.shape, coco_mapping)\n",
" mapped3, colorized3 = m2f_do_one(m2f_3, frame, gt_data.shape, mapi_mapping)\n",
"\n",
" mapped1_rsz, colorized1_rsz = m2f_do_one(m2f_1, rgb_rsz, gt_data.shape, mapi_mapping)\n",
" mapped2_rsz, colorized2_rsz = m2f_do_one(m2f_2, rgb_rsz, gt_data.shape, coco_mapping)\n",
" mapped3_rsz, colorized3_rsz = m2f_do_one(m2f_3, rgb_rsz, gt_data.shape, mapi_mapping)\n",
"\n",
" all_res = [\n",
" (mapped1, colorized1), (mapped2, colorized2), (mapped3, colorized3),\n",
" (mapped1_rsz, colorized1_rsz), (mapped2_rsz, colorized2_rsz), (mapped3_rsz, colorized3_rsz),\n",
" ]\n",
" columns = [\"swin_mapillary\", \"swin_coco\", \"r50_mapillary\",\n",
" \"swin_mapillary_rsz\", \"swin_coco_rsz\", \"r50_mapillary_rsz\"]\n",
"\n",
" eval_and_store(frame, frame_ix, all_res, gt_color, columns)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "ngc",
"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.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|