Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find median of list of images

If I have a list of images represented by 3D ndarray such as [[x,y,color],...], what operations can I use to output an image with values that are median of all values? I am using a for loop and find it too slow.

like image 450
ferk86 Avatar asked May 25 '16 17:05

ferk86


People also ask

How do you find the median of a list?

Median Example The median is the number in the middle {2, 3, 11, 13, 26, 34, 47}, which in this instance is 13 since there are three numbers on either side. To find the median value in a list with an even amount of numbers, one must determine the middle pair, add them, and divide by two.

How do you find the median of a picture?

The median is calculated by first sorting all the pixel values from the surrounding neighborhood into numerical order and then replacing the pixel being considered with the middle pixel value.

What is median NumPy?

3. Usage of NumPy median() Function. The numpy. median() function in the NumPy library is used to calculate the median value along with the specified axis of single-dimensional as-well as multi-dimensional array. This function returns the median value of the array as an output.


1 Answers

This is my vectorized implementation using NumPy:

For my test I used these five images:

enter image description here

The relevant parts:

import numpy as np
import scipy.ndimage

# Load five images:
ims = [scipy.ndimage.imread(str(i + 1) + '.png', flatten=True) for i in range(5)]
# Stack the reshaped images (rows) vertically:
ims = np.vstack([im.reshape(1,im.shape[0] * im.shape[1]) for im in ims])
# Compute the median column by column and reshape to the original shape:
median = np.median(ims, axis=0).reshape(100, 100)

The complete script:

import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt

ims = [scipy.ndimage.imread(str(i + 1) + '.png', flatten=True) for i in range(5)]
print ims[0].shape # (100, 100)

ims = np.vstack([im.reshape(1,im.shape[0] * im.shape[1]) for im in ims])
print ims.shape # (5, 10000)

median = np.median(ims, axis=0).reshape(100, 100)

fig = plt.figure(figsize=(100./109., 100./109.), dpi=109, frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')
plt.imshow(median, cmap='Greys_r')
plt.show()

The median (numpy.median) result of the five images looks like this:

enter image description here

Fun part: The mean (numpy.mean) result looks like this:

enter image description here

Okay, science meets art. :-)

like image 71
Darius Avatar answered Sep 21 '22 12:09

Darius