RGB通道并不能很好地反映出物体具体的颜色信息 , 而相对于RGB空间,HSV空间能够非常直观的表达色彩的明暗,色调,以及鲜艳程度,方便进行颜色之间的对比.
python代码:
import numpy as np
import collections
# 定义字典存放颜色分量上下限
# 例如:{颜色: [min分量, max分量]}
# {'red': [array([160, 43, 46]), array([179, 255, 255])]}
# 设置HSV中颜色范围
def getColorList():
dict = collections.defaultdict(list)
# # 设置HSV中黑色范围
lower_black = np.array([0, 0, 0])
upper_black = np.array([180, 255, 46])
color_list = []
color_list.append(lower_black)
color_list.append(upper_black)
dict['black'] = color_list
# #灰色
lower_gray = np.array([0, 0, 46])
upper_gray = np.array([180, 43, 220])
color_list = []
color_list.append(lower_gray)
color_list.append(upper_gray)
dict['gray']=color_list
# 白色
lower_white = np.array([0, 0, 221])
upper_white = np.array([180, 30, 255])
color_list = []
color_list.append(lower_white)
color_list.append(upper_white)
dict['white'] = color_list
# 红色
lower_red = np.array([156, 43, 46])
upper_red = np.array([180, 255, 255])
color_list = []
color_list.append(lower_red)
color_list.append(upper_red)
dict['red'] = color_list
# 红色2
lower_red = np.array([0, 43, 46])
upper_red = np.array([10, 255, 255])
color_list = []
color_list.append(lower_red)
color_list.append(upper_red)
dict['red2'] = color_list
# 橙色
# lower_orange = np.array([11, 43, 46])
# upper_orange = np.array([25, 255, 255])
# color_list = []
# color_list.append(lower_orange)
# color_list.append(upper_orange)
# dict['orange'] = color_list
# 黄色
# lower_yellow = np.array([26, 43, 46])
# upper_yellow = np.array([34, 255, 255])
# color_list = []
# color_list.append(lower_yellow)
# color_list.append(upper_yellow)
# dict['yellow'] = color_list
# 绿色
lower_green = np.array([35, 43, 46])
upper_green = np.array([77, 255, 255])
color_list = []
color_list.append(lower_green)
color_list.append(upper_green)
dict['green'] = color_list
# 青色
# lower_cyan = np.array([78, 43, 46])
# upper_cyan = np.array([99, 255, 255])
# color_list = []
# color_list.append(lower_cyan)
# color_list.append(upper_cyan)
# dict['cyan'] = color_list
# 蓝色
lower_blue = np.array([100, 43, 46])
upper_blue = np.array([124, 255, 255])
color_list = []
color_list.append(lower_blue)
color_list.append(upper_blue)
dict['blue'] = color_list
# 紫色
# lower_purple = np.array([125, 43, 46])
# upper_purple = np.array([155, 255, 255])
# color_list = []
# color_list.append(lower_purple)
# color_list.append(upper_purple)
# dict['purple'] = color_list
return dict
if __name__ == '__main__':
answer = []
frame=cv2.imread("1.jpg")
# 利用cvtColor()将BGR格式转成HSV格式
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
for d in self.color_dict:
# 利用inRange()函数和HSV模型中某种颜色范围的上下界获取mask,mask中原视频中的某种颜色部分会被弄成白色,其他部分黑色。
mask = cv2.inRange(hsv, self.color_dict[d][0], self.color_dict[d][1])
# 将mask于原视频帧进行按位与操作,则会把mask中的白色用真实的图像替换
res = cv2.bitwise_and(frame, frame, mask=mask)
answer.append([d,res])
print(answer)