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:
1 |
pip install pillow |
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:
1 |
from PIL import Image |
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:
1 |
image = Image.open('robot.jpg') |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Get the width and height of the image width, height = image.size # Create a new RGB image with the same dimensions red_image = Image.new('RGB', (width, height)) # Iterate over the pixels in the original image for x in range(width): for y in range(height): # Get the RGB values of the current pixel r, g, b = image.getpixel((x, y)) # Set the pixel value in the red image to (r, 0, 0) red_image.putpixel((x, y), (r, 0, 0)) |
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:
1 |
red_image.save('red_robot.jpg') |
Replace ‘path/to/save/new_image.jpg’ with the desired output file name and location.
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
from PIL import Image # Load the image image = Image.open('robot.jpg') # Get the width and height of the image width, height = image.size # Create a new RGB image with the same dimensions red_image = Image.new('RGB', (width, height)) # Iterate over the pixels in the original image for x in range(width): for y in range(height): # Get the RGB values of the current pixel r, g, b = image.getpixel((x, y)) # Set the pixel value in the red image to (r, 0, 0) red_image.putpixel((x, y), (r, 0, 0)) # Save the output image red_image.save('red_robot.jpg') |
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.