Python Pillow - 影像剪裁和貼上



剪裁影像

Pillow(Python 影像庫)允許我們從影像中提取矩形區域。提取的影像區域也稱為影像的邊界框。在crop()方法中,Image模組建立一個新的影像,表示原始影像的指定區域。此方法允許我們指定要裁剪區域的邊界框的座標。

以下是 Pillow 中'crop()'方法的語法和用法:

Image.crop(box)

其中,

  • box - 這是一個元組,指定我們要提取的矩形區域。box 引數應為四個值的元組:(左,上,右,下)。

    • left 是邊界框左邊緣的 x 座標。

    • upper 是邊界框上邊緣的 y 座標。

    • right 是邊界框右邊緣的 x 座標。

    • lower 是邊界框下邊緣的 y 座標。

示例

在這個示例中,我們根據需要使用Image模組的crop()方法裁剪矩形部分。

from PIL import Image

#Open the image
image = Image.open("Images/book.jpg")

#Define the bounding box for cropping
box = (100, 100, 200, 200)  
#(left, upper, right, lower)

#Crop the image using the defined bounding box
cropped_image = image.crop(box)

#Save or display the cropped image
cropped_image.save("output Image/cropped_image.jpg")
cropped_image.show()

要裁剪的影像

book

輸出

cropped image

示例

這是另一個使用crop()方法裁剪影像矩形部分的示例。

from PIL import Image

#Open the image
image = Image.open("Images/rose.jpg")

#Define the bounding box for cropping
box = (10, 10, 200, 200)  
#(left, upper, right, lower)

#Crop the image using the defined bounding box
cropped_image = image.crop(box)

#Save or display the cropped image
cropped_image.save("output Image/cropped_image.jpg")
cropped_image.show()

輸入影像

flower

輸出

cropped_image

貼上影像

使用 Python Pillow 貼上影像允許我們從一個影像中提取感興趣的區域並將其貼上到另一個影像上。此過程可用於影像裁剪、物件提取和合成等任務。

Pillow(Python 影像庫)中的paste()方法允許我們將一個影像貼上到另一個影像的指定位置。這是一種常用的影像合成方法,用於新增水印或將一個影像疊加到另一個影像上。

以下是paste()函式的語法和引數:

PIL.Image.paste(im, box, mask=None)
  • im - 這是源影像,即我們要貼上到當前影像上的影像。

  • box - 此引數指定我們要貼上源影像的位置。它可以是座標元組'(左,上,右,下)'。源影像將貼上到這些座標定義的邊界框內。

  • mask(可選) - 如果提供此引數,則它可以是定義透明蒙版的影像。貼上的影像將根據蒙版影像中的透明度值進行蒙版。

示例

以下是如何使用paste()方法將一個影像貼上到另一個影像上的示例。

from PIL import Image

#Open the background image
background = Image.open("Images/bw.png")

#Open the image to be pasted
image_to_paste = Image.open("Images/tutorialspoint.png")

#Define the position where the image should be pasted
position = (100, 100)

#Paste the image onto the background
background.paste(image_to_paste, position)

#Save the modified image
background.save("OutputImages/paste1.jpg")
background.show()

要使用的影像

black white tutorialpoint

輸出

paste1
廣告