Colour identification in images

Introduction

Images are composed using a grid of small squares called pixels. Each pixel is assigned to a specific colour value and, when combined, creates the overall image.

To identify all the colours in the image, Python is used which has a library called OpenCV.

Library

We import basic libraries including matplotlib.pyplot , cv2, numpy, pandas

import cv2
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt

pandas and numpy are used to extract the count, cv2 is used for OpenCV. matplotlib is used to plot the output.

To read any image we use cv2.imread()

image = cv2.imread('link_to_image')
# if we have to resize the image then
image = cv2.resize(img, (960,540))

To view the read image we use matplotlib to plot the image with the following code:

plt.figure(figsize=(18,6)) # used to specify the size of image
plt.imshow(img) # This shows the image

The image that has been read using cv2 is in the colour format of BGR so to make it in RGB format we apply the following line of code:

grid_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

after formatting to RGB colour pattern we again plot the image using the above code of plt.figure().....

Reading data from filename.csv file we use pandas read_csv

csv_path = "path of csv flie e.g. './filename.csv'"
df = pd.read_csv(csv_path, names=index, header=None)

Colour Identification

Defined a function, to achieve the colour in the given function

def get_color_name(R,G,B):
    minimum = 1000
    for i in range(len(df)):
        d = abs(R - int(df.loc[i,'R'])) + abs(G - int(df.loc[i,'G'])) + abs(B-int(df.loc[i,'B']))
        if d <= minimum:
            minimum = d
            cname = df.loc[i,'color_name']
    return cname

Handling the mouse event.

def draw_function(event, x, y, flags, params):
    if event == cv2.EVENT_LBUTTONDBLCLK:
        global b, g, r, xpos, ypos, clicked
        clicked = True
        xpos = x
        ypos = y
        b,g,r = img[y,x]
        b = int(b)
        g = int(g)
        r = int(r)

OpenCV window

cv2.namedWindow('Color Identification in Images')
cv2.setMouseCallback('Color Identification in Images', draw_function)

while True:
    cv2.imshow('Color Identification in Images', img)
    if clicked:
        cv2.rectangle(img, (20,20), (600,60), (b,g,r), -1)

        text = get_color_name(r,g,b) + 'R = ' + str(r) + 'G = ' + str(g) + 'B = ' + str(b)
        # Draw text on image
        cv2.putText(img, text, (50,50), 2,0.8, (255,255,255) , 2 , cv2.LINE_AA)
    # exit on esc    
    if cv2.waitKey(20) & 0xFF == 27:
        break
cv2.destroyAllWindows()