Home > Net >  how to get RGB numbers from a list
how to get RGB numbers from a list

Time:10-15

I used colorgram library, and got a list of RGB color code.

[<colorgram.py Color: Rgb(r=80, g=97, b=85), 42.86094708532268%>,
 <colorgram.py Color: Rgb(r=34, g=48, b=37), 20.90975231208169%>,
 <colorgram.py Color: Rgb(r=29, g=26, b=18), 12.300570275661888%>]

I want to extract the numbers of RGB numbers like this.

[[80, 97, 85], [34, 48, 37], [29, 26, 18]]

but each element's type is 'colorgram.cologram.Color', and the length of list is variable. how can I get RGB numbers?

CodePudding user response:

[list(c.rgb) for c in l]

where l is your list of colorgram should do

Example

import colorgram
l=colorgram.extract("file.png", 6)
colors=[list(c.rgb) for c in l]

[f(x) for x in iterable] is the compound list syntax. So it's a way to compute a list a f(x) from a list of x. Here, what I do is taking each colorgram c in l, and computing list(c.rgb) from it.

c begin a colorgram, c.rgb is the rgb color or that colorgram (but still in the form of a type specific of the colorgram package. That allows to also access by fields [c.r, c.g, c.b]). And list(c.rgb) transforms this rgb color in a list of 3 int.

CodePudding user response:

The rgb values are stored as a named tuple that is stored under the .rgb property of the Color object.

You can extract an rgb triple by just calling my_color.rgb.

If you want to make a list of lists of rgb values then, and have all of your Colors objects stored in a list that is named my_colors you can use:

rgb_list = [list(color.rgb) for color in my_colors]
  • Related