All the answers discuss the methods to find a single color in an image but knowing how to find multiple colors in the image is always beneficial. Especially when you deal with segmentation task's images.
Let's take an image for our explanation
Clearly, every class of objects in this picture has a different color.
Let's write a function to download an image from a URL and convert it into a numpy array. It becomes very easy to deal with images in this way.
import numpy as np
import cv2
import urllib
from urllib.request import urlopen
import webcolors
import time
def getImageArray(mask):
req = requestObject(mask)
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
im = cv2.imdecode(arr, -1)
im = im[:, :, :3]
return im
def requestObject(mask):
temp_req = {'status': 403}
retry_counter = 1
while((temp_req['status'] != 200) and (retry_counter <= 10)):
try:
req = urlopen(mask)
temp_req = {"status": 200}
except:
print("Retrying for: ", retry_counter)
temp_req = {"status": 403}
time.sleep(4)
retry_counter = retry_counter + 1
return req
Now, Let's get the image:
url = 'https://i.stack.imgur.com/Bi16j.jpg'
image = getImageArray(url)
Let's write a function to find all the colors:
def bgr_to_hex(bgr):
rgb =list(bgr)
rgb.reverse()
return webcolors.rgb_to_hex(tuple(rgb))
def FindColors(image):
color_hex = []
for i in image:
for j in i:
j = list(j)
color_hex.append(bgr_to_hex(tuple(j)))
return set(color_hex)
color_list = FindColors(image)
Try running the above script in your terminal and you'll get the list of hexadecimal codes for all colors in the variable color_list
.
Let me know if the code works/doesn't for you :)