Pillow - 裁剪影像



在 Pillow(Python 影像庫)中裁剪影像涉及選擇影像的特定區域或子區域,並從該區域建立新影像。此操作可用於去除影像中不需要的部分,專注於特定主題或將影像調整為特定尺寸。

Pillow 庫的 **Image** 模組提供了 **crop()** 方法來對影像執行裁剪操作。

使用 crop() 方法裁剪影像

可以透過使用 crop() 方法裁剪影像,該方法允許我們定義一個框,指定要保留的區域的左、上、右和下角的座標,然後它會建立一個僅包含原始影像該部分的新影像。

以下是 Pillow 庫中 **crop()** 方法的基本語法:

PIL.Image.crop(box)

其中,

  • **box** - 一個元組,以 (left, upper, right, lower) 的格式指定裁剪框的座標。這些座標表示我們要保留的矩形區域的左、上、右和下邊緣。

示例

在此示例中,我們透過傳遞我們要裁剪的影像區域的左、上、右和下角,使用 **crop()** 方法裁剪影像。

from PIL import Image

#Open an image
image = Image.open("Images/saved_image.jpg")

# Display the inaput image 
image.show()

#Define the coordinates for the region to be cropped (left, upper, right, lower)
left = 100  
upper = 50  
right = 300  
lower = 250 

#Crop the image using the coordinates
cropped_image = image.crop((left, upper, right, lower))

#Display the cropped image as a new file
cropped_image.show()

輸出

以上程式碼將生成以下輸出:

輸入影像

crop_image_input

輸出影像(裁剪後的影像)

crop_output image

示例

這是一個使用 crop() 方法對輸入影像的指定部分執行裁剪操作的另一個示例。

from PIL import Image

#Open an image
image = Image.open("Images/yellow_car.jpg")

# Display the inaput image 
image.show()

#Define the coordinates for the region to be cropped (left, upper, right, lower)
left = 100  
upper = 100  
right = 300  
lower = 300 

#Crop the image using the coordinates
cropped_image = image.crop((left, upper, right, lower))

#Display the cropped image 
cropped_image.show()

輸出

執行上述程式碼後,您將獲得以下輸出:

輸入影像

crop_image_input

輸出(裁剪後的影像)

crop_output image
廣告