utils.py 10.6 KB
Newer Older
1 2 3 4
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
"""
5 6 7 8
    Generic utilities classes.
    
    Name: main.py
    Author: Alessandro dos Santos Ferreira ( santosferreira.alessandro@gmail.com )
9
"""
10
import cv2
11
import random
12
import time
13 14
from sklearn.metrics import confusion_matrix
import numpy as np
15

16
class ColorUtils(object):
17
    """Set of utilities to manipulate colors."""
18 19 20

    @staticmethod
    def rand_color():
21 22 23 24 25 26 27
        """Return a random color.
        
        Returns
        -------
        color : string
            Color in format #FFFFFF.
        """
28 29
        r = random.randint
        
30 31
        return '#%02X%02X%02X' % (r(0, 255), r(0, 255), r(0, 255))
        
32 33

class ImageUtils(object):
34
    """Set of utilities to manipulate images."""
35 36 37
    
    @staticmethod
    def image_to_bgr(image):
38 39 40 41 42 43 44 45 46 47 48 49
        """Convert a image to BGR.
        
        Parameters
        ----------
        image : opencv RGB color image
            Image to be converted.
        
        Returns
        -------
        image : opencv BGR color image
            Image converted to BGR.
        """
50 51 52 53
        return cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
        
    @staticmethod
    def image_to_hsv(image, bgr = False):
54 55 56 57 58 59 60 61 62 63 64 65 66 67
        """Convert a image to HSV.
        
        Parameters
        ----------
        image : opencv 3-channel color image
            Image to be converted.
        bgr : boolean, optional, default = False
            If true image is BGR, else image is RGB.
        
        Returns
        -------
        image : opencv HSV color image
            Image converted to HSV.
        """
68
        if bgr == False:
69
            image = ImageUtils.image_to_bgr(image)
70 71 72 73
        return cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
        
    @staticmethod
    def image_to_cielab(image, bgr = False):
74 75 76 77 78 79 80 81 82 83 84 85 86 87
        """Convert a image to CIELab.
        
        Parameters
        ----------
        image : opencv 3-channel color image
            Image to be converted.
        bgr : boolean, optional, default = False
            If true image is BGR, else image is RGB.
        
        Returns
        -------
        image : opencv CIELab color image
            Image converted to CIELab.
        """
88
        if bgr == False:
89
            image = ImageUtils.image_to_bgr(image)
90 91 92 93
        return cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
        
    @staticmethod
    def image_grayscale(image, bgr = False):
94 95 96 97 98 99 100 101 102 103 104 105 106 107
        """Convert a image to grayscale.
        
        Parameters
        ----------
        image : opencv 3-channel color image
            Image to be converted.
        bgr : boolean, optional, default = False
            If true image is BGR, else image is RGB.
        
        Returns
        -------
        image : opencv grayscale image
            Image converted to grayscale.
        """
108
        if bgr == False:
109
            image = ImageUtils.image_to_bgr(image)
110 111 112 113
        return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        
    @staticmethod
    def image_binary(image, bgr = False, grayscale = False):
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
        """Convert a image to binary.
        
        Parameters
        ----------
        image : opencv 3-channel color image
            Image to be converted.
        bgr : boolean, optional, default = False
            If true image is BGR, else image is RGB.
        grayscale : boolean, optional, default = False
            If true image is grayscale, else image is 3-channel color.
        
        Returns
        -------
        image : opencv binary image
            Image converted to binary.
        """
130
        if grayscale == False:
131
            image = ImageUtils.image_grayscale(image, bgr)
132 133
        
        image = cv2.GaussianBlur(image,(5,5),0)
