首页 > 解决方案 > 使用 concurrent.futures.ProcessPoolExecutor 在 Python 中进行多处理

问题描述

我刚刚阅读了有关使用 concurrent.futures 进行多处理的教程,并且正在尝试使自己的代码更高效。

# Return a manipulated image with mosaic implemented
def photo_mosaic(imagePath, imageDict, step, targetWidth=2500):
    print("Creating a mosaic...")
    image = get_image(imagePath)  # load main image to make photo mosaic
    width, height = image.size  # get width and height
    if width < targetWidth:  # enlarge image
        image = resize_image(image, targetWidth=targetWidth)
        width, height = image.size
    pixels = list(image.getdata())  # get list of RGB values from image
    matrix = [[pixels[width * y + x] for x in range(width)] for y in range(height)]  # get 2D array of RGB values

    editedImage = Image.new(image.mode, (width, height))  # instantiate new image
    processed = {'value': 0}

    def process_image(y):
        y2 = y + step if y + step < height else height  # make end point y + step if not over height, else height
        for x in range(0, width, step):  # loop over columns until exhaustion
            x2 = x + step if x + step < width else width  # make end point x + step if not over width, else width
            subList = []  # instantiate new list to append subMatrix values to
            for z in range(y, y2):  # loop over subMatrix
                subMatrix = matrix[z][x:x2]
                subList.append(subMatrix)
            flat_list = [rgbTuple for elem in subList for rgbTuple in elem]  # flatten list
            average = get_average(flat_list)  # get average RGB tuple
            img = best_match(average, imageDict)  # find best matching image
            editedImage.paste(img, (x, y))  # paste image to x, y coordinate
        progress_bar(processed['value'], height)
        processed['value'] += step

    yList = list(range(0, height, step))
    with ProcessPoolExecutor() as executor:
        executor.map(process_image, yList)

我将 process_image 函数嵌套在我的主函数 photo_mosaic 中。基本上,我试图将 y 值的处理传播到每个 CPU,直到 yList 用尽。但是,当我运行代码时,似乎什么都没有发生。我一定在某个地方犯了一个愚蠢的错误。有人会知道为什么吗?

标签: pythonmultiprocessing

解决方案


推荐阅读