【问题标题】:Compare current pixel value with the previous one on numpy array将当前像素值与 numpy 数组上的前一个像素值进行比较
【发布时间】:2014-02-27 19:53:51
【问题描述】:

是否可以在 numpy 数组中实现此图像过滤过程?我需要检查上一列和上一行中的像素是否与当前像素不同。

width, height = orig_bin.size
pixels = orig_bin.load()

delta = 50
begin = 10
min_w = 30
max_w = 260
min_h = 10
max_h = 40

w_range = range(begin, width - min_w - delta)
h_range = range(begin, height - min_h - delta)

is_changing = False
for x in w_range:
    for y in h_range:
        change_pixel = False
        current_pixel = pixels[x,y]
        if current_pixel != pixels[x, y+1]:
            change_pixel = True

        if current_pixel != pixels[x+1, y]:
            change_pixel = True

        if change_pixel:
            pixels[x,y] = (0,0,0)
        else:
            pixels[x,y] = (255,255,255)

最好的问候, 埃米利奥

【问题讨论】:

  • 此实现是否存在问题,或者您是否正在寻求优化?这里具体有什么问题?

标签: python arrays image numpy


【解决方案1】:

这是一种方法。发example image

你没有说你的orig_bin来自哪里,所以我用了scipy.misc.imread

from scipy.misc import imread, imsave
img = imread('input.png')

首先,为不同于上面像素的像素创建一个遮罩(这使用了来自Bi Rico's answer的想法):

up   = (img[1:,1:] != img[:-1,1:]).any(axis=2)

请注意,imread 以行优先顺序加载图像,因此第一个 NumPy 轴是垂直轴。解释见“Multidimensional Array Indexing Order Issues”。

同样,为与左侧像素不同的像素创建蒙版:

left = (img[1:,1:] != img[1:,:-1]).any(axis=2)

组合这些以获得与上方或左侧像素不同的像素的掩码:

mask = numpy.zeros(img.shape[:2], dtype=bool)
mask[1:,1:] = left | up

创建大小合适的黑色输出图像;然后将蒙版设置为白色:

output = numpy.zeros(img.shape)
output[mask] = (255, 255, 255)
imsave('output.png', output)

结果如下:

或者如果您希望颜色相反,请反转遮罩:

output[~mask] = (255, 255, 255)

【讨论】:

  • 好地方!固定的;我采纳了你计算更小的掩码的想法。
  • Gareth Rees,可以反转颜色吗?蒙版使用(0,0,0),颜色填充255,255,255 ?
【解决方案2】:

你想要这样的东西:

change = (pixels[1:, 1:] != pixels[1:, :-1]) | (pixels[1:, 1:] != pixels[:-1, 1:])

这将是二进制(真,假),如果您希望结果为 0/255,则需要将其乘以 255。如果您的数组是 (x, y, 3),您可能还需要在最后一维上运行和 any。

还有其他方法可以重新解决这个问题,例如,使用 [1, -1] 的卷积可能会帮助您解决大部分问题。

【讨论】:

  • 当我尝试这个时我得到ValueError: operands could not be broadcast together
  • @GarethRees,| 的左侧和右侧应该具有相同的形状。我已经解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2022-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多