简体   繁体   English

Python 图像卷积与 numpy 切片在某些图像上产生奇怪的结果

[英]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.我正在尝试使用 Numpy 在 GIMP 的插件中实现卷积,但得到了一些奇怪的结果。

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:具体示例可以是在此图像上应用 5x5 高斯模糊时:

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:例如,如果我在 GIMP 中手动将图像扩展为正方形,则会得到正确模糊的图像:

正确的输出

I've tried resizing the numpy array to be a square and then cropping it back, but that surprisingly didn't fix the issue.我已经尝试将 numpy 数组的大小调整为一个正方形,然后将其裁剪回来,但令人惊讶的是,这并没有解决问题。

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但是对于任何 3x3 过滤器都可以看到同样的问题,像这样的内核可以正常工作

[  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.该问题是由于错误地将数据从 GIMP 解析到 numpy 数组而引起的。 Accidentaly swapped the dimensions of the array and it caused some strange behavior for filters.不小心交换了数组的维度,导致过滤器出现了一些奇怪的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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