我一直在为学校的图像处理项目工作,但在遍历包含某些图像的文件时遇到了麻烦。我为图像文件使用了一个列表,并在整个列表中运行它,但最终总是将所有图像变成列表中的最后一个。
def border_one_image(original_image):
old_images =("suit2.jpeg", "suit1.jpeg",)
for index in old_images:
print(index)
old_img = Image.open(index)
old_size = old_img.size
new_size = (700, 486)
new_img = Image.new("RGB", new_size, (255, 200, 0))
new_img.paste(old_img, ((new_size[0]-old_size[0])/2,(new_size[1]-old_size[1])/2))
new_img.show()
return new_img
这应该在图像周围创建边框,但确实如此,但是它仅对所有图像使用列表中的最后一个图像。其余的代码用于进入文件夹并在所有图像上实际放置边框。
def get_images(directory=None):
"""
Returns PIL.Image objects for all the images in directory.
If directory is not specified, uses current directory.
Returns a 2-tuple containing
a list with a PIL.Image object for each image file in root_directory, and
a list with a string filename for each image file in root_directory
"""
if directory == None:
directory = os.getcwd() # Use working directory if unspecified
image_list = [] # Initialize aggregaotrs
file_list = []
directory_list = os.listdir(directory) # Get list of files
for entry in directory_list:
absolute_filename = os.path.join(directory, entry)
try:
image = PIL.Image.open(absolute_filename)
file_list += [entry]
image_list += [image]
except IOError:
pass # do nothing with errors tying to open non-images
return image_list, file_list
def border_of_all_images(directory=None):
"""
Saves a modfied version of each image in directory.
Uses current directory if no directory is specified.
Places images in subdirectory 'modified', creating it if it does not exist.
New image files are of type PNG and have transparent rounded corners.
"""
if directory == None:
directory = os.getcwd() # Use working directory if unspecified
# Create a new directory 'modified'
new_directory = os.path.join(directory, 'border_images')
try:
os.mkdir(new_directory)
except OSError:
pass # if the directory already exists, proceed
# Load all the images
image_list, file_list = get_images(directory)
# Go through the images and save modified versions
for n in range(len(image_list)):
# Parse the filename
print(n)
filename, filetype = os.path.splitext(file_list[n])
# Round the corners with default percent of radius
curr_image = image_list[n]
new_image = border_one_image(curr_image)
# Save the altered image, suing PNG to retain transparency
new_image_filename = os.path.join(new_directory, filename + '.png')
new_image.save(new_image_filename)
border_of_all_images()