How to perform image manipulation in Python?
Published on Aug. 22, 2023, 12:17 p.m.
Image manipulation is a common task in many applications, and Python provides several libraries for performing image manipulation tasks. Here are some of the most common tasks:
- Reading an image: To read an image in Python, you can use the
PIL
(Python Imaging Library) library, which has been forked into thePillow
library. Here is an example code snippet:
from PIL import Image
# Open an image file
with Image.open("image.png") as img:
# Process the image
# ...
# Display the image
img.show()
- Changing the size of an image: To change the size of an image, you can use the
resize()
method of thePIL.Image
object. Here is an example code snippet:
from PIL import Image
# Open an image file
with Image.open("image.png") as img:
# Resize the image
img_resized = img.resize((100, 100))
# Display the resized image
img_resized.show()
- Cropping an image: To crop an image, you can use the
crop()
method of thePIL.Image
object. Here is an example code snippet:
from PIL import Image
# Open an image file
with Image.open("image.png") as img:
# Crop the image
img_cropped = img.crop((0, 0, 100, 100))
# Display the cropped image
img_cropped.show()
- Saving an image: To save an image, you can use the
save()
method of thePIL.Image
object. Here is an example code snippet:
from PIL import Image
# Open an image file
with Image.open("image.png") as img:
# Process the image
# ...
# Save the modified image
img.save("modified_image.png")
These are just a few examples of common image manipulation tasks in Python. Python provides many more image manipulation libraries and methods, so it’s a good idea to familiarize yourself with these libraries if you’re working with images in your code.