简体   繁体   中英

Python image convolution with numpy slices produces strange results on some images

I'm trying to implement a convolution in a plugin in GIMP using Numpy, and I'm getting some strange results.

The function giving me problems is this one: (It is only operating on a grayscale image)

def convolve(self, pixels, kernel):
  bw, bh = pixels.shape
  k_w, k_h = kernel.shape
  if (k_w != k_h):
    raise ValueError("Passed kernel is not of the right shape")

  #expand the image
  bigger = np.lib.pad(pixels, int(k_w/2), 'reflect').astype(np.float)

  pixels.fill(0)
  pixels = pixels.astype(np.float)
  for x in range(k_w):
    for y in range(k_h):
      pixels += kernel[x,y]*bigger[x : bw + x,
                                   y : bh + y]
  return np.clip(pixels,0,255).astype(np.uint8)

Somehow, for some image sizes the output gets all messed up. Specific example can be when applying a 5x5 gaussian blur on this image:

Input:输入

Incorrect output:错误的输出

The strangest thing about this is that for a lot of images - especially square ones - the plugin works fine. For example, if I expand the Image manually in GIMP to be a square I get a correctly blurred image:

正确的输出

I've tried resizing the numpy array to be a square and then cropping it back, but that surprisingly didn't fix the issue.

EDIT: currently running the code like this:

self.convolve(pixels,
              np.array([
              [ 1, 4, 6, 4, 1,],
              [ 4,16,24,16, 4,],
              [ 6,24,36,24, 6,],
              [ 4,16,24,16, 4,],
              [ 1, 4, 6, 4, 1,],
              ], dtype=np.float)*1/256)

But the same issue can be seen with any 3x3 filter, where kernels such as this work fine

[  0, 0,   0,],
[0.5, 0, 0.5,],
[  0, 0,   0,],

and kernels such as this create the strange issue:

[ 0, 0.5, 0,],
[ 0,   0, 0,],
[ 0, 0.5, 0,],

Found the issue! The problem was caused by incorrectly parsing the data from GIMP to the numpy array. Accidentaly swapped the dimensions of the array and it caused some strange behavior for filters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM