move colormap to config

This commit is contained in:
Blake Blackshear 2021-08-16 08:02:04 -05:00
parent bbf0fc8324
commit 1c85f774eb
3 changed files with 30 additions and 22 deletions

View File

@ -1,18 +1,18 @@
from __future__ import annotations from __future__ import annotations
from enum import Enum
import json import json
import logging import logging
import os import os
from enum import Enum
from typing import Dict, List, Optional, Tuple, Union from typing import Dict, List, Optional, Tuple, Union
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
import yaml
from pydantic import BaseModel, Field, validator from pydantic import BaseModel, Field, validator
from pydantic.fields import PrivateAttr from pydantic.fields import PrivateAttr
import yaml
from frigate.const import BASE_DIR, RECORD_DIR, CACHE_DIR from frigate.const import BASE_DIR, CACHE_DIR, RECORD_DIR
from frigate.edgetpu import load_labels from frigate.edgetpu import load_labels
from frigate.util import create_mask, deep_merge from frigate.util import create_mask, deep_merge
@ -578,11 +578,16 @@ class ModelConfig(BaseModel):
default_factory=dict, title="Labelmap customization." default_factory=dict, title="Labelmap customization."
) )
_merged_labelmap: Optional[Dict[int, str]] = PrivateAttr() _merged_labelmap: Optional[Dict[int, str]] = PrivateAttr()
_colormap: Dict[int, Tuple[int, int, int]] = PrivateAttr()
@property @property
def merged_labelmap(self) -> Dict[int, str]: def merged_labelmap(self) -> Dict[int, str]:
return self._merged_labelmap return self._merged_labelmap
@property
def colormap(self) -> Dict[int, tuple[int, int, int]]:
return self._colormap
def __init__(self, **config): def __init__(self, **config):
super().__init__(**config) super().__init__(**config)
@ -591,6 +596,12 @@ class ModelConfig(BaseModel):
**config.get("labelmap", {}), **config.get("labelmap", {}),
} }
cmap = plt.cm.get_cmap("tab10", len(self._merged_labelmap.keys()))
self._colormap = {}
for key, val in self._merged_labelmap.items():
self._colormap[val] = tuple(int(round(255 * c)) for c in cmap(key)[:3])
class LogLevelEnum(str, Enum): class LogLevelEnum(str, Enum):
debug = "debug" debug = "debug"

View File

@ -1,5 +1,5 @@
import copy
import base64 import base64
import copy
import datetime import datetime
import hashlib import hashlib
import itertools import itertools
@ -14,30 +14,20 @@ from statistics import mean, median
from typing import Callable, Dict from typing import Callable, Dict
import cv2 import cv2
import matplotlib.pyplot as plt
import numpy as np import numpy as np
from frigate.config import FrigateConfig, CameraConfig from frigate.config import CameraConfig, FrigateConfig
from frigate.const import RECORD_DIR, CLIPS_DIR, CACHE_DIR from frigate.const import CACHE_DIR, CLIPS_DIR, RECORD_DIR
from frigate.edgetpu import load_labels from frigate.edgetpu import load_labels
from frigate.util import ( from frigate.util import (
SharedMemoryFrameManager, SharedMemoryFrameManager,
calculate_region,
draw_box_with_label, draw_box_with_label,
draw_timestamp, draw_timestamp,
calculate_region,
) )
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
PATH_TO_LABELS = "/labelmap.txt"
LABELS = load_labels(PATH_TO_LABELS)
cmap = plt.cm.get_cmap("tab10", len(LABELS.keys()))
COLOR_MAP = {}
for key, val in LABELS.items():
COLOR_MAP[val] = tuple(int(round(255 * c)) for c in cmap(key)[:3])
def on_edge(box, frame_shape): def on_edge(box, frame_shape):
if ( if (
@ -72,9 +62,12 @@ def is_better_thumbnail(current_thumb, new_obj, frame_shape) -> bool:
class TrackedObject: class TrackedObject:
def __init__(self, camera, camera_config: CameraConfig, frame_cache, obj_data): def __init__(
self, camera, colormap, camera_config: CameraConfig, frame_cache, obj_data
):
self.obj_data = obj_data self.obj_data = obj_data
self.camera = camera self.camera = camera
self.colormap = colormap
self.camera_config = camera_config self.camera_config = camera_config
self.frame_cache = frame_cache self.frame_cache = frame_cache
self.current_zones = [] self.current_zones = []
@ -247,7 +240,7 @@ class TrackedObject:
if bounding_box: if bounding_box:
thickness = 2 thickness = 2
color = COLOR_MAP[self.obj_data["label"]] color = self.colormap[self.obj_data["label"]]
# draw the bounding boxes on the frame # draw the bounding boxes on the frame
box = self.thumbnail_data["box"] box = self.thumbnail_data["box"]
@ -357,7 +350,7 @@ class CameraState:
for obj in tracked_objects.values(): for obj in tracked_objects.values():
if obj["frame_time"] == frame_time: if obj["frame_time"] == frame_time:
thickness = 2 thickness = 2
color = COLOR_MAP[obj["label"]] color = self.config.model.colormap[obj["label"]]
else: else:
thickness = 1 thickness = 1
color = (255, 0, 0) color = (255, 0, 0)
@ -448,7 +441,11 @@ class CameraState:
for id in new_ids: for id in new_ids:
new_obj = tracked_objects[id] = TrackedObject( new_obj = tracked_objects[id] = TrackedObject(
self.name, self.camera_config, self.frame_cache, current_detections[id] self.name,
self.config.model.colormap,
self.camera_config,
self.frame_cache,
current_detections[id],
) )
# call event handlers # call event handlers

View File

@ -14,7 +14,7 @@ import numpy as np
from frigate.config import FRIGATE_CONFIG_SCHEMA, FrigateConfig from frigate.config import FRIGATE_CONFIG_SCHEMA, FrigateConfig
from frigate.edgetpu import LocalObjectDetector from frigate.edgetpu import LocalObjectDetector
from frigate.motion import MotionDetector from frigate.motion import MotionDetector
from frigate.object_processing import COLOR_MAP, CameraState from frigate.object_processing import CameraState
from frigate.objects import ObjectTracker from frigate.objects import ObjectTracker
from frigate.util import ( from frigate.util import (
DictFrameManager, DictFrameManager,