python判断图片主颜色(HSV)
app选项是否能被点击,判断执行逻辑。做自动化测试的朋友肯定遇到好多次,按钮属性无法判别时,就需要自己将app选项颜色进行判断。网上大多数方案:通过图片AI识别,识别精度再高也不能到达百分百。就会识别错误几个选项,导致大批量的测试失败几次。
决定用RGB值判断图片主颜色,结果发现颜色模型太复杂,太烧脑细胞,果断放弃。
我个人的方案就是用过app选项颜色RGB值判断,执行会百分百成功。RGB值对我们个人不太友好,值的范围也不好弄清楚,所以我采用让人更容易理解的HSV值去判断app选项的颜色。
![在这里插入图片描述](https://img-blog.csdnimg.cn/94d3c979d2764fd1988592d30f19c71f.png)
import colorsys
import PIL.Image as Image
# 获取图片主要颜色rgb值
def get_dominant_color(image):
max_score = 0.0001
dominant_color = None
for count,(r,g,b) in image.getcolors(image.size[0]*image.size[1]):
# 转为HSV标准
saturation = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)[1]
y = min(abs(r*2104+g*4130+b*802+4096+131072)>>13,235)
y = (y-16.0)/(235-16)
#忽略高亮色
if y > 0.9:
continue
score = (saturation+0.1)*count
if score > max_score:
max_score = score
dominant_color = (r,g,b)
return dominant_color
# 图片rgb值转为hsv
def rgb2hsv(r, g, b):
r, g, b = r/255.0, g/255.0, b/255.0
mx = max(r, g, b)
mn = min(r, g, b)
m = mx-mn
if mx == mn:
h = 0
elif mx == r:
if g >= b:
h = ((g-b)/m)*60
else:
h = ((g-b)/m)*60 + 360
elif mx == g:
h = ((b-r)/m)*60 + 120
elif mx == b:
h = ((r-g)/m)*60 + 240
if mx == 0:
s = 0
else:
s = m/mx
v = mx
#此时h,s,v值范围分别是0-360, 0-1, 0-1,在OpenCV中,H,S,V范围是0-180,0-255,0-255,加上下面代码转换:
H = h / 2
S = s * 255.0
V = v * 255.0
return H,S,V
# # 返回值是255 100 100的范围
# return h,s*100,v*100
def pan_duan_yan_se(h_0,s_0,v_0):
if 0<=h_0<180 and 0<=s_0<255 and 0<=v_0<46 :
print("黑色")
elif 0<=h_0<180 and 0<=s_0<43 and 46<=v_0<220:
print("灰色")
elif 0<=h_0<180 and 0<=s_0<30 and 221<=v_0<255:
print("白色")
elif (0<=h_0<10 or 156<=h_0<180) and 43<=s_0<255 and 46<=v_0<255:
print("红色")
elif 11<=h_0<25 and 43<=s_0<255 and 16<=v_0<255:
print("橙色")
elif 26<=h_0<34 and 43<=s_0<255 and 46<=v_0<255:
print("黄色")
elif 35<=h_0<77 and 43<=s_0<255 and 46<=v_0<255:
print("绿色")
elif 78<=h_0<99 and 43<=s_0<255 and 46<=v_0<255:
print("青色")
elif 100<=h_0<124 and 43<=s_0<255 and 46<=v_0<255:
print("蓝色")
elif 125<=h_0<155 and 43<=s_0<255 and 46<=v_0<255:
print("紫色")
else:
print("色调H超出范围,饱和度S,亮度V明度")
if __name__ == '__main__':
image = Image.open(放自己图片保存路径)
image = image.convert('RGB')
print(get_dominant_color(image))
print(type(get_dominant_color(image)))
r, g, b = get_dominant_color(image)[0], get_dominant_color(image)[1], get_dominant_color(image)[2]
hsv_value = rgb2hsv(r, g, b)
print(hsv_value)
h_0 = hsv_value[0]
s_0 = hsv_value[1]
v_0 = hsv_value[2]
pan_duan_yan_se(h_0,s_0,v_0)
在网上查了好多的资料,发现都转换为RGB值,然后就不好判断了,因为自己项目中要用,就赶快写一个HSV判断图片主颜色,这个方案仅供大家参考学习,如果有不当之处,请多多包含。修改其中的一些代码放在自己项目中,希望可以帮到小伙伴。