【问题标题】:Convolve an RGB image with a custon neighbout kernel using Python and Numpy使用 Python 和 Numpy 将 RGB 图像与自定义邻居内核卷积
【发布时间】:2013-09-26 04:28:08
【问题描述】:

我正在尝试实现一种算法来验证 RGB 图像的 4 个相邻像素(上、下、左和右),如果所有像素 RGB 值都相等,我将输出图像中的一个像素标记为 1,否则它将为 0。非矢量化实现是:

def set_border_interior(img):
  img_rows = img.shape[0]
  img_cols = img.shape[1]
  res = np.zeros((img_rows,img_cols))
  for row in xrange(1,img_rows-1):
      for col in xrange(1,img_cols-1):
          data_b = set()
          data_g = set()
          data_r = set()
          up = row - 1
          down = row + 1
          left = col - 1
          right = col + 1

          data_b.add(img.item(row,col,0))
          data_g.add(img.item(row,col,1))
          data_r.add(img.item(row,col,2))

          data_b.add(img.item(up,col,0))
          data_g.add(img.item(up,col,1))
          data_r.add(img.item(up,col,2))

          data_b.add(img.item(down,col,0))
          data_g.add(img.item(down,col,1))
          data_r.add(img.item(down,col,2))

          data_b.add(img.item(row,left,0))
          data_g.add(img.item(row,left,1))
          data_r.add(img.item(row,left,2))

          data_b.add(img.item(row,right,0))
          data_g.add(img.item(row,right,1))
          data_r.add(img.item(row,right,2))

          if (len(data_b) == 1) and (len(data_g) == 1) and (len(data_r) == 1):
              res.itemset(row,col, False)
          else:
              res.itemset(row,col, True)
  return res

这种非向量化的方式,但是真的很慢(甚至使用 img.item 读取数据和 img.itemset 设置新值)。有没有更好的方法在 Numpy(或 scipy)中实现这一点?

【问题讨论】:

    标签: python image numpy scipy


    【解决方案1】:

    把边界放在一边,你的功能没有很好地定义,你可以做以下事情:

    import numpy as np
    import matplotlib.pyplot as plt
    
    rows, cols = 480, 640
    rgb_img = np.zeros((rows, cols, 3), dtype=np.uint8)
    
    rgb_img[:rows//2, :cols//2] = 255
    
    center_slice = rgb_img[1:-1, 1:-1]
    left_slice = rgb_img[1:-1, :-2]
    right_slice = rgb_img[1:-1, 2:]
    up_slice = rgb_img[:-2, 1:-1]
    down_slice = rgb_img[2:, 1:-1]
    
    all_equal = (np.all(center_slice == left_slice, axis=-1) &
                 np.all(center_slice == right_slice, axis=-1) &
                 np.all(center_slice == up_slice, axis=-1) &
                 np.all(center_slice == down_slice, axis=-1))
    
    plt.subplot(211)
    plt.imshow(rgb_img, interpolation='nearest')
    plt.subplot(212)
    plt.imshow(all_equal, interpolation='nearest')
    plt.show()
    

    【讨论】:

    • 感谢您的快速回答!在我的函数中,我从第 1 行开始,以 height-1 结束,从 col 1 开始,直到 width-1。如何使用切片设置此边界?
    • 这基本上就是上面的代码所做的:返回的all_equal数组在两个方向上都短了两个,缺少第一个(索引0)和最后一个(索引n-1),其中我相信你的做法是一样的。
    猜你喜欢
    • 1970-01-01
    • 2021-02-11
    • 2019-09-29
    • 2018-11-11
    • 2019-08-28
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    相关资源
    最近更新 更多