簡體   English   中英

Python 多處理循環與多個 arguments

[英]Python multiprocessing for loop with multiple arguments

我正在嘗試獲取圖像的像素坐標(僅白色像素)

當然這是一個耗時的任務,我應用了多處理。

它有效,但我不確定我是否做對了。

imagee = cv2.imread('cv02.png')

def func1(y, x):
    if imagee[y][x][0] == 255 and imagee[y][x][1] == 255 and imagee[y][x][0] == 255:
        maskk.append([y, x])
        return [y, x]
    else:
        pass

def func2(y, x, imagee):
    if imagee[y][x][0] == 255 and imagee[y][x][1] == 255 and imagee[y][x][0] == 255:
        return [y, x]
    else:
        pass

image = cv2.imread('cv02.png')
height, width, c = image.shape
width = 5; height = 2 # for simple debug

w = [i for i in range(width)] * height
h = [j for j in range(height)] * width
pixel_list = [[i, j] for i in range(height) for j in range(width)]

with Pool(5) as p:
    t= p.starmap(func1, pixel_list)
list1 = [tt for tt in t if tt is not None]
print(list1) # [[0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4]]


pixel_list2 = [[i, j, image] for i in range(height) for j in range(width)]
with Pool(5) as p:
    t= p.starmap(func2, pixel_list2)
list2 = [tt for tt in t if tt is not None]
print(list2) # [[0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4]]

我想出了兩種方法,它們看起來都不夠用(即使有效)

我認為存在幾個問題,

  1. 對於 func2,我將 [height coordinates, weight coordinates, images] 列表添加到 multiprocessing。

     pixel_list2 = [[i, j, image] for i in range(height) for j in range(width)]

    在這部分中,'image' 是不必要的,因為它不是可迭代的 object。我將加載的圖像 im 更改為 [im, im, ... im],長度為 (width * height),將其用作 i 的輸入和 j 的寬度和高度坐標。 圖像被不必要地復制到列表中。

    我想將其更改為帶有圖像的可迭代像素坐標。 喜歡

    t = p.starmap(func2, pixel_list, # not pixel_list2 image # 'an image' )
  2. 因為我保存了 p.starmap 的結果,它總是有值,即使它不應該有。

     list2 = [tt for tt in t if tt is not None]

    如果我不使用這句話,p.starmap 的原始結果為“無”。

這句話可以省略嗎? 如果像素不是白色,就不是 append 'nothing'。

通過使用 numpy 的本機矢量化函數,這可能會快幾個數量級(並且更簡單):

# find pixels that have 255 for all color values
white_mask = np.all(image == [255, 255, 255], axis=-1)
# get the indices of those pixels
white_pixels = np.argwhere(white_mask)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM