'Python multiprocessing for loop with multiple arguments
I'm trying to get pixel coordinates of an image (only white color pixels)
Of course it is time-consuming task, I applied multiprocessing.
It works, however I am not sure that I did properly.
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]]
I come up with two methods, both of them looks like insufficient (even though it works)
I think several problems exist,
for the case of func2, I add [height coordinates, weight coordinates, images] list to multiprocessing.
pixel_list2 = [[i, j, image] for i in range(height) for j in range(width)]in this part, 'image' is unnecessary because it is not an iterable object. I change a loaded image im to [im, im, ... im] with length of (width * height), to use it as input with i and j coordinates of width and height. An image is unnecessarily copied to list.
I'd like to change it to iterable pixel coordinates with an image. like
t = p.starmap(func2, pixel_list, # not pixel_list2 image # 'an image' )because i saved the result of an p.starmap, it always have values even though it should not have.
list2 = [tt for tt in t if tt is not None]If I do not use this sentence, original result of the p.starmap has 'None'.
Is it possible to omit this sentence? just not append 'nothing' if it pixel is not white.
Solution 1:[1]
This can likely be several orders of magnitude faster (and much simpler) by using numpy's native vectorized functions:
# 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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | yut23 |
