”;
Changing the color of an image by changing the pixel values in Pillow (PIL) involves manipulating the individual pixel values of an image to achieve the desired color transformation. We can perform various color operations by altering the RGB values of each pixel.
Modifying Pixel Values using the getdata() Method
We have the method namely, getdata() in pillow. It can used to retrieve the pixel data of an image. It returns a sequence of pixel values typically as a one-dimensional list or iterable where each pixel value represents the color of a pixel in the image. By using the getdata() method, you can access and modify the pixel values of an image.
The below is the syntax and parameters of the Image.getdata() method −
Image.getdata(band=None)
Where,
-
band − This specifies that what the band has to return. The default value is to return all bands. For returning a single band pass in the index value. For example 0 to get the Rband from an RGBimage.
The below are the steps to be followed for changing the color pixels of an image.
-
Open the image that we want to modify using Pillow”s Image.open() method.
-
Access the image data as a pixel-by-pixel list using image.getdata().
-
Create a new list of pixel values by changing the color as we desire.
-
Create a new image with the modified pixel values using Image.new().
-
Save or display the modified image using save().
Example
In this example we are getting the list of pixel data of the given input image by using the Image.getdata() method.
from PIL import Image #Open the image you want to modify image = Image.open("Images/python logo.png") #Access the pixel data of the image pixels = list(image.getdata()) print(pixels)
Input Image
Output
[(255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255),………………………………………………………………………………………………………………………………………………………………………….. (255, 255, 255, 255), (255, 255, 255, 255)]
Example
Here in this example we are modifying the pixel of the given input image into red by using the Image.getdata() method.
from PIL import Image #Open the image you want to modify image = Image.open("Images/three.jpg") #Access the pixel data of the image pixels = list(image.getdata()) #Define the new color you want (e.g., red) new_color = (255, 0, 0) #Red #Create a new list of pixel values with the new color modified_pixels = [new_color if pixel != (255, 255, 255) else pixel for pixel in pixels] #Create a new image with the modified pixel values modified_image = Image.new("RGB", image.size) modified_image.putdata(modified_pixels) #Save the modified image to a file modified_image.save("output Image/modified_image.jpg") #Display the modified image modified_image.show()
Input Image
Output
”;