python遍历一个文件夹中的图片,每张图片与之前的图片一一比较,如果相同则将其删除
时间: 2023-10-07 18:09:48 浏览: 113
你可以使用 Python 的 `os` 和 `PIL` 库来实现这个功能,具体步骤如下:
1. 导入需要的库
```python
import os
from PIL import Image
```
2. 定义一个函数来比较两张图片是否相同
```python
def compare_images(image1_path, image2_path):
image1 = Image.open(image1_path)
image2 = Image.open(image2_path)
return image1 == image2
```
3. 获取文件夹中所有的图片路径
```python
folder_path = "/path/to/folder"
image_paths = [os.path.join(folder_path, filename) for filename in os.listdir(folder_path) if filename.endswith(".jpg") or filename.endswith(".png")]
```
4. 遍历所有的图片路径,依次和前面的图片比较
```python
for i in range(len(image_paths)):
current_image_path = image_paths[i]
for j in range(i):
previous_image_path = image_paths[j]
if compare_images(current_image_path, previous_image_path):
os.remove(current_image_path)
break
```
5. 完整代码如下:
```python
import os
from PIL import Image
def compare_images(image1_path, image2_path):
image1 = Image.open(image1_path)
image2 = Image.open(image2_path)
return image1 == image2
folder_path = "/path/to/folder"
image_paths = [os.path.join(folder_path, filename) for filename in os.listdir(folder_path) if filename.endswith(".jpg") or filename.endswith(".png")]
for i in range(len(image_paths)):
current_image_path = image_paths[i]
for j in range(i):
previous_image_path = image_paths[j]
if compare_images(current_image_path, previous_image_path):
os.remove(current_image_path)
break
```
阅读全文