Open In App

Create Random RGB Color Code using Python

Last Updated : 05 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Color codes are the defacto method of representing a color. It helps accurately represent the color, regardless of the display calibration. This article will teach you how to create random RGB color code using Python.

RGB Color Code

An RGB color code is a tuple containing 3 numbers representing Red, Green, and Blue color values, respectively. Ex. The color code tuple for a 24-bit color system (channel_intensity < 256) would be:

(X, Y, Z)

Where,

X => Red channel intensity

Y => Green channel intensity

Z => Blue channel intensity 

And the intensity of all channels should be less than 256 (for an 8-bit per channel system). 

Hence for pure red color, the color code would be

(255, 0, 0)

Where 

Red     = 255
Green     = 0
Blue    = 0

Similarly, over 16 million colors could be uniquely represented. Throughout the article, the 8-bit per channel color space would be considered.

Approach 1 (Using random module):

  • The problem at hand is creating a color code tuple in which each value represents the intensity of a channel between 0 and 255.
  • The value must be random and calculated individually for each channel. For this purpose, the use of the randint function inside the random module would be made. 
randint(a, b) 
   Return random integer in range [a, b], including both end points.

Code:

Python3




import random
  
# The minimum intensity of the color space
min = 0
  
# The maximum intensity of the color space
max = 255
  
# Calculating 3 random values for each channel between min & max
red = random.randint(min, max)
green = random.randint(min, max)
blue = random.randint(min, max)
  
print("Color Code :", (red, green, blue))


Output

Color Code : (68, 211, 217)

Explanation:

Firstly, the random library is imported, allowing the python compiler to produce pseudo-random values. Then two variables are defined, containing the maximum and minimum intensity values representable in the color space. Then the randint function is used to produce a random value between the aforementioned range. The same process is done individually for all 3 channels. In the end, the random values are displayed in a tuple representing a Color code. 

Approach 2 (Using Numpy):

  • Import the Numpy module.
  •  The color’s size and value will then be assigned to the variable created.
  • Print the variable.

Python3




# importing library
import numpy as np
# creating a list
color = list(np.random.choice(range(255), size=3))
# printing the random color code generated
print("Color code is:", color)


Output:

Color code is: [122, 111, 220]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads