Python pillow library allows us can change image color easily. In this tutorial, we will use an example to show you how to change a specific color of an image to other color.
Load image using python pillow
First, we should load image file.
from PIL import Image import numpy as np img = Image.open("file.png")
The file.png is:
Get image mode and size
Image mode determines the data structure of each pixel in image, we can process each pixel by size.
print(img.mode) #RGB print(img.size)
Run this code, we can find the mode of image is RGB, the size is (640, 640)
Change color pixel by pixel
We can change the color pixel by pixel.
In order to get the color of a pixel, we can use img.getpixel((i,j)). To change the color of a pixel, we can use img.putpixel((i,j),(44, 44, 44))
In this tutorial, we will change white color (#ffffff) or (255, 255, 255) to #444444 or (68, 68, 68)
Best Practice to Python Convert Hex Color to RGB – Python Tutorial
Here is the example code.
width = img.size[0] height = img.size[1] for i in range(0,width):# process all pixels for j in range(0,height): data = img.getpixel((i,j)) #print(data) #(255, 255, 255) if (data[0]==255 and data[1]==255 and data[2]==255): img.putpixel((i,j),(44, 44, 44)) img.show()
Run this code, you will get a new image.
Thanks a lot.
This is helpful for me.