An RGB image is a type of digital image that uses the red-green-blue color model to represent colors. It’s one of the most common ways to digitally represent colors in images.
In the RGB color model, each pixel in the image is composed of three color channels: red, green, and blue. The combination of these three primary colors in varying intensities creates a wide array of colors and shades visible to the human eye.
The intensity of each color channel (red, green, blue) in a pixel is typically represented using an 8-bit value, ranging from 0 to 255. The combination of these three channels determines the final color of the pixel.
A grayscale image, also known as a black-and-white image, is an image where each pixel typically represents varying shades of gray, ranging from black to white. Unlike an RGB image that contains three color channels (red, green, blue), a grayscale image has only one channel representing the intensity of light, often measured as a single value between 0 and 255.
To convert an RGB image to a grayscale image using scikit-image (skimage
) in Python, we can use the rgb2gray()
function from the skimage.color
module as shown in the syntax below:
skimage.color.rgb2gray(rgb_image)
The rgb2gray()
function accepts an image in RGB format with the channel dimension and returns an array of the same size as the input image without the channel dimension.
Here’s an example of how to do this:
import matplotlib.pyplot as pltfrom skimage import datafrom skimage.color import rgb2grayoriginal = data.cat()grayscale = rgb2gray(original)fig, axes = plt.subplots(1, 2, figsize=(8, 4))ax = axes.ravel()ax[0].imshow(original)ax[0].set_title("RGB")ax[1].imshow(grayscale, cmap=plt.cm.gray)ax[1].set_title("Grayscale")fig.tight_layout()plt.show()
Let’s understand the code above with the following explanation:
Lines 1–3: We import necessary Python modules and libraries—matplotlib
for creating plots, and skimage
for image processing.
Line 5: We use the cat
image available in the skimage.data
.
Line 6: We convert the image to grayscale using rgb2gray()
function.
Lines 8–15: We plot the RGB image with the converted grayscale image.
Free Resources