我创建了一个for循环,循环遍历图像目录并调整每个图像的大小,然后将其保存到另一个目录.代码可以工作,但我正在try 将进程并行化,以使其速度更快.

这是调整大小函数

import cv2 
import os

def resize_image(img):
    # get the name of the file
    name = os.path.basename(img)
    # read the image
    img = cv2.imread(img)
    # resize and save to new directory
    resize = cv2.resize(img, (700, 700)) 
    resized_image = cv2.imwrite("Resized/"+name, resize)

下面是for循环,它将遍历目录中的图像(调整目录中所有图像的大小大约需要700秒).

SOURCE_DIRECTORY = "Source/"
directory_list = os.listdir(SOURCE_DIRECTORY)

for source_file in directory_list:
    source_path = os.path.join(SOURCE_DIRECTORY, source_file) 
    if os.path.isfile(source_path):
        resize_image(source_path)

为了使进程并行化,我try 使用conCurent.Futures并将其映射到RESIZE函数.

import concurrent.futures

SOURCE_DIRECTORY = "Source/"
directory_list = os.listdir(SOURCE_DIRECTORY)

with concurrent.futures.ProcessPoolExecutor() as executor: 
    executor.map(resize_image, directory_list)

但我立刻就发现了这个错误.

BrokenProcessPool: A child process terminated abruptly, the process pool is not usable anymore

我如何并行化调整图像大小的过程.任何帮助都将不胜感激.

推荐答案

以下是可用于并行化任务的示例框架(使用multiprocessing.Pool):

import os
from multiprocessing import Pool

import cv2


def resize_image(file_name):
    # get the name of the file
    name = os.path.basename(file_name)

    # just to be sure the file exists (skip if not necessary):
    if not os.path.exists(name):
        return f"{name} does not exist!"

    # read the image
    img = cv2.imread(img)
    # resize and save to new directory
    resize = cv2.resize(img, (700, 700))
    resized_image = cv2.imwrite("Resized/" + name, resize)

    return f"{name} resized."


if __name__ == "__main__":

    SOURCE_DIRECTORY = "Source/"
    directory_list = os.listdir(SOURCE_DIRECTORY)

    filelist = []
    for source_file in directory_list:
        source_path = os.path.join(SOURCE_DIRECTORY, source_file)
        if os.path.isfile(source_path):
            filelist.append(source_path)

    with Pool(4) as pool:  # 4 is number of processes we want to use
        for result in pool.imap_unordered(resize_image, filelist):
            print(result)

Python-3.x相关问答推荐

Python网页抓取:代码输出:汤未定义

安装grpcio时出现错误DeproationWarning:pkg_resource

比较和排序 DataFrame 两列中的值并在 python 中的同一行中排序

selenium 无法执行网站上最简单的功能

如何立即从asyncio.Task获取异常?

根据按不同列中的值分组的平均值划分 DataFrame

Keras 中 Conv2D 层的意外结果

提高时间复杂度的一些建议

为列表列表中的每个列表插入 str 到 index[0] 中. Python

在python中将字符串写入文本文件

有没有办法使用重采样矢量化添加缺失的月份?

在气流中运行 DAG 时出现处理信号:ttou消息

错误:预期语句,发现 py:Dedent

如何通过python打开文件

使用 Python 3 按行进行分析

asyncio.Semaphore RuntimeError: Task got Future 附加到不同的循环

如何在 Python3 中添加带有标志的命令行参数?

在不关心项目的情况下运行生成器功能的更简单方法

python 3的蓝牙库

在 Meta 中创建具有动态模型的通用序列化程序