How To Extract Red Color From An Image In Python

In this tutorial, you will learn how to extract the red color from an image in Python. This can be helpful in various applications such as image analysis, computer vision or simply enhancing the aesthetics of an image.

We’ll use the popular image-processing library, Pillow (PIL), to perform this task.

Step 1: Install the Pillow Library

If you do not have the Pillow library already installed, you’ll need to install it first. You can do this using pip:

Make sure the installation is successful before proceeding to the next step.

Step 2: Import the Required Libraries

First, we need to import the necessary modules from the Pillow library. Import Image and ImageOps:

Step 3: Load the Image

Choose an image from your computer and load it with the following code, replacing the filename with the path to your own image:

I’m going to use this one:

Step 4: Extract the Red Color

Next, we will extract the red color from the image by iterating over the pixels and setting both the green and blue color channels to zero. Here’s how you can do it:

After running this snippet, you’ll have a new image object (red_image) that only contains red hues.

Step 5: Save the Output Image

Now that we have extracted the red color, save the output image using the following line of code:

Replace ‘path/to/save/new_image.jpg’ with the desired output file name and location.

Full Code:

Output

Conclusion

In this tutorial, we have learned how to extract red color from an image using Python and the Pillow library. This can come in handy for a variety of applications, including image analysis and computer vision. We encourage you to experiment with different colors and see how this method can be adapted to suit your needs.