? 前兩天想要把連續(xù)的不同幀的靜態(tài)圖片拼成一個(gè)GIF圖片,但是原來(lái)的圖片需要裁剪,而且存在很多張,幸好這么多張的圖片裁剪的位置是一樣的,于是我便嘗試用Python優(yōu)雅地批量裁剪這些圖片。
? 首先介紹一下Python裁剪照片的原理。代碼的輸入是圖片的地址和兩個(gè)點(diǎn)的坐標(biāo),這兩個(gè)點(diǎn)的坐標(biāo)分別表示一個(gè)矩形的左上角頂點(diǎn)和右下角頂點(diǎn),這個(gè)矩形就是你的裁剪區(qū)域。
? 寫代碼前,先引入一下所需要的庫(kù)。
from PIL import Image, ImageDraw, ImageFont
? 那么你一定會(huì)有個(gè)疑問(wèn),怎么確定圖片矩形區(qū)域的頂點(diǎn)位置呢?下面貼出一個(gè)在原圖像上繪制邊界框的代碼。
def draw_bbox(image_path, bbox, output_path):
"""
Draw bounding box on the image.
Parameters:
image_path (str): Path to the input image file.
bbox (tuple): Bounding box coordinates (left, upper, right, lower).
output_path (str): Path to save the image with bounding box.
Returns:
None
"""
# Open image
img = Image.open(image_path)
# Draw bounding box
draw = ImageDraw.Draw(img)
draw.rectangle(bbox, outline="red", width=3)
# Add text with coordinates
font = ImageFont.truetype("arial.ttf", 20)
draw.text((bbox[0], bbox[1]), f"{bbox}", fill="red", font=font)
# Save image with bounding box
img.save(output_path)
input_image_path = r"F:\Desktop\woman.jpg"
output_image_path = r"F:\Desktop\woman.jpg"
crop_box = (700, 550, 1850, 1000) # Define crop box (left, upper, right, lower)
draw_bbox(input_image_path, crop_box, output_image_path)
? crop_box(x1, y1, x2, y2),其中左上角頂點(diǎn)表示為(x1, y1),右下角頂點(diǎn)表示為(x2, y2)。但是你只能通過(guò)不斷摸索crop_box的取值,根據(jù)原圖像上繪制的邊界框,逐漸確定你最后的裁剪區(qū)域。下面給出運(yùn)行draw_bbox代碼的可視化例子。
? 用draw_bbox拿到合適的crop_box以后,下面給出裁剪圖片的代碼。
def crop_image(input_image_path, output_image_path, crop_box):
"""
Crop an image using the specified crop box.
Parameters:
input_image_path (str): Path to the input image file.
output_image_path (str): Path to save the cropped image.
crop_box (tuple): Crop box coordinates (left, upper, right, lower).
Returns:
None
"""
# Open image
img = Image.open(input_image_path)
# Crop image
cropped_img = img.crop(crop_box)
# Save cropped image
cropped_img.save(output_image_path)
print("Image cropped and saved successfully.")
? 最后給出裁剪以后的可視化例子。
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-843699.html
? 如果想要批量裁剪圖片的話,就在外面套一個(gè)循環(huán)就可以了。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-843699.html
到了這里,關(guān)于Python批量裁剪圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!