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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
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) |
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