How to check the accuracy rate of the model trained using hsv color model

103 Views Asked by At

I am trying to detect the colour of the images using hsv model.

Below is the code that I have used to detect the colour using hsv model.

import os
import numpy as np
import cv2

# map colour names to HSV ranges
color_list = [
    ['red', [0, 160, 70], [10, 250, 250]],
    ['pink', [0, 50, 70], [10, 160, 250]],
    ['yellow', [15, 50, 70], [30, 250, 250]],
    ['green', [40, 50, 70], [70, 250, 250]],
    ['cyan', [80, 50, 70], [90, 250, 250]],
    ['blue', [100, 50, 70], [130, 250, 250]],
    ['purple', [140, 50, 70], [160, 250, 250]],
    ['red', [170, 160, 70], [180, 250, 250]],
    ['pink', [170, 50, 70], [180, 160, 250]]
]


def detect_main_color(hsv_image, colors):
    color_found = 'undefined'
    max_count = 0

    for color_name, lower_val, upper_val in colors:
        # threshold the HSV image - any matching color will show up as white
        mask = cv2.inRange(hsv_image, np.array(lower_val), np.array(upper_val))

        # count white pixels on mask
        count = np.sum(mask)
        if count > max_count:
            color_found = color_name
            max_count = count

    return color_found


for root, dirs, files in os.walk('C:/Users/User/Desktop/images/'):
    f = os.path.basename(root)

    for file in files:
        img = cv2.imread(os.path.join(root, file))
        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        print(f"{file}: {detect_main_color(hsv, color_list)}")

The output

image_1 : blue
image_3 : pink
image_12: purple
...

How can I check the accuracy rate of this trained model?

Any help is appreciated.

Thank you.

2

There are 2 best solutions below

1
On

By eys I think, or test you code on some pure color images. I think it is better to clarify the definition of "the colour of the image" firstly. For example, what is the color of this image? enter image description here

1
On

you could compare with colorsys

docs.python.org - colorsys

import colorsys

colorsys.rgb_to_hsv(0.2, 0.4, 0.4) = (0.5, 0.5, 0.4)
colorsys.hsv_to_rgb(0.5, 0.5, 0.4) = (0.2, 0.4, 0.4)