I have a NumPy matrix of shape (n, height, width)
containing grayscale images in the uint8
range. Each layer (n in total) contains a prediction from a neural network. I would like to compare all n layers
and for each pixel get the second most common value and create a new matrix of shape (height, width)
with this new value. In other words, I use per-pixel voting to create a new 2D matrix from all the matrices in the layered one. I prefer the second most common value as the most common one is 3, for different reasons, and I would like to ignore this; this is why I search for the second most common value with mode(vote[vote != 3], axis=None)[0][0]
. The following is a working solution. However, it is not very fast as I have to slowly iterate. I would like to use a vectorized solution to save time.
import numpy
from scipy.stats import mode
n = 84
height = 1872
width = 3128
layered_image = numpy.ndarray(shape=(n, height , width), dtype=numpy.uint8)
image = numpy.ndarray(shape=(height , width), dtype=numpy.uint8)
for i in range(0, height):
for j in range(0, width):
vote = []
for k in range(len(layered_image)):
vote.append(layered_image[k][i][j])
vote = numpy.asarray(vote, dtype=numpy.uint8)
image[i][j] = mode(vote[vote != 3], axis=None)[0][0]
Thank you for any suggestions.