python - 使用 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 用尽。但是,当我运行代码时,似乎什么都没有发生。我一定在某个地方犯了一个愚蠢的错误。有人会知道为什么吗?
解决方案
推荐阅读
- datagridview - 在不启动 Excel 程序的情况下从 Excel 导入 Visual Basic
- java - 如何为特定请求仅指定一个过滤器?
- arrays - Bash 中的嵌套数组来自分离的数组值的集合
- javascript - 如何通过 Javascript 中的 Google Calendar API 获取 Google Calendar 中事件的位置?
- database - 将大文件上传到 AWS 数据库
- java - osx shell 生成的 base64 无法从 Java 中解码
- javascript - 拖动项目时如何自定义 SortableJS 插件上的光标
- python - Python:通过类方法更新类属性
- java - “对象不属于指定的子类 [com.app.sportapp.entity.User]:鉴别器:玩家;-休眠,SpringBoot
- database - DBNavigator - 连接错误 - 无法识别的会话属性 - PyCharm 中的“v$session.program”