I wrote program to identify a color from file and prints the name of given colors, from which color of file has the highest similarity with. I used HSV to get range of color and compare HSV to this range to get the most similar color. I try to iterate through the dictionary of colors to compare them to HSV of file I pass. However, it doesn't work and show any errors.
from pickletools import uint8
import cv2
from matplotlib import image
import numpy as np
#HSV Hue - color, Saturation - color density, Value - brightness of color.
#use lower and upper value of a color to define range where picture will fit.
#opencv's HSV values are H(0-179)S(0-255)V(0-255)
img = cv2.imread('purple.jpg', cv2.COLOR_BGR2HSV)
#colors
color_list= {
"white":([0,0,50],[0,0,255]),
"black":([0,0,0],[0,0,49]),
"red":([0,0,225],[127,0,255]),
"green":([40,40,40],[70,255,255]),
"yellow":([23,41,223],[40,150,255]),
"blue":([78,158,124],[138,255,255])
}
#get image
img = cv2.imread('purple.jpg')
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
for color_name, (lower, upper) in color_list.items():
lower = np.array(lower, dtype = np.uint8)
upper = np.array(upper, dtype = np.uint8)
mask = cv2.inRange(img,lower,upper)
output = cv2.bitwise_and(img,img, mask = mask)
if mask.any():
print(f"{color_name} :{mask.sum}")
CodePudding user response:
You have the right idea. But instead of summing the pixels in mask
, you need to find the number of white pixels for each color range
Here is a simple approach.
- For every color in the dictionary, obtain the
mask
- The
mask
is a binary image (black and white image) with value of either0
(black) and255
(white). The white pixel means it contains the color within the specified range. - For each color range, count the number of white pixels present in
mask
. The image has the corresponding color if its range has the most number of white pixels.
Additional Code:
final_color = None
final_count = None
for color_name, (lower, upper) in color_list.items():
mask = cv2.inRange(hsv, tuple(lower), tuple(upper))
# count non-zero pixels in mask
count=np.count_nonzero(mask)
if count > 0:
final_count = count
final_color = color_name
print("Nearest Color is {}".format(final_color))
CodePudding user response:
You need to call the cv2.cvtColor()
method, like so:
import cv2
img = cv2.cvtColor(cv2.imread('purple.jpg'), cv2.COLOR_BGR2HSV)