Temporal median ignore zero


I am using pytorch to generate a temporal median across “n” images in an array and this works very well. But now I would like to mask out image regions I dont need to compute the median for and set these regions to zero in the image array, ie. mask.

Now I have a stacked array of images that are mostly zero values, but the pytorch median function takes same time to compute.

How do I construct a torch.median(image_array) to ignore zeros, but retain the image shape in the result. If I do torch.nonzero I get tuples and if I set as_tupples=False, pytorch says there is no such thing as “as_tupples”.

Any help would be appreciated. Image array is [1920x1080x1] by 21 frames stacked into a buffer, converted to torch tensor, then apply torch.median to the buffer. This works fine and retains shape provided I use np.array(tensor) to convert back to an image.

thanks in advance

What would be the result, if a certain pixel location contains all zeros?
You are most likely looking for as_tuple=False (note the missing s at the end).

thanks for you quick response ptrblck,

The result I am getting is,

TypeError: nonzero() got an unexpected keyword argument ‘as_tuple’

I am using PyTorch on ARM64, version 1.1.0

The as_tuple argument was introduced in 1.2.0 (docs), so you should update to the latest stable version.

Hi ptrblk,

Yes, upgrading to 1.2 fixes the missing option as_tuple, thank you for pointing this out, much appreciated.

I still have a problem with maintaining or reconstructing the result back to the original image shape. It appears that the result becomes a 1D array, whereas the original image was a 2D array.

Can you tell me what is required to reconstruct the image array from the nonzero median result [1D array].

If I do not use the torch.nonzero step, a 2D image format is preserved.

This is my test code (buffer = "stacked array of 2D images, each image has the same masked area having zero values)

buffer2 = torch.nonzero(buffer, as_tuple=False)
median = torch.median(buffer2, 0)[0] # this is a temporal median along axis 0
median2 = median.cpu()
median3 = np.array(median2)
cv2.imshow(“median”, median3)


ValueError: Image must be 2D (grayscale, RGB, or RGBA).

Regards rapidproto