Python 3 (OpenCV + Numpy) Script to Extract Dominant Color in RGB Hex Code From Image File Full Project For Beginners

Python 3 (OpenCV + Numpy) Script to Extract Dominant Color in RGB Hex Code From Image File Full Project For Beginners

 

Welcome folks today in this blog post we will be extracting dominant color in rgb hex code from image file in python using opencv and numpy library. All the source code of the application is given below.

 

 

Get Started

 

 

In order to get started you need to install the following library using the pip command as shown below

 

pip install numpy

 

pip install opencv-python

 

After installing these libraries make an app.py file and copy paste the following code

 

app.py

 

import cv2
import numpy as np

path = input("Enter Path :- ")
try:
    img = cv2.imread(path)
    cv2.imshow("img", img)
except Exception:
    print("Path not found")
    exit()


array = np.array(img)
unique, counts = np.unique(array, return_counts=True)

ocurrance = dict(zip(unique, counts))


a1_sorted_keys = sorted(ocurrance, key=ocurrance.get, reverse=True)
print(a1_sorted_keys[:3])


# Create a blank 300x300 black image
image = np.zeros((300, 300, 3), np.uint8)
# Fill image with red color(set each pixel to red)
image[:] = a1_sorted_keys[:3]


c = a1_sorted_keys[0]

# Create a blank 300x300 black image
color = np.zeros((300, 300, 3), np.uint8)
# Fill image with red color(set each pixel to red)
color[:] = (c, c, c)

print("Tone : " + str(a1_sorted_keys[:3]))
cv2.imshow("Tone", image)
print("color : " + str([c, c, c]))
cv2.imshow("color", color)

 

See also  Python 3 PyQt5 BMI (Body Mass Index) Calculator GUI Script Desktop App Full Project For Beginners

 

Now if you execute this python script by typing the below command

 

python app.py

 

 

 

As you can see it asks for the path of the image we provide the image as input and then it returns the dominant color which is present in image in the form of RGB hex code and also return tone information about image

Leave a Reply