134 135 136 137 138
        _, image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
        return image
        
    @staticmethod
    def image_edge_detector(image, canny_min = 100, canny_max = 200, bgr = False, grayscale = False):
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        """Detect the edges of image.
        
        Parameters
        ----------
        image : opencv 3-channel color image
            Source image to be analyzed.
        canny_min : integer, optional, default = 100
            First threshold for the hysteresis procedure.
        canny_max : integer, optional, default = 200
            Second threshold for the hysteresis procedure.
        bgr : boolean, optional, default = False
            If true image is BGR, else image is RGB.
        grayscale : boolean, optional, default = False
            If true image is grayscale, else image is 3-channel color.
        
        Returns
        -------
        image : opencv grayscale image
            Image with edges detected.
        """
159
        if grayscale == False:
160
            image = ImageUtils.image_grayscale(image, bgr)
161 162 163 164
        return cv2.Canny(image, canny_min, canny_max)
        
    @staticmethod
    def image_resize(image, width, height):
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        """Resize the image.
        
        Parameters
        ----------
        image : opencv image
            Image to be resized.
        width : integer
            Width of image.
        height : integer
            Height of image.
        
        Returns
        -------
        image : opencv image
            Image resized.
        """
181
        return cv2.resize(image, (width, height))
182

183
        
184
class TimeUtils(object):
185
    """Set of utilities to manipulate time."""
186 187 188

    @staticmethod
    def get_time():
189 190 191 192 193 194 195
        """Return the current time.
        
        Returns
        -------
        time : float
            Returns the time as a floating point number expressed in seconds since the epoch, in UTC.
        """
196
        return time.time()
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 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371


