Remove a Specific Color From An Image in Python

In this tutorial, we are going to learn how to remove a specific color from an image in the Python program. To achieve this, we will use the PIL python library. PIL allows us to manipulate our image files. PIL or Pillow lets us perform operations like rotate, resize, modification of color, etc.

We have an image file named “pic.jpeg”, we will remove ‘RED’ color from this image and save our image as “changd.jpeg”.

So, Let’s discuss the steps involved:

  • Importing Image module from Pillow (PIL).
    from PIL import Image
  • Taking the image file input.
    image = Image.open('pic.jpeg')

    syntax : image = Image.open(‘your file name with extension’).

  • To check if the right image file is being imported, Let’s see the image.
    image.show()

    rose with blue sky

  • Reading image data from the “.jpeg file”.
    image_data = image.load()
  • Storing the size of the image.
    height,width = image.size
  • Going through each pixel of the image and setting the (r,g,b) value as (0,g,b), i.e setting the value for RED as 0.
    If you want to remove GREEN or BLUE color then assign the values accordingly.

    for loop1 in range(height):
        for loop2 in range(width):
            r,g,b = image_data[loop1,loop2]
            image_data[loop1,loop2] = 0,g,b
  • Saving our image after removing RED color from it, and naming it “changed.jpeg”.
    image.save('changed.jpeg')

     

Once all the above steps are performed, your image file named “changed.jpeg” will be saved in the directory.

Now, open “changed.jpeg” to check if the RED color is removed from the initial image.

black rose

The complete Python program

The complete Python code to remove specific color from our image is given below:

from PIL import Image

image = Image.open('pic.jpeg')

image.show()

image_data = image.load()

height,width = image.size

for loop1 in range(height):
    for loop2 in range(width):
        r,g,b = image_data[loop1,loop2]
        image_data[loop1,loop2] = 0,g,b

image.save('changed.jpeg')

I hope, you will try it on your own machine with your own image. Have fun with it…

Also, read: How to Crop an Image in Python?

 

2 responses to “Remove a Specific Color From An Image in Python”

  1. Tanmay Singh says:

    Nicely explained Sir!

Leave a Reply

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