【问题标题】:Find median of list of images查找图像列表的中位数
【发布时间】:2016-09-23 11:43:51
【问题描述】:

如果我有一个由 3D ndarray 表示的图像列表,例如[[x,y,color],...],我可以使用哪些操作来输出具有所有值中值的图像?我正在使用 for 循环,发现它太慢了。

【问题讨论】:

  • 分享产生预期结果的循环实现?

标签: image python-2.7 opencv numpy image-processing


【解决方案1】:

这是我使用NumPy的矢量化实现:

在我的测试中,我使用了这五张图片:

相关部分:

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)

完整的脚本:

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()

五张图片的中位数 (numpy.median) 结果如下所示:

有趣的部分:平均 (numpy.mean) 结果如下所示:

好吧,科学遇上艺术。 :-)

【讨论】:

    【解决方案2】:

    您说您的图像是彩色的,格式为 3d ndarrays 列表。假设有n 图片:

    imgs = [img_1, ..., img_n]
    

    imgs 是一个list,每个img_i 是一个ndarray,形状为(nrows, ncols, 3)

    将列表转换为 4d ndarray,然后在对应于图像的维度上取中值:

    import numpy as np
    
    # Convert images to 4d ndarray, size(n, nrows, ncols, 3)
    imgs = np.asarray(imgs)
    
    # Take the median over the first dim
    med = np.median(imgs, axis=0)
    

    这给出了按像素计算的中位数。每个像素的每个颜色通道的值是所有图像中相应像素/通道的中位数。

    asarray() 的文档说“如果输入已经是 ndarray,则不执行复制”。这表明如果您将原始图像列表存储为 4d ndarray 而不是列表,则操作会更快。在这种情况下,不需要复制内存中的信息(或运行asarray()

    【讨论】:

    • 谢谢!我之前尝试过axis = 0,但它不起作用。再次尝试,代码np.median(imgs, axis=0) 简单且有效。
    【解决方案3】:

    你能举一个你的数据的例子吗?

    否则,我认为您可以将 numpy 与 numpy.mean 一起使用?

    你有文档here ;)

    【讨论】:

    • OP 明确要求中位数不是均值。
    猜你喜欢
    • 1970-01-01
    • 2014-07-28
    • 2017-06-29
    • 2011-02-15
    • 2021-02-21
    • 2011-07-03
    • 2016-11-23
    • 1970-01-01
    • 2017-06-29
    相关资源
    最近更新 更多