ChunML / ssd-tf2

A super clean implementation of SSD (Single Shot MultiBox Detector) made possible by Tensorflow 2.0
MIT License
115 stars 54 forks source link

What is the class_colors? #12

Closed Ikhwansong closed 4 years ago

Ikhwansong commented 4 years ago

Hi ! Thanks for your sharing the code.

According to the source code, the class_colors was not used in anywhere.

Why did you write the code like this?

image

ChunML commented 4 years ago

Hi, that's for folks that want a different color for each class, otherwise, only the green color (default implementation) will be used.

Ikhwansong commented 4 years ago

image

This is code for the random colorizing.

class ImageVisualizer_cv2(object):

def __init__(self, idx_to_name, class_colors = None, save_dir = None):
    self.idx_to_name = idx_to_name
    self.color_matrix = self._colorizing()
    self.color_matrix = np.random.shuffle(self.color_matrix)

    if save_dir is None:
        self.save_dir = './'
    else:
        self.save_dir = save_dir

    os.makedirs(self.save_dir, exist_ok=True)

def _colorizing(self,):
    factor = math.floor(math.pow(len(self.idx_to_name), 1/3))
    color_divider = 255/factor
    color_matrix = np.zeros(((factor+1)*(factor+1)*(factor+1),3))
    index = 0
    for x in range(factor+1):
        for y in range(factor+1) :
            for z in range(factor+1) :
                color_matrix[index,:] = np.array([x*color_divider, y*color_divider, z*color_divider])
                index = index + 1 
    return color_matrix[1:-1]

def save_image(self, img_path, boxes, labels, name):
    img  = cv2.imread(img_path)
    save_path = os.path.join(self.save_dir, name)

    for i, box in enumerate(boxes):
        idx = labels[i] -1
        cls_name = self.idx_to_name[idx]
        top_left = (box[0], box[1])
        bot_right = (box[2], box[3])
        cv2.rectangle(img,top_left, bot_right, self.color_matrix[idx], 1 )
        cv2.putText(img, cls_name, top_left,1, (255,255,255), 1)

    cv2.imwrite(save_path, img)

For example, If the len of class is the number of 27, It generate 444 number of cases and perform random matching the class name with one color pair except two colors (white and black). It means the dog only have the one color forever. (Ex. dog = red)