Python遍历文件夹图片并显示

在Python编程中,经常会遇到需要遍历文件夹中的图片并进行处理的情况。这种需求在图像处理、机器学习等领域非常常见。本文将介绍如何使用Python编程语言来实现遍历文件夹中的图片,并且显示这些图片。

步骤1:导入必要的库

首先,我们需要导入必要的库来处理文件夹和图片。在Python中,常用的处理图像的库有PILOpenCV。本文我们将使用PIL库来实现。

from PIL import Image
import os

步骤2:定义遍历文件夹函数

接下来,我们需要定义一个函数来遍历文件夹,并返回文件夹中的所有图片文件路径。我们可以使用os库的listdir函数来获取文件夹中的所有文件,然后使用os.path库的isfile函数来判断文件是否为图片文件。

def get_image_files(folder_path):
    image_files = []
    for file_name in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file_name)
        if os.path.isfile(file_path):
            if file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
                image_files.append(file_path)
    return image_files

步骤3:显示图片

现在,我们已经获取了文件夹中的所有图片文件路径。接下来,我们可以使用PIL库的open函数来打开图片,并使用show函数来显示图片。

def show_images(image_files):
    for file_path in image_files:
        image = Image.open(file_path)
        image.show()

步骤4:完整代码

下面是完整的代码示例:

from PIL import Image
import os

def get_image_files(folder_path):
    image_files = []
    for file_name in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file_name)
        if os.path.isfile(file_path):
            if file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
                image_files.append(file_path)
    return image_files

def show_images(image_files):
    for file_path in image_files:
        image = Image.open(file_path)
        image.show()

folder_path = 'path/to/folder'
image_files = get_image_files(folder_path)
show_images(image_files)

总结

通过以上代码示例,我们学习了如何使用Python编程语言来遍历文件夹中的图片,并显示这些图片。这个方法可以用于图像处理、机器学习等领域的应用。希望本文对你有所帮助!