2017-04-04 128 views
-1

我寫一個Python腳本,我需要檢查的顏色代碼對3種顏色:紅色,黃色和綠色在這樣:如何根據顏色範圍檢查RGB顏色?

if (255,255,255) is in green range: 
    print("green") 
else if (255,255,255) is in yellow range: 
    print("yellow") 
else if (255,255,255) is in red range: 
    print("red") 
else: 
    print("none") 

我有麻煩的事情是怎麼看它是否is in yellow range

任何建議,將不勝感激。

編輯

下圖展示了我的黃色,綠色和紅色的感覺:

enter image description here

+2

「綠色範圍」是什麼意思?你能定義嗎? –

+0

這意味着如果顏色是任何陰影的綠色 – Elisha512

+2

是的,但我的意思是說,你有一個顏色'(r,g,b)'在什麼條件下它「接近」紅色?它應該只是'(255,0,0)'還是'(200,10,10)'也是允許的?曾經進行過一次關於人們是否將顏色識別爲綠色或藍色的實驗。因爲俄羅斯對藍色(淺藍色和深藍色)有兩個不同的詞,所以俄羅斯人看到更多的顏色爲藍色。即使人們不同意這個問題,所以你需要首先定義。 –

回答

2

我砍死在終端下面的解決方案,不是很乾淨,但我希望你有想法。

TARGET_COLORS = {"Red": (255, 0, 0), "Yellow": (255, 255, 0), "Green": (0, 255, 0)} 

def color_difference (color1, color2): 
    return sum([abs(component1-component2) for component1, component2 in zip(color1, color2)]) 

my_color = (123, 234, 100) 

differences = [[color_difference(my_color, target_value), target_name] for target_name, target_value in TARGET_COLORS.items()] 
differences.sort() # sorted by the first element of inner lists 
my_color_name = differences[0][1] 

print(my_color_name) 

圖,my_color = (123, 234, 100)最匹配的是綠色的:)

+0

這完美的作品!正是我需要的。謝謝! – Elisha512

1

轉換顏色到HSL和指色輪狀this one選擇你的黃,紅,綠,特別是H值的定義。