from PIL import Image, ImageFilter, ImageOps
def load_image(path):
return Image.open(path)
def convert_to_grayscale(image):
return image.convert('L')
def crop_image(image, size):
width, height = image.size
left = (width - size[0])/2
top = (height - size[1])/2
right = (width + size[0])/2
bottom = (height + size[1])/2
return image.crop((left, top, right, bottom))
def rotate_image(image, angle):
return image.rotate(angle)
def flip_image(image, direction):
if direction == 'horizontal':
return image.transpose(Image.FLIP_LEFT_RIGHT)
elif direction == 'vertical':
return image.transpose(Image.FLIP_TOP_BOTTOM)
else:
print("Invalid direction! Use 'horizontal' or 'vertical'")
return image
def smooth_image(image):
return image.filter(ImageFilter.SMOOTH)
def detect_edges(image):
return image.filter(ImageFilter.FIND_EDGES)
# Ví dụ cách sử dụng các chức năng
if __name__ == "__main__":
img_path = 'path_to_your_image.jpg' # Thay thế đường dẫn đến ảnh của bạn
image = load_image(img_path)
# Convert to grayscale
grayscale_image = convert_to_grayscale(image)
grayscale_image.show()
# Crop image to 200x200
cropped_image = crop_image(image, (200, 200))
cropped_image.show()
# Rotate image by 90 degrees
rotated_image = rotate_image(image, 90)
rotated_image.show()
# Flip image horizontally
flipped_image = flip_image(image, 'horizontal')
flipped_image.show()
# Smooth image
smoothed_image = smooth_image(grayscale_image) # Smooth chỉ áp dụng tốt trên ảnh xám
smoothed_image.show()
# Detect edges
edges_image = detect_edges(grayscale_image)
edges_image.show()
Lưu ý rằng bạn cần thay "path_to_your_image.jpg" bằng đường dẫn thực tế đến ảnh cần xử lý trên máy của bạn. Chương trình này chỉ bao gồm các chức năng cơ bản. Để sử dụng ảnh trong các tình huống cụ thể và tích hợp chúng trong các ứng dụng thực tế, bạn cần viết thêm mã để xử lý các ngoại lệ và điều kiện đặc biệt tùy vào yêu cầu của dự án.