How to Convert RGB Images to Grayscale in Python?

Estimated read time 2 min read

To convert RGB images to grayscale in Python, you can use the PIL (Python Imaging Library) library. Here’s an example:

from PIL import Image

def rgb_to_grayscale(image_path):
    image ='L')
    grayscale_image_path = 'grayscale.jpg'
    return grayscale_image_path

# Example usage
image_path = 'image.jpg'
grayscale_path = rgb_to_grayscale(image_path)
print(f"Grayscale image saved as: {grayscale_path}")

In this example, we define a function rgb_to_grayscale that takes the path to an RGB image as input.

We use the function from PIL to open the image. We then use the convert('L') method to convert the image to grayscale.

Next, we specify the file path and name for the grayscale image, in this case, 'grayscale.jpg'. You can change this path as per your requirement.

We save the grayscale image using the save() method and return the grayscale image’s file path.

Finally, we call the rgb_to_grayscale function with the path to the RGB image, and it will convert the image to grayscale and save it as 'grayscale.jpg' in the current directory.

Note: Make sure to install the PIL library if you haven’t already by using pip install pillow. Also, replace 'image.jpg' with the actual path to your RGB image file.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply