import os from PIL import Image # 定义一个函数,判断图片是否全黑 def is_black_image(filepath): img = Image.open(filepath) width, height = img.size for x in range(width): for y in range(height): pixel = img.getpixel((x,y)) if sum(pixel) != 0: return False return True # 遍历文件夹,判断并删除纯黑照片 def batch_delete_black_images(folder_path): for f in os.listdir(folder_path): file_path = os.path.join(folder_path, f) if os.path.isfile(file_path): if is_black_image(file_path): os.remove(file_path) print('{} has been deleted successfully.'.format(file_path)) # 调用函数批量删除 batch_delete_black_images(r'F:\H18\Dfinal640.tif\8-5')
时间: 2024-03-07 21:49:39 浏览: 134
Python各类图像库的图片读写方式总结(推荐)
你的代码已经实现了批量删除文件夹内的纯黑照片,可以直接运行。但是需要注意的是,你的文件夹路径中包含了文件名,应该将文件名从文件夹路径中分离出来,只保留文件夹路径。
修改后的代码如下:
```python
import os
from PIL import Image
# 定义一个函数,判断图片是否全黑
def is_black_image(filepath):
img = Image.open(filepath)
width, height = img.size
for x in range(width):
for y in range(height):
pixel = img.getpixel((x,y))
if sum(pixel) != 0:
return False
return True
# 遍历文件夹,判断并删除纯黑照片
def batch_delete_black_images(folder_path):
for f in os.listdir(folder_path):
file_path = os.path.join(folder_path, f)
if os.path.isfile(file_path):
if is_black_image(file_path):
os.remove(file_path)
print('{} has been deleted successfully.'.format(file_path))
# 调用函数批量删除
batch_delete_black_images(r'F:\H18\Dfinal640.tif\8-5')
```
其中,r'F:\H18\Dfinal640.tif\8-5'是你的文件夹路径,需要根据实际情况进行修改。
阅读全文