All answers discuss methods for finding a single color in an image, but itβs always useful to know how to find several colors in an image. Especially when you are dealing with images of segmentation tasks.
Let's take an image for our explanation

Obviously, each class of objects in this figure has its own color.
Let's write a function to load an image from a URL and convert it to an empty array. Thus, it becomes very easy to work with images.
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 = '/img/2e3a2f883613d9cc35e15875a7eb399f.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 will get a list of hexadecimal codes for all colors in the color_list variable.
Let me know if the code works / not for you :)
Lavish Saluja Jul 07 '19 at 19:00 2019-07-07 19:00
source share