【发布时间】:2019-03-27 00:50:46
【问题描述】:
我正在编写一个程序,它遍历卫星图像目录,将每个图像裁剪为具有正方形纵横比 (1:1),然后将裁剪后的图像保存在程序开始时创建的不同目录中.我能够成功裁剪每张图像,但裁剪后的图像被保存到其原始目录,而不是在程序开始时创建的目录。
例如,指向但不包括包含图像的目录的文件路径是C:\Users\nickm\Documents\Projects\Platform\Imagery,而包含卫星图像的目录是dir(Imagery 的子目录)。每个图像被裁剪后,我想将其保存到程序开始时创建的目录(例如10-22-18 cropped,这也是Imagery的子目录)。相反,它被保存在dir 中,覆盖了原始图像。
这是我的代码:
# image.py
import datetime
import os
from PIL import Image
def make_new_dir(abs_path):
'''Creates the directory where our cropped imagery will be saved and
returns its absolute file path.
'''
date_obj = datetime.datetime.now()
date = date_obj.strftime('%x').replace('/', '-')
new_path = abs_path + '/' + date + ' cropped'
os.mkdir(new_path)
return new_path
def get_crop_area(image):
'''Crops each image to have a square aspect ratio (1:1) using the
image's size.
'''
image_width, image_height = image.size
diff = max(image_width, image_height) - min(image_width, image_height)
if image_width > image_height:
return [diff / 2, 0, image_width - diff / 2, image_height]
else:
return [0, diff / 2, image_width, image_height - diff / 2]
def crop_images(abs_path, image_dir, new_dir):
'''Iterates over the directory containing the satellite images
(abs_path + image_dir), cropping each image and saving it to our
new directory (the value returned from our make_new_dir function).
'''
new_dir = os.path.abspath(new_dir)
image_dir = os.path.join(abs_path, image_dir)
images = os.listdir(image_dir)
for image in images:
image_path = os.path.join(image_dir, image)
image = Image.open(image_path)
crop_area = get_crop_area(image)
cropped_image = image.crop(crop_area)
cropped_image_path = os.path.join(new_dir, image.filename)
cropped_image.save(cropped_image_path, 'JPEG')
程序正在使用run.py 运行。 abs_path 和 image_dir 由用户在命令行中提供,并在我们的 make_new_dir 和 crop_images 函数中用作参数。这就是我从命令行启动脚本时的样子:
C:\Users\nickm\Documents\Projects\Code\image>python run.py C:\Users\nickm\Documents\Projects\Platform\Imagery dir
请注意,绝对文件路径和包含图像的目录是两个不同的命令行参数。
这是我的run.py 脚本:
# run.py
import sys
from image import make_new_dir, get_crop_area, crop_images
if __name__ == '__main__':
filename, abs_path, image_dir = sys.argv
new_dir = make_new_dir(abs_path)
crop_images(abs_path, image_dir, new_dir)
这是我创建的第一个不仅仅是基本编码练习的程序,所以我想知道我是否错误地实现了os.path.join。我查看了here 和here 以进行澄清,但两者都没有使用os 模块,我很确定这是我遇到问题的地方。
提前感谢您提供的任何帮助。
【问题讨论】:
-
嗨@NicholasMaloof image.filename 是否返回绝对路径?
-
image.filename返回文件名。我将它附加到new_dir以创建新创建目录的文件路径。 -
是的,但问题是如果 image.filename 是图像的绝对路径 os.path.join 将返回该路径,这可能是图像被写入的原因同一个目录
-
我明白你在说什么,你是对的。
image.filename返回图像的绝对路径。我将研究如何仅获取文件名并回答我自己的问题,除非有人击败我。我想知道为什么它只返回图像的绝对路径而忽略new_dir的绝对路径。我假设如果我没有正确加入他们,那么它会返回一条错误消息。
标签: python python-3.x operating-system python-imaging-library