原图片尺寸大小为720*1280,现要求得到尺寸为800*800的图片,python代码如下:
from PIL import Image
import os
def batch_crop_images(input_dir, output_dir, target_size):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.endswith(".jpg") or filename.endswith(".png"):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
image = Image.open(input_path)
width, height = image.size
new_width = min(width, height)
new_height = new_width
left = (width - new_width) / 2
top = (height - new_height) / 2
right = left + new_width
bottom = top + new_height
cropped_image = image.crop((left, top, right, bottom))
resized_image = cropped_image.resize(target_size, Image.ANTIALIAS)
resized_image.save(output_path)
input_directory = '/home/dl/wj/nerf/nerf-pytorch-master/data/nerf_llff_data/cup/images'
output_directory = '/home/dl/wj/nerf/nerf-pytorch-master/data/nerf_llff_data/cup/cut_images'
target_size = (800, 800)
batch_crop_images(input_directory, output_directory, target_size)
代码解释:
我们首先计算了调整后图像的宽度和高度。我们选择将宽度和高度中的较小值作为新的宽度和高度。这样可以确保裁剪后的图像是一个正方形。
然后,我们根据新的宽度和高度计算裁剪框的位置,使其位于图像中心。
接下来,我们使用image.crop
方法根据裁剪框裁剪图像,并使用cropped_image.resize
方法将裁剪后的图像调整为目标尺寸。
最后,我们将调整大小后的图像保存到输出路径。
这种方法将图像裁剪为一个正方形,并在保持图像纵横比的同时,将其调整为填充整个800x800区域。
请记得将'/home/dl/wj/nerf/nerf-pytorch-master/data/nerf_llff_data/cup/images'
替换为输入目录的实际路径,将'/home/dl/wj/nerf/nerf-pytorch-master/data/nerf_llff_data/cup/cut_
images'
替换为输出目录的实际路径。
同样,根据需要修改target_size
以适应你的要求。