class MetricUtils(object):
    """Calculate segmentation metrics."""

    @staticmethod
    def confusion_matrix(eval_segm, gt_segm):
        return confusion_matrix(gt_segm.flatten(), eval_segm.flatten())

    @staticmethod
    def pixel_accuracy(eval_segm, gt_segm):
        """sum_i(n_ii) / sum_i(t_i)"""

        MetricUtils.check_size(eval_segm, gt_segm)

        cl, n_cl = MetricUtils.extract_classes(gt_segm)
        eval_mask, gt_mask = MetricUtils.extract_both_masks(eval_segm, gt_segm, cl, n_cl)

        sum_n_ii = 0
        sum_t_i  = 0

        for i, c in enumerate(cl):
            curr_eval_mask = eval_mask[i, :, :]
            curr_gt_mask = gt_mask[i, :, :]

            sum_n_ii += np.sum(np.logical_and(curr_eval_mask, curr_gt_mask))
            sum_t_i  += np.sum(curr_gt_mask)
 
        if (sum_t_i == 0):
            pixel_accuracy_ = 0
        else:
            pixel_accuracy_ = sum_n_ii / sum_t_i

        return pixel_accuracy_


    @staticmethod
    def mean_accuracy(eval_segm, gt_segm):
        """(1/n_cl) sum_i(n_ii/t_i)"""

        MetricUtils.check_size(eval_segm, gt_segm)

        cl, n_cl = MetricUtils.extract_classes(gt_segm)
        eval_mask, gt_mask = MetricUtils.extract_both_masks(eval_segm, gt_segm, cl, n_cl)

        accuracy = list([0]) * n_cl

        for i, c in enumerate(cl):
            curr_eval_mask = eval_mask[i, :, :]
            curr_gt_mask = gt_mask[i, :, :]

            n_ii = np.sum(np.logical_and(curr_eval_mask, curr_gt_mask))
            t_i  = np.sum(curr_gt_mask)
     
            if (t_i != 0):
                accuracy[i] = n_ii / t_i

        mean_accuracy_ = np.mean(accuracy)
        return mean_accuracy_, accuracy


    @staticmethod
    def mean_IU(eval_segm, gt_segm):
        """(1/n_cl) * sum_i(n_ii / (t_i + sum_j(n_ji) - n_ii))"""

        MetricUtils.check_size(eval_segm, gt_segm)

        cl, n_cl   = MetricUtils.union_classes(eval_segm, gt_segm)
        _, n_cl_gt = MetricUtils.extract_classes(gt_segm)
        eval_mask, gt_mask = MetricUtils.extract_both_masks(eval_segm, gt_segm, cl, n_cl)

        IU = list([0]) * n_cl

        for i, c in enumerate(cl):
            curr_eval_mask = eval_mask[i, :, :]
            curr_gt_mask = gt_mask[i, :, :]
     
            if (np.sum(curr_eval_mask) == 0) or (np.sum(curr_gt_mask) == 0):
                continue

            n_ii = np.sum(np.logical_and(curr_eval_mask, curr_gt_mask))
            t_i  = np.sum(curr_gt_mask)
            n_ij = np.sum(curr_eval_mask)

            IU[i] = n_ii / (t_i + n_ij - n_ii)
     
        mean_IU_ = np.sum(IU) / n_cl_gt
        return mean_IU_, IU

    @staticmethod
    def frequency_weighted_IU(eval_segm, gt_segm):
        """sum_k(t_k)^(-1) * sum_i((t_i*n_ii)/(t_i + sum_j(n_ji) - n_ii))"""

        MetricUtils.check_size(eval_segm, gt_segm)

        cl, n_cl = MetricUtils.union_classes(eval_segm, gt_segm)
        eval_mask, gt_mask = MetricUtils.extract_both_masks(eval_segm, gt_segm, cl, n_cl)

        frequency_weighted_IU_ = list([0]) * n_cl

        for i, c in enumerate(cl):
            curr_eval_mask = eval_mask[i, :, :]
            curr_gt_mask = gt_mask[i, :, :]
     
            if (np.sum(curr_eval_mask) == 0) or (np.sum(curr_gt_mask) == 0):
                continue

            n_ii = np.sum(np.logical_and(curr_eval_mask, curr_gt_mask))
            t_i  = np.sum(curr_gt_mask)
            n_ij = np.sum(curr_eval_mask)

            frequency_weighted_IU_[i] = (t_i * n_ii) / (t_i + n_ij - n_ii)
     
        sum_k_t_k = MetricUtils.get_pixel_area(eval_segm)
        
        frequency_weighted_IU_ = np.sum(frequency_weighted_IU_) / sum_k_t_k
        return frequency_weighted_IU_


    @staticmethod
    def get_pixel_area(segm):
        """Auxiliary functions used during evaluation."""
        return segm.shape[0] * segm.shape[1]

    @staticmethod
    def extract_both_masks(eval_segm, gt_segm, cl, n_cl):
        eval_mask = MetricUtils.extract_masks(eval_segm, cl, n_cl)
        gt_mask   = MetricUtils.extract_masks(gt_segm, cl, n_cl)

        return eval_mask, gt_mask

    @staticmethod
    def extract_classes(segm):
        cl = np.unique(segm)
        n_cl = len(cl)

        return cl, n_cl

    @staticmethod
    def union_classes(eval_segm, gt_segm):
        eval_cl, _ = MetricUtils.extract_classes(eval_segm)
        gt_cl, _   = MetricUtils.extract_classes(gt_segm)

        cl = np.union1d(eval_cl, gt_cl)
        n_cl = len(cl)

        return cl, n_cl

    @staticmethod
    def extract_masks(segm, cl, n_cl):
        h, w  = MetricUtils.segm_size(segm)
        masks = np.zeros((n_cl, h, w))

        for i, c in enumerate(cl):
            masks[i, :, :] = segm == c

        return masks

    @staticmethod
    def segm_size(segm):
        try:
            height = segm.shape[0]
            width  = segm.shape[1]
        except IndexError:
            raise

        return height, width

    @staticmethod
    def check_size(eval_segm, gt_segm):
        h_e, w_e = MetricUtils.segm_size(eval_segm)
        h_g, w_g = MetricUtils.segm_size(gt_segm)

        if (h_e != h_g) or (w_e != w_g):
            raise EvalSegErr("DiffDim: Different dimensions of matrices!")