Image Processing in Python
#original Image
from PIL import Image
Image.open('clcodingmr.jpg')
1. Image Resizing:
from PIL import Image
def resize_image(image_path, output_path, width, height):
image = Image.open(image_path)
resized_image = image.resize((width, height))
resized_image.save(output_path)
# Example usage:
resize_image('clcodingmr.jpg', 'resized_output.jpg', 300, 200)
# Now, open and show the resized image
Image.open('clcodingmr.jpg')
Image.open('resized_output.jpg')
2. Image Rotation with Pillow:
from PIL import Image
def rotate_image(image_path, output_path, angle):
image = Image.open(image_path)
rotated_image = image.rotate(angle)
rotated_image.save(output_path)
# Example usage:
rotate_image('clcodingmr.jpg', 'rotated_output.jpg', 45)
Image.open('rotated_output.jpg')
3. Image Translation (using crop) with Pillow:
from PIL import Image
def translate_image(image_path, output_path, tx, ty):
image = Image.open(image_path)
translated_image = image.crop((tx, ty, image.width, image.height))
translated_image.save(output_path)
# Example usage:
translate_image('clcodingmr.jpg', 'translated_output.jpg', 50, 30)
Image.open('translated_output.jpg')
4. Image Shearing (using affine transform) with Pillow:
Image.open('sheared_output.jpg')
from PIL import Image, ImageOps
def shear_image(image_path, output_path, shear_factor):
image = Image.open(image_path)
shear_matrix = [1, shear_factor, 0, 0, 1, 0]
sheared_image = image.transform(image.size, Image.AFFINE, shear_matrix)
sheared_image.save(output_path)
# Example usage:
shear_image('clcodingmr.jpg', 'sheared_output.jpg', 0.2)
Image.open('sheared_output.jpg')
5. Image Normalization (simple contrast adjustment) with Pillow:
from PIL import Image
def normalize_image(image_path, output_path):
image = Image.open(image_path)
normalized_image = ImageOps.autocontrast(image)
normalized_image.save(output_path)
# Example usage:
normalize_image('clcodingmr.jpg', 'normalized_output.jpg')
Image.open('normalized_output.jpg')
6. Image Blurring (using a filter) with Pillow:
from PIL import Image, ImageFilter
def blur_image(image_path, output_path, radius):
image = Image.open(image_path)
blurred_image = image.filter(ImageFilter.GaussianBlur(radius))
blurred_image.save(output_path)
# Example usage:
blur_image('clcodingmr.jpg', 'blurred_output.jpg', 5)
Image.open('blurred_output.jpg')
0 Comments:
Post a Comment