如何将不同长度和宽度的图像裁切成相等的长度和宽度?

时间:2019-05-28 12:31:58

标签: python image crop

我正在使用COCO数据集。数据集图像的长度和宽度不同,但是我必须将它们裁切成相等的长度和宽度。

所有图像都放置在一个文件夹中。我试图将它们裁剪成相等的长度和宽度,即386X386

import sys
import os
from PIL import Image

filepath = "/content/drive/My Drive/Colab Notebooks/SRGAN/data"

# Loop through all provided arguments
for filename in os.listdir(filepath):
    if "." not in filename:
        continue
    ending = filename.split(".")[1]
    if ending not in ["jpg", "gif", "png"]:
        continue


    # Attempt to open an image file
    image = Image.open(os.path.join(filepath, filename))


    # Perform operations on the image here
    image = image.crop((0, 0, 386, 386))

    # Split our origional filename into name and extension 
    name, extension = os.path.splitext(filename)

    # Save the image as "(origional_name)_thumb.jpg
    print(name + '_cropped.jpg')
    image.save(os.path.join("/content/drive/My Drive/Colab Notebooks/SRGAN/data", name + '_cropped.jpg'))

它应该将所有图像裁剪为386X386大小,但它会生成同一图像的多个副本,这些副本的长度和宽度都不同。

1 个答案:

答案 0 :(得分:0)

from keras.preprocessing import image
test_img = image.load_img('Image Path', target_size=(386,386))

“目标尺寸”定义了要裁剪的尺寸。