Python Generate random colors (RGB)

Generate random colors (RGB)

I just picked up image processing in python this past week at the suggestion of a friend to generate patterns of random colors. I found this piece of script online that generates a wide array of different colors across the RGB spectrum.

def random_color():
    levels = range(32,256,32)
    return tuple(random.choice(levels) for _ in range(3))

I am simply interesting in appending this script to only generate one of three random colors. Preferably red, green, and blue.

 

回答1

A neat way to generate RGB triplets within the 256 (aka 8-byte) range is

color = list(np.random.choice(range(256), size=3))

color is now a list of size 3 with values in the range 0-255. You can save it in a list to record if the color has been generated before or no.

 评论

Should be color = list(np.random.random(size=3) * 256) Mar 6, 2018 at 16:48
 
Or without np: rand_color = random.choices(range(256), k=3) Jul 5, 2021 at 23:33
 
 
You could rather use a tuple: color = tuple(np.random.random(size=3) * 256) May 19 at 8:58

 

vowels = ['a', 'e', 'i', 'o', 'i', 'u']

>>> type(vowels)
<class 'list'>

 

>>> color = list(np.random.choice(range(256), size=3))
>>> type(color)
<class 'list'>

 

>>> color = tuple(np.random.random(size=3) * 256)
>>> type(color)
<class 'tuple'>

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-09-17 向量内积(点乘)和外积(叉乘)概念及几何意义
2021-09-17 jQuery Migrate
2021-09-17 Best way to expose resource strings to JavaScript files in ASP.NET MVC?
2021-09-17 What's the difference between sweetalert and sweetalert2?
2021-09-17 Does javascript have an Equivalent to C#s HttpUtility.HtmlEncode? [duplicate]
2021-09-17 sweetalert2 and xss
2021-09-17 上海居住证办理条件以及流程?
点击右上角即可分享
微信分享提示