[英]Color handling in Python
對於我的聚類gui,我目前正在使用隨機顏色進行聚類,因為我不知道手頭會有多少個聚類。
在Python中,這看起來像:
import random
def randomColor():
return (random.random(),random.random(),random.random())
但是,當我更新東西時,顏色會發生變化。
所以我傾向於擁有一個具有輸入參數I的函數,例如
def nonrandomColor(i):
...
return color
總是會為同一個I返回相同的顏色,同時保持生成任意多種顏色的能力。
答案不一定要用Python來表達,它更像是我感興趣的總體布局。
一種方法是使用緩存。 使用defaultdict
:
>>> import random
>>> def randomColor():
... return (random.random(),random.random(),random.random())
...
>>> from collections import defaultdict
>>> colors = defaultdict(randomColor)
>>> colors[3]
(0.10726172906719755, 0.97327604757295705, 0.58935794305308264)
>>> colors[1]
(0.48991106537516382, 0.77039712435566876, 0.73707003166893892)
>>> colors[3]
(0.10726172906719755, 0.97327604757295705, 0.58935794305308264)
只需將隨機生成器的種子設置為索引,這可能比存儲顏色便宜。
random.seed(i)
請注意,這將使隨機數的方法比以前少了隨機的。 如果這是一個問題,例如,如果您的應用程序在其他地方使用隨機數,您可能需要查看其他答案建議的緩存選項。
您想要將顏色存儲在字典或列表中:
colors = {} # int -> color
def nonrandomColor(i):
if i not in colors:
colors[i] = randomColor()
return colors[i]
如果你想要可重復的非碰撞顏色,那么你可以使用類似下面的功能。 它將數字分為1,10,100,然后將它們用作顏色的RGB部分。
def color(i):
r = i % 10
g = (i//10) % 10
b = (i//100) % 10
return(r*25, g*25, b*25)
例如:
color(1) == (25,0,0)
color(10) == (0,25,0)
color(999) = (225,225,255)
您可以使用i
為隨機數生成器播種。 因此,只要種子保持不變,就可以得到相同的值。
>>> import random
>>> random.seed(12)
>>> random.randint(0,255), random.randint(0,255), random.randint(0,255)
(121, 168, 170)
>>> random.seed(12)
>>> random.randint(0,255), random.randint(0,255), random.randint(0,255)
(121, 168, 170)
>>> random.seed(10)
>>> random.randint(0,255), random.randint(0,255), random.randint(0,255)
(146, 109, 147)
>>> random.seed(10)
>>> random.randint(0,255), random.randint(0,255), random.randint(0,255)
(146, 109, 147)
根據您可能生成的顏色數量(即10或100萬),緩存方法可能比seed()
方法更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.