优化使得每检索50张照片,执行一次删除任务,并输出已删除照片数:import os from PIL import Image from multiprocessing import Pool def is_black_image(file_path): with Image.open(file_path) as img: pixels = list(img.getdata()) if all(sum(pixel) == 0 for pixel in pixels): return True else: return False def delete_black_images(file_path): if is_black_image(file_path): os.remove(file_path) print('{} has del'.format(file_path)) def batch_delete_black_images(folder_path): file_list = [] for f in os.listdir(folder_path): file_path = os.path.join(folder_path, f) if os.path.isfile(file_path): file_list.append(file_path) with Pool() as p: p.map(delete_black_images, file_list) if name == 'main': batch_delete_black_images(r'F:\H18\Dfinal640.tif\8-2')
时间: 2024-03-10 09:49:54 浏览: 21
为了每检索50张照片执行一次删除任务,并输出已删除照片数,您可以在 `batch_delete_black_images` 函数中添加一个计数器和一个列表,分别用于记录已删除的文件数和待删除的文件路径。具体地,您可以在函数中添加一个变量 `count` 和一个列表 `to_delete`,每次调用 `delete_black_images` 函数时,将文件路径添加到 `to_delete` 列表中,并将计数器加1。当计数器能够被50整除时,调用 `p.map` 函数删除 `to_delete` 列表中的所有文件,并将已删除文件数加到计数器中。下面是修改后的代码:
```
import os
from PIL import Image
from multiprocessing import Pool
def is_black_image(file_path):
with Image.open(file_path) as img:
pixels = list(img.getdata())
if all(sum(pixel) == 0 for pixel in pixels):
return True
else:
return False
def delete_black_images(file_path):
if is_black_image(file_path):
os.remove(file_path)
return True
return False
def batch_delete_black_images(folder_path):
file_list = []
count = 0
to_delete = []
for f in os.listdir(folder_path):
file_path = os.path.join(folder_path, f)
if os.path.isfile(file_path):
file_list.append(file_path)
with Pool() as p:
for file_path in file_list:
to_delete.append(file_path)
count += 1
if count % 50 == 0:
results = p.map(delete_black_images, to_delete)
deleted_count = sum(results)
print('已删除 {} 张照片'.format(deleted_count))
to_delete = []
count = deleted_count
if to_delete:
results = p.map(delete_black_images, to_delete)
deleted_count = sum(results)
print('已删除 {} 张照片'.format(deleted_count))
if __name__ == '__main__':
batch_delete_black_images(r'F:\H18\Dfinal640.tif\8-2')
```
注意,为了避免多个进程同时打印已删除照片数,我们只在每50次删除操作后打印已删除照片数。同时,为了避免最后一次删除操作没有达到50次而未能打印已删除照片数,我们在函数末尾添加了一个额外的 `if` 语句来处理剩余的待删除文件。