Trying to calculate the mean of a sliding window of an image Python

匿名 (未验证) 提交于 2019-12-03 09:05:37

问题:

I'm trying to pixelate (\mosaic) an image by calculate the mean of a (non overlap) sliding window over the image. For this I try to implement a "window size" and a "step" parameters. Assuming my step won't exceed the image border. Means that if my image is a 32X32 dims the window can be 2x2\4x4\8x8\16x16 dims. Here an example

I try to look for some combinations of mean operator\mask\convolution but didn't find anything relevant.

Here some examples of what iI try to look for: Those links gave some parts of my question but iI didn't find out how to combine them in order to implement a sliding window with step skipping.

Numpy Two-Dimensional Moving Average, scipy.org/../scipy.signal.medfilt, mosaic.py on GitHub and Numpy Vectorization of sliding-window operation How to do this sliding window in order to pixelate parts of an image seperatly.

回答1:

Here is (I think) a possible solution to your problem:

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 

Where img is a 2D NumPy array representing an image, wx is the horizontal size of the window and wy the vertical size (which defaults to the same as wy). The image must be divisible by the window size. Basically it reshapes the image array to its windows, computes the means, tiles the result and reshapes back.

Here is an example with a circumference:

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

Output:



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!