python两列显示两个文件夹的图片,图片名称是img_1.jpg, img_2.jpg等等
时间: 2024-09-06 20:07:40 浏览: 83
在Python中,你可以使用`os`模块来遍历文件夹,然后利用图像处理库比如`PIL` (Python Imaging Library) 或者 `opencv-python` 来打开和显示图片。下面是一个简单的示例,假设你有两个文件夹:`folder1` 和 `folder2`,并且它们都有从`img_1.jpg`开始递增命名的图片。
```python
import os
from PIL import Image
# 定义两个文件夹路径
folder1_path = 'path_to_folder1'
folder2_path = 'path_to_folder2'
# 遍历两个文件夹,读取并显示图片
for i in range(1, 3): # 这里假设每个文件夹有两张图片
img1_name = f'img_{i}.jpg'
img2_name = f'img_{i+1}.jpg' if i < 2 else None # 处理最后一个文件夹可能只有img_2.jpg的情况
try:
with Image.open(os.path.join(folder1_path, img1_name)) as img1:
print(f"Displaying image {img1_name} from folder1")
img1.show()
if img2_name:
with Image.open(os.path.join(folder2_path, img2_name)) as img2:
print(f"Displaying image {img2_name} from folder2")
img2.show()
except FileNotFoundError:
print(f"Image {img1_name}/{img2_name} not found")
阅读全文