Average of image masks in OpenCV

Question:

Currently I have a variable number of np.ndarray‘s that represent image masks of the same size. The values in the arrays are either 255 or 0. Now I want to be able to get an average of all of these arrays. I currently have the code:

mask = np.mean(masks).astype(int)
mask[mask > 169] = 255

masks is a list of np.ndarray‘s of the size (296, 640). But I get the error:

TypeError: 'numpy.int64' object does not support item assignment
Asked By: SDG

||

Answers:

You are taking the overall mean of the masks over all axis which reduces it into a single scaler value (object type int64). You want to take the average over axis=0 since you have them contained in a list to retain the Height and Width of the masks into a single average mask.

mask1 = np.random.randint(0,255,(296, 640))
mask2 = np.random.randint(0,255,(296, 640))
mask3 = np.random.randint(0,255,(296, 640))

masks = [mask1, mask2, mask3]

mask = np.mean(masks, axis=0).astype(int)
mask[mask > 169] = 255

mask.shape
(296, 640)
Answered By: Akshay Sehgal