Converting color image to greyscale in Python

Converting a color image to a grayscale image is a common task in image processing. This task can be easily accomplished in Python using various libraries such as OpenCV, and PIL (Python Imaging Library). The grayscale image is a single-channel image that contains only the intensity values of the original color image. The conversion process involves assigning a single value to each pixel of the image, which indicates its brightness level. The grayscale image is useful for applications such as image compression, image analysis, and feature extraction. In the following sections, we will explore some of the popular methods for converting a color image to grayscale using Python.

Converting color  to a

Greyscale

 image

Let us understand this concept with examples,

    1. We need to import the library in our code.
      from matplotlib.image import imread
      import matplotlib.pyplot as plt 
      import numpy as np

      2. To proceed with the task at hand, it is necessary to provide input in the form of an image. This image should be in a compatible format, and it should contain the relevant information that is required for the task to be completed successfully. Depending on the nature of the task, there might be specific requirements for the image, such as its size, resolution, or color space. It is important to ensure that the image meets all the necessary criteria to avoid any potential issues or errors that may arise during the process.

      input_image = imread("happy.jpg")

      3. When working with digital images, converting an image to greyscale is a common operation. This process involves changing the color values of each pixel in the image to a single shade of grey. To do this, we need to implement an algorithm that calculates the appropriate grey value for each pixel based on its original color values. There are various algorithms available for this purpose, such as the average method, the luminosity method, and the desaturation method. Each algorithm has its strengths and weaknesses, and the choice of algorithm depends on the specific requirements of the image processing task.

r,g,b = input_image[:,:,0], input_image[:,:, 1], input_image[:,:,2]
gamma = 1.04
r_const, g_const, b_const = 0.2126, 0.7152, 0.0722
grayscale_image = r_const
fig = plt.figure(1)
img1, img2 = fig.add_subplot(121), fig.add_subplot(122)
img1.imshow(input_image)
img2.imshow(grayscale_image, cmap = plt.cm.get_cmap('gray'))

4.  Then the image converted should be printed to the output by using these code lines.

fig.show()
plt.show()

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top