How to change the pixel values of an Image in Python?
In this blog, we will be learning about changing the pixel values of an image in Python. For this purpose, we will have to use the Python Imaging Library (abbreviated as PIL). Now let’s see how it is going to work out for us.
Importing and installing PIL
You can add any image from your library or else you can simply use the following procedure to create a simple black image.
from PIL import Image
First import the Image package from PIL. If you get any error such as the absence of PIL (expected in Python 2.7 & above) then do the following in command prompt:
pip uninstall Pillow pip uninstall PIL pip install Pillow
In the next step, import it again and get started. Now we need to import a package called display from IPython so that we can display our images with ease.
from PIL import Image from IPython.display import display
Creating or importing an image
Now, we create a black image for our purpose. Create a variable and store in that variable the pixel values and colour code and name as given below:
MyImg = Image.new( 'RGB', (250,250), "black") #Imported_Img = Image.open('ImageName.jpg') #use the commented code to import from our own computer
Creating a pixel map
pixels = MyImg.load()
We now have to change pixel values of every row and column of the image (if we consider it as a matrix of pixels).
for i in range(MyImg.size[0]): #for each column for j in range(MyImg.size[1]): #For each row pixels[i,j] = (i, j, 100) #set the colour according to your wish
Displaying the image
Finally, we display the image that is created after the change in pixel values.
display(MyImg)
The complete code to change the pixel values of an Image in Python
from PIL import Image from IPython.display import display MyImg = Image.new( 'RGB', (250,250), "black") pixels = MyImg.load() # creates the pixel map display(MyImg) # displays the black image for i in range(MyImg.size[0]): for j in range(MyImg.size[1]): pixels[i,j] = (i, j, 100) display(MyImg) # displays the changed colourful image
This is outstanding application and learning.
for i in range(MyImg.size[0]): #for each column
in this line should n’t it be for each row
?
after that we iterate over columns then next row
How to convert pixels values into a image ..
you can add the following to save the image:
MyImg.save(‘directory\filename’)
#eg: MyImg.save(‘C:\pythonImages\myimage.jpg’)