,

Color Detection using Pandas & OpenCV in Python

Today’s project is going to be both enjoyable and informative. We’ll delve into the world of colors, exploring various concepts along the way. Color detection is crucial for object recognition and serves as a fundamental tool in numerous image editing and drawing applications.

Color detection is the process of identifying or recognizing different colors in an image or video. This could involve tasks such as identifying the presence of certain colors, measuring color values, or segmenting an image based on colors.

In this color detection Python project, we are going to build an application through which you can automatically get the name of the color by clicking on them in any image which has been pre defined by the user. So for this, we will have a data file that contains the color name and its values. Then we will calculate the distance from each color and find the shortest one.

Full Code:

First let us create a csv file which has the data for various colors. I have taken in the below format and my csv file name is colors.csv. Similarly you can create yours and give a file name and replace the same file name in the below code.

import cv2
import pandas as pd
import argparse

# Argument parsing
ap = argparse.ArgumentParser()
ap.add_argument('-i', '--image', required=True, help="Image Path")
args = vars(ap.parse_args())
img_path = args['image']

# Reading image with OpenCV
img = cv2.imread(img_path)

# Reading csv file with pandas and giving names to each column
csv = pd.read_csv('colors.csv')

# Function to get the name of the clicked color
def getColorName(R, G, B):
    minimum = 10000
    cname = "Undefined"
    for i in range(len(csv)):
        d = abs(R - csv.loc[i, "R"]) + abs(G - csv.loc[i, "G"]) + abs(B - csv.loc[i, "B"])
        if d < minimum:
            minimum = d
            cname = csv.loc[i, "color_name"]
    return cname

# Mouse click event function
def draw_function(event, x, y, flags, param):
    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)

# Create a window and set mouse callback
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_function)

clicked = False
while True:
    cv2.imshow("image", img)
    if clicked:
        cv2.rectangle(img, (20, 20), (750, 60), (b, g, r), -1)
        text = getColorName(r, g, b) + ' R=' + str(r) + ' G=' + str(g) + ' B=' + str(b)
        cv2.putText(img, text, (50, 50), 2, 0.8, (255, 255, 255), 2, cv2.LINE_AA)
        if r + g + b >= 600:
            cv2.putText(img, text, (50, 50), 2, 0.8, (0, 0, 0), 2, cv2.LINE_AA)
        clicked = False

    # Break the loop when user hits 'esc' key
    if cv2.waitKey(20) & 0xFF == 27:
        break

cv2.destroyAllWindows()

Note: In order to load the image you have to put the below command in your terminal. Replace your_script with your file name and path with your path name for the image.

python your_script.py -i path/to/your/image.jpg

Output:

Explanation of the above code:

  1. import cv2: Imports the OpenCV library for image processing.
  2. import pandas as pd: Imports the Pandas library for data manipulation and analysis.
  3. import argparse: Imports the argparse module for parsing command-line arguments.
  4. ap = argparse.ArgumentParser(): Creates an ArgumentParser object for handling command-line arguments.
  5. ap.add_argument('-i', '--image', required=True, help="Image Path"): Adds a required command-line argument -i or --image for specifying the path to the image file.
  6. args = vars(ap.parse_args()): Parses the command-line arguments and stores them in a dictionary.
  7. img_path = args['image']: Extracts the image path from the dictionary of parsed arguments.
  8. img = cv2.imread(img_path): Reads the image from the specified path using OpenCV.
  9. csv = pd.read_csv('colors.csv'): Reads the CSV file containing color data into a Pandas DataFrame.
  10. def getColorName(R, G, B): Defines a function getColorName that returns the name of the color closest to the given RGB values.
  11. cv2.namedWindow('image'): Creates a window with the name ‘image’ for displaying the image.
  12. cv2.setMouseCallback('image', draw_function): Sets a mouse callback function draw_function for handling mouse events on the image window.
  13. while True:: Starts an infinite loop for continuously displaying the image and handling mouse events.
  14. cv2.imshow("image", img): Displays the image in the ‘image’ window.
  15. if clicked:: Checks if a mouse double-click event has occurred.
  16. cv2.rectangle(img, (20, 20), (750, 60), (b, g, r), -1): Draws a filled rectangle on the image to display the detected color.
  17. text = getColorName(r, g, b) + ' R=' + str(r) + ' G=' + str(g) + ' B=' + str(b): Gets the name of the detected color and its RGB values.
  18. cv2.putText(img, text, (50, 50), 2, 0.8, (255, 255, 255), 2, cv2.LINE_AA): Adds text to the image displaying the color name and RGB values.
  19. if r + g + b >= 600:: Checks if the color is very light and adjusts the text color accordingly.
  20. cv2.destroyAllWindows(): Closes all OpenCV windows when the loop is exited.

In this project, we used Python with OpenCV and Pandas to create a color detection system. We loaded an image and displayed it in a window, allowing the user to click on any pixel. By analyzing the RGB values of the clicked pixel and comparing them with a predefined set of colors, we identified the closest matching color. This system can be useful in various applications such as image editing, computer vision, and color-based object detection.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>