【问题标题】:Trying to calculate the mean of a sliding window of an image Python试图计算图像 Python 的滑动窗口的平均值
【发布时间】:2018-02-11 07:33:56
【问题描述】:

我正在尝试通过计算图像上(非重叠)滑动窗口的平均值来像素化(\mosaic)图像。为此,我尝试实现“窗口大小”和“步长”参数。假设我的步骤不会超过图像边界。意味着如果我的图像是 32X32 暗度,则窗口可以是 2x2\4x4\8x8\16x16 暗度。 Here an example

我尝试寻找一些均值运算符\掩码\卷积的组合,但没有找到任何相关内容。

以下是我尝试寻找的一些示例:这些链接给出了我的问题的某些部分,但我没有找到如何将它们组合起来以实现带有跳步的滑动窗口。

Numpy 二维移动平均线,scipy.org/../scipy.signal.medfilt, GitHub上的mosaic.py和滑动窗口操作的Numpy矢量化 如何执行此滑动窗口以单独对图像的各个部分进行像素化。

【问题讨论】:

  • 您是在寻找下采样(例如this question)还是真的想要保留图像大小(例如下采样和上采样)?
  • 我不确定我是否正确理解了下采样的含义。我想将尺寸保持在原来的比例尺寸。只想移动一个非重叠窗口并将其平均值应用于图像的相应部分。然后将窗口滑动到下一部分重复。完全如我附上的图片所示。谢谢你的回答。

标签: python operator-keyword mean convolution sliding-window


【解决方案1】:

这是(我认为)您的问题的可能解决方案:

def pixelate(img, wx, wy=None):
    wy = wy or wx
    y, x = img.shape
    if x % wx != 0 or y % wy != 0:
        raise ValueError("Invalid window size.")
    ny = y // wy
    nx = x // wx
    windowed = img.reshape((ny, wy, nx, wx))
    means = windowed.mean(axis=(1, 3), keepdims=True)
    means = np.tile(means, (1, wy, 1, wx))
    result = means.reshape((y, x))
    return result

其中img 是表示图像的 2D NumPy 数组,wx 是窗口的水平尺寸,wy 是垂直尺寸(默认与 wy 相同)。图像必须能被窗口大小整除。基本上,它将图像数组重塑为其窗口,计算均值,平铺结果并重新整形。

这是一个带有圆周的示例:

import numpy as np
import matplotlib.pyplot as plt

def pixelate(img, wx, wy=None):
    wy = wy or wx
    y, x = img.shape
    if x % wx != 0 or y % wy != 0:
        raise ValueError("Invalid window size.")
    ny = y // wy
    nx = x // wx
    windowed = img.reshape((ny, wy, nx, wx))
    means = windowed.mean(axis=(1, 3), keepdims=True)
    means = np.tile(means, (1, wy, 1, wx))
    result = means.reshape((y, x))
    return result

# Build a circumference
WIDTH = 400
HEIGHT = 300
RADIUS = 100
THICKNESS = 10
xx, yy = np.meshgrid(np.arange(WIDTH) - WIDTH / 2, np.arange(HEIGHT) - HEIGHT / 2)
r = np.sqrt(np.square(xx) + np.square(yy))
circ = (r > (RADIUS - THICKNESS / 2)) & (r < (RADIUS + THICKNESS / 2))
circ = circ.astype(np.float32)

# Pixelate
WINDOW_SIZE = 20
circ_pix = pixelate(circ, WINDOW_SIZE)

# Show
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.imshow(circ, "binary")
ax2 = fig.add_subplot(122)
ax2.imshow(circ_pix, "binary")

输出:

【讨论】:

    猜你喜欢
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 2014-12-09
    • 2021-12-20
    相关资源
    最近更新 更多